@seanhogg/builderforce-webcontainers-core 2026.10.12 → 2026.10.13

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.
Files changed (185) hide show
  1. package/dist/archive.d.ts +25 -2
  2. package/dist/archive.d.ts.map +1 -1
  3. package/dist/archive.js +45 -6
  4. package/dist/archive.js.map +1 -1
  5. package/dist/attribution.js.map +1 -1
  6. package/dist/check/acquire.js.map +1 -1
  7. package/dist/check/typeStore.d.ts.map +1 -1
  8. package/dist/compileScript.js.map +1 -1
  9. package/dist/devServer.d.ts +2 -0
  10. package/dist/devServer.d.ts.map +1 -1
  11. package/dist/devServer.js +2 -2
  12. package/dist/devServer.js.map +1 -1
  13. package/dist/hot/moduleGraph.d.ts.map +1 -1
  14. package/dist/html.d.ts +5 -2
  15. package/dist/html.d.ts.map +1 -1
  16. package/dist/html.js +9 -7
  17. package/dist/html.js.map +1 -1
  18. package/dist/index.d.ts +3 -3
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +2 -2
  21. package/dist/index.js.map +1 -1
  22. package/dist/installer/npmrc.js.map +1 -1
  23. package/dist/installer/registry.d.ts.map +1 -1
  24. package/dist/installer/registry.js.map +1 -1
  25. package/dist/installer/semver.js.map +1 -1
  26. package/dist/installer/tree.d.ts +2 -2
  27. package/dist/installer/tree.d.ts.map +1 -1
  28. package/dist/node/assert.d.ts.map +1 -1
  29. package/dist/node/buffer.d.ts.map +1 -1
  30. package/dist/node/buffer.js.map +1 -1
  31. package/dist/node/callable.js.map +1 -1
  32. package/dist/node/crypto.d.ts.map +1 -1
  33. package/dist/node/crypto.js +6 -2
  34. package/dist/node/crypto.js.map +1 -1
  35. package/dist/node/events.d.ts.map +1 -1
  36. package/dist/node/events.js.map +1 -1
  37. package/dist/node/fs/index.js.map +1 -1
  38. package/dist/node/fs/stats.d.ts.map +1 -1
  39. package/dist/node/fs/stats.js.map +1 -1
  40. package/dist/node/fs/sync.d.ts +1 -1
  41. package/dist/node/fs/sync.d.ts.map +1 -1
  42. package/dist/node/fs/sync.js.map +1 -1
  43. package/dist/node/http/client.d.ts.map +1 -1
  44. package/dist/node/http/client.js.map +1 -1
  45. package/dist/node/http/index.js.map +1 -1
  46. package/dist/node/http/messages.d.ts.map +1 -1
  47. package/dist/node/http/messages.js.map +1 -1
  48. package/dist/node/http/server.d.ts.map +1 -1
  49. package/dist/node/http/server.js +10 -1
  50. package/dist/node/http/server.js.map +1 -1
  51. package/dist/node/http/serverResponse.d.ts +2 -1
  52. package/dist/node/http/serverResponse.d.ts.map +1 -1
  53. package/dist/node/http/serverResponse.js +4 -2
  54. package/dist/node/http/serverResponse.js.map +1 -1
  55. package/dist/node/http/upgradeSocket.d.ts.map +1 -1
  56. package/dist/node/http/upgradeSocket.js.map +1 -1
  57. package/dist/node/inspect.d.ts +2 -2
  58. package/dist/node/inspect.d.ts.map +1 -1
  59. package/dist/node/inspect.js.map +1 -1
  60. package/dist/node/loader.d.ts.map +1 -1
  61. package/dist/node/loader.js.map +1 -1
  62. package/dist/node/loop.d.ts.map +1 -1
  63. package/dist/node/loop.js.map +1 -1
  64. package/dist/node/misc.js.map +1 -1
  65. package/dist/node/process.js.map +1 -1
  66. package/dist/node/processExit.d.ts.map +1 -1
  67. package/dist/node/processExit.js.map +1 -1
  68. package/dist/node/readline.js.map +1 -1
  69. package/dist/node/resolve.d.ts +2 -2
  70. package/dist/node/resolve.d.ts.map +1 -1
  71. package/dist/node/runtime.d.ts.map +1 -1
  72. package/dist/node/runtime.js +2 -2
  73. package/dist/node/runtime.js.map +1 -1
  74. package/dist/node/stream/index.d.ts.map +1 -1
  75. package/dist/node/stream/index.js.map +1 -1
  76. package/dist/node/stream/readable.d.ts.map +1 -1
  77. package/dist/node/stream/readable.js.map +1 -1
  78. package/dist/node/stream/writable.d.ts.map +1 -1
  79. package/dist/node/stream/writable.js.map +1 -1
  80. package/dist/node/util.d.ts +2 -2
  81. package/dist/node/util.d.ts.map +1 -1
  82. package/dist/node/util.js.map +1 -1
  83. package/dist/node/wasi/abi.d.ts.map +1 -1
  84. package/dist/node/wasi/abi.js.map +1 -1
  85. package/dist/node/wasi/files.d.ts.map +1 -1
  86. package/dist/node/wasi/index.js.map +1 -1
  87. package/dist/node/workerThreads.js.map +1 -1
  88. package/dist/packageCdn.js.map +1 -1
  89. package/dist/previewBridge.d.ts +15 -3
  90. package/dist/previewBridge.d.ts.map +1 -1
  91. package/dist/previewBridge.js +30 -8
  92. package/dist/previewBridge.js.map +1 -1
  93. package/dist/projectConfig.d.ts +1 -1
  94. package/dist/projectConfig.d.ts.map +1 -1
  95. package/dist/projectConfig.js.map +1 -1
  96. package/dist/resolve.d.ts +1 -1
  97. package/dist/resolve.d.ts.map +1 -1
  98. package/dist/rootedFs.d.ts +7 -0
  99. package/dist/rootedFs.d.ts.map +1 -1
  100. package/dist/rootedFs.js +22 -2
  101. package/dist/rootedFs.js.map +1 -1
  102. package/dist/shell/builtins.d.ts +3 -0
  103. package/dist/shell/builtins.d.ts.map +1 -1
  104. package/dist/shell/builtins.js +4 -4
  105. package/dist/shell/builtins.js.map +1 -1
  106. package/dist/shell/compound.js.map +1 -1
  107. package/dist/shell/context.js.map +1 -1
  108. package/dist/shell/exec.d.ts +11 -1
  109. package/dist/shell/exec.d.ts.map +1 -1
  110. package/dist/shell/exec.js +47 -13
  111. package/dist/shell/exec.js.map +1 -1
  112. package/dist/shell/expand.js.map +1 -1
  113. package/dist/shell/lineEditor.d.ts.map +1 -1
  114. package/dist/shell/lineEditor.js.map +1 -1
  115. package/dist/shell/npm.d.ts.map +1 -1
  116. package/dist/shell/npm.js +3 -0
  117. package/dist/shell/npm.js.map +1 -1
  118. package/dist/shell/options.d.ts +37 -0
  119. package/dist/shell/options.d.ts.map +1 -0
  120. package/dist/shell/options.js +86 -0
  121. package/dist/shell/options.js.map +1 -0
  122. package/dist/shell/packageManagers.d.ts +2 -2
  123. package/dist/shell/packageManagers.d.ts.map +1 -1
  124. package/dist/shell/parse.js.map +1 -1
  125. package/dist/shell/program.d.ts +4 -0
  126. package/dist/shell/program.d.ts.map +1 -1
  127. package/dist/shell/program.js +20 -8
  128. package/dist/shell/program.js.map +1 -1
  129. package/dist/shell/testCommand.js.map +1 -1
  130. package/dist/shell/textCommands.d.ts.map +1 -1
  131. package/dist/shell/textCommands.js +3 -1
  132. package/dist/shell/textCommands.js.map +1 -1
  133. package/dist/shell/tokenize.d.ts.map +1 -1
  134. package/dist/shell/tokenize.js.map +1 -1
  135. package/dist/styles/imports.d.ts.map +1 -1
  136. package/dist/system/commands.d.ts +1 -1
  137. package/dist/system/commands.d.ts.map +1 -1
  138. package/dist/system/cookieJar.d.ts.map +1 -1
  139. package/dist/system/httpStream.d.ts +16 -4
  140. package/dist/system/httpStream.d.ts.map +1 -1
  141. package/dist/system/httpStream.js +25 -3
  142. package/dist/system/httpStream.js.map +1 -1
  143. package/dist/system/index.d.ts +1 -0
  144. package/dist/system/index.d.ts.map +1 -1
  145. package/dist/system/index.js +1 -0
  146. package/dist/system/index.js.map +1 -1
  147. package/dist/system/ipc.js.map +1 -1
  148. package/dist/system/kernel.d.ts.map +1 -1
  149. package/dist/system/kernel.js.map +1 -1
  150. package/dist/system/ports.d.ts.map +1 -1
  151. package/dist/system/process.js.map +1 -1
  152. package/dist/system/serverEvents.d.ts.map +1 -1
  153. package/dist/system/signals.d.ts +26 -0
  154. package/dist/system/signals.d.ts.map +1 -0
  155. package/dist/system/signals.js +36 -0
  156. package/dist/system/signals.js.map +1 -0
  157. package/dist/system/terminal.d.ts +13 -1
  158. package/dist/system/terminal.d.ts.map +1 -1
  159. package/dist/system/terminal.js +49 -0
  160. package/dist/system/terminal.js.map +1 -1
  161. package/dist/system/webSocketFrames.d.ts.map +1 -1
  162. package/dist/system/webSocketFrames.js.map +1 -1
  163. package/dist/vfs.d.ts.map +1 -1
  164. package/dist/vfs.js.map +1 -1
  165. package/package.json +6 -5
  166. package/src/archive.ts +46 -6
  167. package/src/devServer.ts +4 -2
  168. package/src/html.ts +11 -7
  169. package/src/index.ts +3 -3
  170. package/src/node/crypto.ts +6 -1
  171. package/src/node/http/server.ts +9 -1
  172. package/src/node/http/serverResponse.ts +5 -3
  173. package/src/node/runtime.ts +2 -3
  174. package/src/previewBridge.ts +31 -9
  175. package/src/rootedFs.ts +21 -2
  176. package/src/shell/builtins.ts +6 -4
  177. package/src/shell/exec.ts +48 -12
  178. package/src/shell/npm.ts +2 -0
  179. package/src/shell/options.ts +104 -0
  180. package/src/shell/program.ts +20 -8
  181. package/src/shell/textCommands.ts +3 -1
  182. package/src/system/httpStream.ts +42 -11
  183. package/src/system/index.ts +1 -0
  184. package/src/system/signals.ts +39 -0
  185. package/src/system/terminal.ts +51 -1
@@ -11,6 +11,7 @@ import { basename, clear, dirname, echo, env, falseCommand, grep, head, printf,
11
11
  import { bracket, test } from './testCommand.js';
12
12
  import { readLine } from './lineReader.js';
13
13
  import type { Flow } from './compound.js';
14
+ import { setBuiltin, type ShellSettings } from './options.js';
14
15
 
15
16
  /** A command started with `&`. */
16
17
  export interface BackgroundJob {
@@ -30,6 +31,8 @@ export interface ShellState {
30
31
  flow?: Flow;
31
32
  /** `$1…`, `$@`; a function call swaps them for its arguments. */
32
33
  positional: string[];
34
+ /** `set -o` options (pipefail). */
35
+ readonly settings: ShellSettings;
33
36
  readonly functions: ReadonlyMap<string, unknown>;
34
37
  readonly jobs: ReadonlyMap<number, BackgroundJob>;
35
38
  /** One frame per running function (for `local`). */
@@ -54,7 +57,8 @@ export const SYSTEM_PROGRAMS = ['node', 'npm', 'npx', 'pnpm', 'yarn', 'bfsh', 's
54
57
  const HELP = `bfsh — BuilderForce WebContainers shell
55
58
 
56
59
  Builtins: cd, pwd, export, unset, exit, source, history, type, which, help,
57
- read, local, shift, return, break, continue, jobs, wait
60
+ read, local, shift, return, break, continue, jobs, wait,
61
+ set -o|+o pipefail (on by default), set -- args
58
62
  Files: ls [-la], cat, mkdir [-p], rm [-rf], cp [-r], mv, touch, test / [ … ]
59
63
  Text: echo, printf, head, tail, grep, wc, env, clear, sleep, basename, dirname
60
64
  Node: node <file>, npm install|ci|run|start|test, npx <bin>, pnpm, yarn
@@ -65,6 +69,7 @@ const HELP = `bfsh — BuilderForce WebContainers shell
65
69
  `;
66
70
 
67
71
  export const BUILTINS: Record<string, Builtin> = {
72
+ set: setBuiltin,
68
73
  async cd(ctx, shell) {
69
74
  const home = shell.env.HOME && ctx.fs.isDirectory(shell.env.HOME) ? shell.env.HOME : '/';
70
75
  const target = ctx.args[0] === '-' ? shell.env.OLDPWD ?? shell.cwd : ctx.args[0] ?? home;
@@ -154,9 +159,6 @@ export const BUILTINS: Record<string, Builtin> = {
154
159
  }
155
160
  return status;
156
161
  },
157
- async set() {
158
- return 0; // options (-e, -x) are accepted and ignored
159
- },
160
162
  async break(ctx, shell) {
161
163
  return loopControl(ctx, shell, 'break');
162
164
  },
package/src/shell/exec.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * The executor: runs a parsed script. Lists honour `&&`/`||`/`;`/`&`; pipeline
3
3
  * stages run concurrently, joined by in-memory pipes, and a pipeline's status is
4
- * the rightmost non-zero stage (pipefail) — not only the last stage. Redirects
4
+ * the rightmost non-zero stage (pipefail, on by default; `set +o pipefail` gives
5
+ * the POSIX last-stage status). A stage writing to a pipe whose reader is gone
6
+ * stops with EPIPE (SIGPIPE's status, 141) instead of buffering forever. Redirects
5
7
  * (here-documents included) swap a stage's stdin/stdout/stderr. Compound
6
8
  * commands run through compound.ts. Dispatch order per simple command: shell
7
9
  * functions, builtins,
@@ -11,6 +13,7 @@
11
13
  */
12
14
  import type { System } from '../system/types.js';
13
15
  import { InputQueue, textChunks } from '../system/terminal.js';
16
+ import { SIGPIPE_STATUS, brokePipe, isBrokenPipe } from '../system/signals.js';
14
17
  import type { Command as CommandNode, FunctionDefinition, Pipeline, Redirect, Script, SimpleCommand, Word } from './ast.js';
15
18
  import { parse, ShellSyntaxError } from './parse.js';
16
19
  import { expandWord, expandWords, type ExpandContext } from './expand.js';
@@ -18,6 +21,7 @@ import { BUILTINS, COREUTILS, type BackgroundJob, type ShellState } from './buil
18
21
  import { resolvePath, type CommandContext } from './context.js';
19
22
  import { devServerHandoff, runDevServerHandoff } from './devHandoff.js';
20
23
  import { runCompound, type Flow, type ScriptRunner } from './compound.js';
24
+ import { DEFAULT_SHELL_SETTINGS, pipelineStatus, type ShellSettings } from './options.js';
21
25
 
22
26
  export interface ShellIO {
23
27
  stdout(text: string): void;
@@ -46,6 +50,12 @@ export interface ShellOptions {
46
50
  commands?: Record<string, ShellCommand>;
47
51
  /** Functions inherited from a parent shell (subshells and `$(…)`). */
48
52
  functions?: Map<string, FunctionDefinition>;
53
+ /**
54
+ * Fail a pipeline when any stage fails (status: the rightmost non-zero).
55
+ * Default true; false is POSIX (the last stage's status). Scripts switch it
56
+ * with `set -o pipefail` / `set +o pipefail`.
57
+ */
58
+ pipefail?: boolean;
49
59
  }
50
60
 
51
61
  let nextShellPid = 500;
@@ -59,6 +69,7 @@ export class Shell implements ShellState, ScriptRunner {
59
69
  flow?: Flow;
60
70
  positional: string[];
61
71
  readonly functions: Map<string, FunctionDefinition>;
72
+ readonly settings: ShellSettings;
62
73
  readonly jobs = new Map<number, BackgroundJob>();
63
74
  /** One frame per running function: names declared `local`, with the value to restore. */
64
75
  readonly localFrames: Array<Map<string, string | undefined>> = [];
@@ -73,11 +84,12 @@ export class Shell implements ShellState, ScriptRunner {
73
84
  this.env = { ...options.env, PWD: options.cwd };
74
85
  this.positional = [...(options.positional ?? [])];
75
86
  this.functions = new Map(options.functions);
87
+ this.settings = { ...DEFAULT_SHELL_SETTINGS, pipefail: options.pipefail ?? DEFAULT_SHELL_SETTINGS.pipefail };
76
88
  }
77
89
 
78
90
  /** A child shell for `npm run` / subshells: same IO, its own cwd, environment and functions. */
79
91
  fork(overrides: { cwd?: string; env?: Record<string, string>; positional?: string[] }): Shell {
80
- return new Shell({ ...this.options, cwd: overrides.cwd ?? this.cwd, env: { ...this.env, ...overrides.env }, positional: overrides.positional ?? this.positional, functions: this.functions });
92
+ return new Shell({ ...this.options, cwd: overrides.cwd ?? this.cwd, env: { ...this.env, ...overrides.env }, positional: overrides.positional ?? this.positional, functions: this.functions, pipefail: this.settings.pipefail });
81
93
  }
82
94
 
83
95
  subshell(): Shell {
@@ -170,23 +182,32 @@ export class Shell implements ShellState, ScriptRunner {
170
182
  private async runPipeline(pipeline: Pipeline, io: ShellIO, input: JobInput, signal: AbortSignal): Promise<number> {
171
183
  const count = pipeline.commands.length;
172
184
  const pipes = Array.from({ length: count - 1 }, () => new InputQueue());
173
- const statuses = await Promise.all(
185
+ // Every stage settles before the pipeline does: none is left running detached.
186
+ const settled = await Promise.allSettled(
174
187
  pipeline.commands.map(async (command, i) => {
175
188
  const stdin: JobInput = i === 0 ? input : { queue: pipes[i - 1]! };
176
189
  const stdout = i === count - 1 ? io.stdout : (text: string) => pipes[i]!.push(text);
177
190
  const stageIO: ShellIO = { stdout, stderr: io.stderr, isTerminal: io.isTerminal && i === count - 1 };
178
191
  try {
179
192
  return await this.runCommand(command, stageIO, stdin, signal, count === 1);
193
+ } catch (error) {
194
+ // Its own pipe broke (the reader exited): SIGPIPE ends the stage. An enclosing
195
+ // pipeline's pipe is not its to absorb: that travels on, ending loops on the way.
196
+ if (i < count - 1 && brokePipe(error, pipes[i]!)) return SIGPIPE_STATUS;
197
+ throw error;
180
198
  } finally {
181
199
  if (i < count - 1) pipes[i]!.push(null);
200
+ if (i > 0) pipes[i - 1]!.closeReader(); // its reader is gone: the writer upstream gets EPIPE
182
201
  }
183
202
  }),
184
203
  );
185
- // pipefail: any non-zero stage fails the pipeline. The status is the rightmost
186
- // non-zero, so `build 2>&1 | tail` reports the build rather than tail's 0.
187
- // A one-stage pipeline (a non-pipeline command) is unchanged.
188
- let status = 0;
189
- for (const stage of statuses) if (stage !== 0) status = stage;
204
+ const failed = settled.find((stage): stage is PromiseRejectedResult => stage.status === 'rejected');
205
+ if (failed) throw failed.reason;
206
+ const statuses = settled.map((stage) => (stage as PromiseFulfilledResult<number>).value);
207
+ // pipefail (the default): any non-zero stage fails the pipeline, the status the
208
+ // rightmost non-zero, so `build 2>&1 | tail` reports the build rather than tail's 0.
209
+ // A one-stage pipeline (a non-pipeline command) is the same either way.
210
+ const status = pipelineStatus(statuses, this.settings);
190
211
  return pipeline.negate ? (status === 0 ? 1 : 0) : status;
191
212
  }
192
213
 
@@ -337,9 +358,22 @@ export class Shell implements ShellState, ScriptRunner {
337
358
  io.stderr(`bfsh: command not found: ${name}\n`);
338
359
  return 127;
339
360
  }
340
- // The shell's own IO is text; a child's bytes are decoded as they enter it.
341
- child.onStdout(textChunks((text) => text !== null && io.stdout(text)));
342
- child.onStderr(textChunks((text) => text !== null && io.stderr(text)));
361
+ // The shell's own IO is text; a child's bytes are decoded as they enter it. Writing into
362
+ // a pipe whose reader has exited kills the child with SIGPIPE (its timers stop with it),
363
+ // then raises the break here, so the stage owning the pipe ends — a loop around it too.
364
+ let brokenPipe: unknown;
365
+ const relay = (write: (text: string) => void) => (text: string | null) => {
366
+ if (text === null || brokenPipe !== undefined) return;
367
+ try {
368
+ write(text);
369
+ } catch (error) {
370
+ if (!isBrokenPipe(error)) throw error;
371
+ brokenPipe = error;
372
+ child.kill('SIGPIPE');
373
+ }
374
+ };
375
+ child.onStdout(textChunks(relay(io.stdout)));
376
+ child.onStderr(textChunks(relay(io.stderr)));
343
377
  let stop: (() => void) | undefined;
344
378
  if (size && input.setRawSink) input.setRawSink((data) => child.write(data));
345
379
  else stop = input.queue.subscribe((chunk) => (chunk === null ? child.closeStdin() : child.write(chunk)));
@@ -347,7 +381,9 @@ export class Shell implements ShellState, ScriptRunner {
347
381
  if (signal.aborted) onAbort();
348
382
  signal.addEventListener('abort', onAbort);
349
383
  try {
350
- return await child.exit;
384
+ const code = await child.exit;
385
+ if (brokenPipe !== undefined) throw brokenPipe;
386
+ return code;
351
387
  } finally {
352
388
  signal.removeEventListener('abort', onAbort);
353
389
  if (size && input.setRawSink) input.setRawSink(undefined);
package/src/shell/npm.ts CHANGED
@@ -15,6 +15,7 @@ import { parseFlags, type CommandContext } from './context.js';
15
15
  import type { JobInput, Shell } from './exec.js';
16
16
  import { devServerHandoff } from './devHandoff.js';
17
17
  import { hostNow } from '../node/hostClock.js';
18
+ import { isBrokenPipe } from '../system/signals.js';
18
19
 
19
20
  export const NPM_VERSION = '10.8.2';
20
21
 
@@ -56,6 +57,7 @@ async function install(ctx: CommandContext, options: Partial<InstallOptions>, di
56
57
  ctx.io.stdout(`\n${parts.length ? parts.join(', ') : 'up to date'}, audited ${result.total + 1} packages in ${seconds}s\n`);
57
58
  return 0;
58
59
  } catch (error) {
60
+ if (isBrokenPipe(error)) throw error; // its reader exited: SIGPIPE, not an install failure
59
61
  if (progress) ctx.io.stdout('\r\x1b[K');
60
62
  if (ctx.signal.aborted) return 130;
61
63
  ctx.io.stderr(`npm error ${error instanceof Error ? error.message : String(error)}\n`);
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Shell options (`set -o NAME` / `set +o NAME`, and the same flags when invoking
3
+ * `bfsh`). Only `pipefail` exists so far. It is ON by default: a pipeline fails
4
+ * when any stage fails, which the Builderforce canvas relies on to see a failing
5
+ * `build 2>&1 | tail`. `set +o pipefail` (or `bfsh +o pipefail -c …`) opts a
6
+ * script out to POSIX behaviour, where a pipeline's status is its last stage's.
7
+ */
8
+ import type { CommandContext } from './context.js';
9
+
10
+ export interface ShellSettings {
11
+ pipefail: boolean;
12
+ }
13
+
14
+ export const DEFAULT_SHELL_SETTINGS: Readonly<ShellSettings> = { pipefail: true };
15
+
16
+ const NAMES = Object.keys(DEFAULT_SHELL_SETTINGS) as Array<keyof ShellSettings>;
17
+
18
+ const isName = (name: string | undefined): name is keyof ShellSettings => NAMES.includes(name as keyof ShellSettings);
19
+
20
+ /**
21
+ * Leading `-o NAME` / `+o NAME` pairs of a `bfsh` invocation, applied to
22
+ * `settings`; returns the arguments after them, or an error message.
23
+ */
24
+ export function takeInvocationOptions(args: string[], settings: ShellSettings): { rest: string[] } | { error: string } {
25
+ let i = 0;
26
+ while ((args[i] === '-o' || args[i] === '+o') && i + 1 < args.length) {
27
+ const name = args[i + 1];
28
+ if (!isName(name)) return { error: `bfsh: ${name}: invalid option name` };
29
+ settings[name] = args[i] === '-o';
30
+ i += 2;
31
+ }
32
+ return { rest: args.slice(i) };
33
+ }
34
+
35
+ /** The state `set` changes. */
36
+ export interface SetTarget {
37
+ settings: ShellSettings;
38
+ positional: string[];
39
+ }
40
+
41
+ /** Real `set -o` names this shell does not model: accepted and ignored, like their short flags. */
42
+ const ACCEPTED_UNMODELLED = new Set([
43
+ 'allexport', 'braceexpand', 'emacs', 'errexit', 'errtrace', 'functrace', 'hashall', 'histexpand',
44
+ 'history', 'ignoreeof', 'interactive-comments', 'keyword', 'monitor', 'noclobber', 'noexec',
45
+ 'noglob', 'nolog', 'notify', 'nounset', 'onecmd', 'physical', 'posix', 'privileged', 'verbose',
46
+ 'vi', 'xtrace',
47
+ ]);
48
+
49
+ /**
50
+ * The `set` builtin: `set -o NAME` / `set +o NAME` and clustered short flags
51
+ * (`-euo pipefail`), `set -o` / `set +o` to list, and `set -- ARGS…` to replace
52
+ * the positional parameters. Only `pipefail` is modelled; other real options
53
+ * (`-e`, `-u`, `-x`, errexit…) are accepted and ignored as the shell always did,
54
+ * and an unknown option name is refused (status 2), as bash does.
55
+ */
56
+ export async function setBuiltin(ctx: CommandContext, shell: SetTarget): Promise<number> {
57
+ const args = ctx.args;
58
+ if (!args.length || (args.length === 1 && (args[0] === '-o' || args[0] === '+o'))) {
59
+ const listing = args[0] === '+o'
60
+ ? NAMES.map((name) => `set ${shell.settings[name] ? '-o' : '+o'} ${name}\n`)
61
+ : NAMES.map((name) => `${name.padEnd(15)}${shell.settings[name] ? 'on' : 'off'}\n`);
62
+ ctx.io.stdout(listing.join(''));
63
+ return 0;
64
+ }
65
+ for (let i = 0; i < args.length; i++) {
66
+ const arg = args[i]!;
67
+ if (arg === '--') {
68
+ shell.positional = args.slice(i + 1);
69
+ return 0;
70
+ }
71
+ // `-o NAME` / `+o NAME`, and clustered short flags (`-euo pipefail`, `+x`): only
72
+ // `pipefail` is modelled. Every other option (errexit, nounset, xtrace, -e, -u, -x)
73
+ // is accepted and ignored, as before, so ordinary `set -euo pipefail` headers in
74
+ // npm scripts keep working.
75
+ const flags = /^[-+][a-zA-Z]+$/.test(arg) ? arg.slice(1) : undefined;
76
+ if (flags === undefined) {
77
+ shell.positional = args.slice(i);
78
+ return 0;
79
+ }
80
+ const on = arg[0] === '-';
81
+ for (const flag of flags) {
82
+ if (flag !== 'o') continue;
83
+ const name = args[++i];
84
+ if (name === undefined) {
85
+ ctx.io.stderr('bfsh: set: -o: option name required\n');
86
+ return 2;
87
+ }
88
+ if (isName(name)) shell.settings[name] = on;
89
+ else if (!ACCEPTED_UNMODELLED.has(name)) {
90
+ ctx.io.stderr(`bfsh: set: ${name}: invalid option name\n`);
91
+ return 2;
92
+ }
93
+ }
94
+ }
95
+ return 0;
96
+ }
97
+
98
+ /** A pipeline's status from its stages': the rightmost non-zero under pipefail, else the last stage's. */
99
+ export function pipelineStatus(statuses: number[], settings: ShellSettings): number {
100
+ if (!settings.pipefail) return statuses[statuses.length - 1] ?? 0;
101
+ let status = 0;
102
+ for (const stage of statuses) if (stage !== 0) status = stage;
103
+ return status;
104
+ }
@@ -16,11 +16,13 @@ import { BUILTINS, COREUTILS, SYSTEM_PROGRAMS } from './builtins.js';
16
16
  import { npmCommand, npxCommand } from './npm.js';
17
17
  import { pnpmCommand, yarnCommand } from './packageManagers.js';
18
18
  import { glob } from './expand.js';
19
+ import { DEFAULT_SHELL_SETTINGS, takeInvocationOptions, type ShellSettings } from './options.js';
19
20
 
20
21
  export const SHELL_COMMANDS: Record<string, ShellCommand> = { npm: npmCommand, npx: npxCommand, pnpm: pnpmCommand, yarn: yarnCommand };
21
22
 
22
- function createShell(ctx: ProgramContext, positional: string[] = []): Shell {
23
+ function createShell(ctx: ProgramContext, positional: string[] = [], settings: ShellSettings = DEFAULT_SHELL_SETTINGS): Shell {
23
24
  return new Shell({
25
+ pipefail: settings.pipefail,
24
26
  system: ctx.system,
25
27
  cwd: ctx.cwd,
26
28
  env: { ...ctx.env, SHELL: '/bin/bfsh' },
@@ -104,9 +106,9 @@ function completer(shell: Shell) {
104
106
  };
105
107
  }
106
108
 
107
- async function interactive(ctx: ProgramContext): Promise<number> {
109
+ async function interactive(ctx: ProgramContext, settings: ShellSettings): Promise<number> {
108
110
  const terminal = ctx.io.terminal!;
109
- const shell = createShell(ctx);
111
+ const shell = createShell(ctx, [], settings);
110
112
  const io = text(ctx);
111
113
  terminal.setRawMode(true);
112
114
  const editor = new LineEditor({ write: (t) => ctx.io.stdout(t), history: shell.history, complete: completer(shell) });
@@ -200,9 +202,19 @@ async function interactive(ctx: ProgramContext): Promise<number> {
200
202
  return code;
201
203
  }
202
204
 
205
+ /**
206
+ * `bfsh [-o|+o OPTION]… -c SCRIPT [ARGS…]`, `bfsh [-o|+o OPTION]… FILE [ARGS…]`,
207
+ * or no arguments (interactive / stdin). `+o pipefail` opts out of pipefail.
208
+ */
203
209
  export const shellProgram: Program = async (ctx) => {
204
- const args = ctx.args.filter((a) => a !== '-l' && a !== '--login' && a !== '-i');
205
- if (args[0] === '-c') return runOnce(ctx, createShell(ctx, args.slice(2)), args[1] ?? '');
210
+ const settings: ShellSettings = { ...DEFAULT_SHELL_SETTINGS };
211
+ const taken = takeInvocationOptions(ctx.args.filter((a) => a !== '-l' && a !== '--login' && a !== '-i'), settings);
212
+ if ('error' in taken) {
213
+ ctx.io.stderr(`${taken.error}\n`);
214
+ return 2;
215
+ }
216
+ const args = taken.rest;
217
+ if (args[0] === '-c') return runOnce(ctx, createShell(ctx, args.slice(2), settings), args[1] ?? '');
206
218
  if (args[0]) {
207
219
  const path = args[0].startsWith('/') ? args[0] : join(ctx.cwd, args[0]);
208
220
  const source = ctx.system.fs.readText(path);
@@ -210,14 +222,14 @@ export const shellProgram: Program = async (ctx) => {
210
222
  ctx.io.stderr(`bfsh: ${args[0]}: No such file or directory\n`);
211
223
  return 127;
212
224
  }
213
- return runOnce(ctx, createShell(ctx, args.slice(1)), source.replace(/^#!.*\n/, ''));
225
+ return runOnce(ctx, createShell(ctx, args.slice(1), settings), source.replace(/^#!.*\n/, ''));
214
226
  }
215
- if (ctx.io.terminal) return interactive(ctx);
227
+ if (ctx.io.terminal) return interactive(ctx, settings);
216
228
  // No terminal, no script: read commands from stdin.
217
229
  const { input, stop } = stdinJob(ctx);
218
230
  const source = await input.queue.readAll();
219
231
  stop();
220
- const shell = createShell(ctx);
232
+ const shell = createShell(ctx, [], settings);
221
233
  const empty = new InputQueue();
222
234
  empty.push(null);
223
235
  return shell.exec(source, text(ctx), { queue: empty }, ctx.signal);
@@ -62,7 +62,9 @@ function headTail(which: 'head' | 'tail'): Command {
62
62
  const numeric = ctx.args.find((a) => /^-\d+$/.test(a));
63
63
  const { values, operands } = parseFlags(ctx.args.filter((a) => a !== numeric), ['n']);
64
64
  const count = numeric ? Number(numeric.slice(1)) : values.n !== undefined ? Number(values.n) : 10;
65
- const files = await inputs(ctx, operands, which);
65
+ // head on stdin stops reading once it has its lines (and exits, closing the pipe), as the real one does.
66
+ const fromStdin = which === 'head' && (!operands.length || (operands.length === 1 && operands[0] === '-'));
67
+ const files = fromStdin ? [{ label: '(standard input)', text: await ctx.io.stdin.readLines(count) }] : await inputs(ctx, operands, which);
66
68
  if (typeof files === 'number') return files;
67
69
  files.forEach((file, index) => {
68
70
  if (files.length > 1) ctx.io.stdout(`${index ? '\n' : ''}==> ${file.label} <==\n`);
@@ -6,10 +6,19 @@
6
6
  */
7
7
  import type { ByteChannel, HttpResponseData, HttpResponseHead, HttpStreamResponse } from './types.js';
8
8
 
9
+ /** Bytes a body stream queues for a reader that is not keeping up before `push` reports it full. */
10
+ export const BODY_HIGH_WATER_MARK = 1024 * 1024;
11
+
9
12
  export interface PushStream {
10
13
  readonly stream: ReadableStream<Uint8Array>;
11
- /** Queue a chunk; ignored once the stream is closed or cancelled. */
12
- push(chunk: Uint8Array): void;
14
+ /**
15
+ * Queue a chunk; ignored once the stream is closed or cancelled. Returns false
16
+ * when the queue is at its high-water mark (or the reader is gone): a producer
17
+ * that can wait should, until `ready()` resolves.
18
+ */
19
+ push(chunk: Uint8Array): boolean;
20
+ /** Resolves when the reader wants more (pulls below the high-water mark), or the stream is done. */
21
+ ready(): Promise<void>;
13
22
  end(): void;
14
23
  /** End with an error: the reader sees a failed read (a truncated response). */
15
24
  fail(error: unknown): void;
@@ -17,32 +26,54 @@ export interface PushStream {
17
26
  readonly done: boolean;
18
27
  }
19
28
 
20
- /** A body stream fed from outside. `onCancel` runs when the reader hangs up before the end. */
21
- export function pushStream(onCancel?: (reason: unknown) => void): PushStream {
29
+ /**
30
+ * A body stream fed from outside, pull-based: it queues up to `highWaterMark`
31
+ * bytes for a slow reader, and `push`/`ready` tell the producer when to wait.
32
+ * `onCancel` runs when the reader hangs up before the end.
33
+ */
34
+ export function pushStream(onCancel?: (reason: unknown) => void, highWaterMark = BODY_HIGH_WATER_MARK): PushStream {
22
35
  let controller!: ReadableStreamDefaultController<Uint8Array>;
23
36
  let done = false;
24
- const stream = new ReadableStream<Uint8Array>({
25
- start: (c) => void (controller = c),
26
- cancel: (reason) => {
27
- if (done) return;
28
- done = true;
29
- onCancel?.(reason);
37
+ let waiting: Array<() => void> = [];
38
+ const wake = () => {
39
+ const resume = waiting;
40
+ waiting = [];
41
+ for (const go of resume) go();
42
+ };
43
+ const hasRoom = () => !done && (controller.desiredSize ?? 0) > 0;
44
+ const stream = new ReadableStream<Uint8Array>(
45
+ {
46
+ start: (c) => void (controller = c),
47
+ pull: wake, // the reader drained below the mark: producers may go on
48
+ cancel: (reason) => {
49
+ if (done) return;
50
+ done = true;
51
+ wake();
52
+ onCancel?.(reason);
53
+ },
30
54
  },
31
- });
55
+ new ByteLengthQueuingStrategy({ highWaterMark }),
56
+ );
32
57
  return {
33
58
  stream,
34
59
  push(chunk) {
35
60
  if (!done && chunk.byteLength) controller.enqueue(chunk);
61
+ return hasRoom();
62
+ },
63
+ ready() {
64
+ return done || hasRoom() ? Promise.resolve() : new Promise((resolve) => waiting.push(resolve));
36
65
  },
37
66
  end() {
38
67
  if (done) return;
39
68
  done = true;
40
69
  controller.close();
70
+ wake();
41
71
  },
42
72
  fail(error) {
43
73
  if (done) return;
44
74
  done = true;
45
75
  controller.error(error);
76
+ wake();
46
77
  },
47
78
  get done() {
48
79
  return done;
@@ -37,6 +37,7 @@ export type { ServerAddress, PortChange } from './serverEvents.js';
37
37
  export { resolveCommand, findExecutable, binDirectories, interpreterFor, commandNotFound } from './commands.js';
38
38
  export type { ResolvedCommand } from './commands.js';
39
39
  export { InputQueue, LineDiscipline, toTerminal } from './terminal.js';
40
+ export { SIGNAL_EXIT_CODES, SIGPIPE_STATUS, signalExitCode, BrokenPipeError, isBrokenPipe, brokePipe } from './signals.js';
40
41
  export { defaultPrograms } from './programs.js';
41
42
  export { startNode } from '../node/runtime.js';
42
43
  export type { NodeInstance, NodeOptions } from '../node/runtime.js';
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Signals as exit statuses (128 + the signal number, as a shell reports a
3
+ * process a signal ended), and the broken-pipe error a write to a pipe whose
4
+ * reader is gone raises — the in-memory stand-in for SIGPIPE.
5
+ */
6
+
7
+ export const SIGNAL_EXIT_CODES: Readonly<Record<string, number>> = { SIGHUP: 129, SIGINT: 130, SIGKILL: 137, SIGPIPE: 141, SIGTERM: 143 };
8
+
9
+ /** The status of a pipeline stage stopped by writing to a closed pipe. */
10
+ export const SIGPIPE_STATUS = SIGNAL_EXIT_CODES.SIGPIPE!;
11
+
12
+ /** The exit status `signal` ends a process with (1 for a signal with no number here). */
13
+ export function signalExitCode(signal: string): number {
14
+ return SIGNAL_EXIT_CODES[signal] ?? 1;
15
+ }
16
+
17
+ /**
18
+ * A write to a pipe nobody reads any more (`yes | head -1` once head exits).
19
+ * `pipe` is the pipe that broke, so the pipeline stage writing into it — and only
20
+ * that stage — turns it into SIGPIPE's status: a loop or group inside the stage
21
+ * (`while true; do echo y; done | head -1`) must stop with it, as SIGPIPE ends the
22
+ * whole subshell in a real shell, not swallow it and go round again.
23
+ */
24
+ export class BrokenPipeError extends Error {
25
+ readonly code = 'EPIPE';
26
+ constructor(readonly pipe?: object) {
27
+ super('EPIPE: broken pipe, write');
28
+ this.name = 'BrokenPipeError';
29
+ }
30
+ }
31
+
32
+ export function isBrokenPipe(error: unknown): boolean {
33
+ return error instanceof BrokenPipeError || (error as { code?: unknown } | null)?.code === 'EPIPE';
34
+ }
35
+
36
+ /** Did writing into `pipe` (and not some other pipe) raise `error`? */
37
+ export function brokePipe(error: unknown, pipe: object): boolean {
38
+ return error instanceof BrokenPipeError && error.pipe === pipe;
39
+ }
@@ -2,7 +2,9 @@
2
2
  * What a kernel's TTY layer does between xterm.js and a program:
3
3
  *
4
4
  * - InputQueue: stdin as a buffered stream of chunks — text, or bytes (data that arrives
5
- * before the program subscribes is kept, not dropped).
5
+ * before the program subscribes is kept, not dropped). As a pipe, its reader
6
+ * closes it on exit (`closeReader`): what was buffered is dropped and later
7
+ * writes throw EPIPE, so the writer stops instead of buffering forever.
6
8
  * - LineDiscipline: "cooked" mode — echo, backspace, Ctrl-U, Enter delivers the
7
9
  * line, Ctrl-C raises SIGINT, Ctrl-D is end-of-file. A program that calls
8
10
  * `setRawMode(true)` (the shell, prompts libraries) gets keystrokes untouched.
@@ -10,6 +12,7 @@
10
12
  * only moves to column 0 on `\r`.
11
13
  */
12
14
  import type { StdioChunk } from './types.js';
15
+ import { BrokenPipeError } from './signals.js';
13
16
 
14
17
 
15
18
  export class InputQueue<T extends StdioChunk = string> {
@@ -18,8 +21,14 @@ export class InputQueue<T extends StdioChunk = string> {
18
21
  private ended = false;
19
22
 
20
23
  private draining = false;
24
+ private readerClosed = false;
21
25
 
26
+ /** Queue a chunk (`null`: end-of-file). Throws {@link BrokenPipeError} once the reader has closed; ending is always allowed. */
22
27
  push(chunk: T | null): void {
28
+ if (this.readerClosed) {
29
+ if (chunk === null) return;
30
+ throw new BrokenPipeError(this);
31
+ }
23
32
  if (this.ended) return;
24
33
  if (chunk === null) this.ended = true;
25
34
  this.buffered.push(chunk);
@@ -64,9 +73,50 @@ export class InputQueue<T extends StdioChunk = string> {
64
73
  });
65
74
  }
66
75
 
76
+ /**
77
+ * The first `count` lines (each with its `\n`; fewer at end-of-file), then stop
78
+ * reading — what `head` needs to exit early, so the writer upstream gets EPIPE.
79
+ */
80
+ readLines(count: number): Promise<string> {
81
+ return new Promise((resolve) => {
82
+ if (count <= 0) return resolve('');
83
+ let text = '';
84
+ let found = 0;
85
+ let done = false;
86
+ const finish = () => {
87
+ done = true;
88
+ stop();
89
+ resolve(text);
90
+ };
91
+ const stop = this.subscribe(
92
+ textChunks((chunk) => {
93
+ if (done) return;
94
+ if (chunk === null) return finish();
95
+ for (let from = 0; ; ) {
96
+ const newline = chunk.indexOf('\n', from);
97
+ if (newline < 0) return void (text += chunk.slice(from));
98
+ text += chunk.slice(from, newline + 1);
99
+ from = newline + 1;
100
+ if (++found === count) return finish();
101
+ }
102
+ }),
103
+ );
104
+ });
105
+ }
106
+
107
+ /** The reader is gone (a pipeline stage exited): drop what it never read; later writes fail with EPIPE. */
108
+ closeReader(): void {
109
+ this.readerClosed = true;
110
+ this.buffered.length = 0;
111
+ }
112
+
67
113
  get isEnded(): boolean {
68
114
  return this.ended;
69
115
  }
116
+
117
+ get isReaderClosed(): boolean {
118
+ return this.readerClosed;
119
+ }
70
120
  }
71
121
 
72
122
  /**