brsh 3.8.1 → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,29 +3,79 @@
3
3
  const nodeFs = require('fs');
4
4
  const nodePath = require('path');
5
5
  const BaseFileSystem = require('./BaseFileSystem');
6
+ const { BinaryFile, SymlinkRef, isUtf8Text } = BaseFileSystem;
6
7
 
7
8
  class NodeFileSystem extends BaseFileSystem {
8
- constructor(cwd, onChange = null) {
9
+ constructor(cwd = '/', onChange = null, options = {}) {
9
10
  super();
10
11
  this._onChange = onChange;
11
12
  this._changeScheduled = false;
12
13
  this._virtualFiles = {};
13
- this.cwd = this._normalizeCwd(cwd || process.cwd());
14
+ this._rootDir = options && options.rootDir ? nodePath.resolve(options.rootDir) : null;
15
+ this.cwd = this._normalizeCwd(cwd || (this._rootDir ? '/' : process.cwd()));
14
16
  }
15
17
 
16
18
  get isRealFilesystem() { return true; }
17
19
 
20
+ get rootDir() { return this._rootDir; }
21
+
18
22
  _normalizeCwd(cwd) {
23
+ if (this._rootDir) {
24
+ let abs = cwd.startsWith('/') ? cwd : '/' + cwd;
25
+ abs = nodePath.posix.normalize(abs);
26
+ return abs === '/' ? '/' : abs + '/';
27
+ }
19
28
  const abs = nodePath.resolve(cwd);
20
29
  return abs === '/' ? '/' : abs + '/';
21
30
  }
22
31
 
23
32
  absolutePath(path) {
33
+ if (!path) return this.cwd;
24
34
  if (path.startsWith('./')) path = path.slice(2);
35
+ if (this._rootDir) {
36
+ const abs = path.startsWith('/') ? path : nodePath.posix.join(this.cwd, path);
37
+ return nodePath.posix.normalize(abs);
38
+ }
25
39
  const abs = path.startsWith('/') ? path : nodePath.join(this.cwd, path);
26
40
  return nodePath.normalize(abs);
27
41
  }
28
42
 
43
+ _toHostPath(virtualPath) {
44
+ const vAbs = this.absolutePath(virtualPath);
45
+ if (!this._rootDir) {
46
+ return nodePath.resolve(vAbs);
47
+ }
48
+ const rel = vAbs.replace(/^\/+/, '');
49
+ const hostPath = nodePath.resolve(this._rootDir, rel);
50
+ if (hostPath !== this._rootDir && !hostPath.startsWith(this._rootDir + nodePath.sep)) {
51
+ return this._rootDir;
52
+ }
53
+ return hostPath;
54
+ }
55
+
56
+ _resolveVirtualPath(virtualPath, maxHops = 10) {
57
+ let current = this.absolutePath(virtualPath);
58
+ let hops = 0;
59
+ while (hops++ < maxHops) {
60
+ const host = this._toHostPath(current);
61
+ let isLink = false;
62
+ let target = null;
63
+ try {
64
+ if (nodeFs.lstatSync(host).isSymbolicLink()) {
65
+ isLink = true;
66
+ target = nodeFs.readlinkSync(host);
67
+ }
68
+ } catch (_) {}
69
+ if (!isLink || !target) break;
70
+ if (target.startsWith('/')) {
71
+ current = this.absolutePath(target);
72
+ } else {
73
+ current = this.absolutePath(nodePath.posix.join(nodePath.posix.dirname(current), target));
74
+ }
75
+ }
76
+ return current;
77
+ }
78
+
29
79
  setCwd(cwd) {
30
80
  const trimmed = cwd.endsWith('/') ? cwd.slice(0, -1) : cwd;
31
81
  const abs = this.absolutePath(trimmed);
@@ -39,9 +89,12 @@ class NodeFileSystem extends BaseFileSystem {
39
89
  return this._virtualFiles[abs];
40
90
  }
41
91
 
92
+ const resolvedVirtual = this._resolveVirtualPath(abs);
93
+ const hostPath = this._toHostPath(resolvedVirtual);
94
+
42
95
  let stat;
43
96
  try {
44
- stat = nodeFs.statSync(abs);
97
+ stat = nodeFs.statSync(hostPath);
45
98
  } catch(e) {
46
99
  return null;
47
100
  }
@@ -49,14 +102,23 @@ class NodeFileSystem extends BaseFileSystem {
49
102
  if (stat.isDirectory()) {
50
103
  const entries = {};
51
104
  try {
52
- for (const name of nodeFs.readdirSync(abs)) {
53
- const childAbs = nodePath.join(abs, name);
105
+ for (const name of nodeFs.readdirSync(hostPath)) {
106
+ const childAbs = this.absolutePath(nodePath.posix.join(resolvedVirtual, name));
54
107
  if (this._virtualFiles[childAbs] !== undefined) {
55
108
  entries[name] = this._virtualFiles[childAbs];
56
109
  } else {
57
110
  try {
58
- entries[name] = nodeFs.statSync(childAbs).isDirectory() ? {} : '';
59
- } catch(e) { /* skip unreadable */ }
111
+ const childHost = nodePath.join(hostPath, name);
112
+ const childStat = nodeFs.statSync(childHost);
113
+ entries[name] = childStat.isDirectory() ? {} : '';
114
+ } catch(e) {
115
+ // If child is a symlink or unreadable file
116
+ try {
117
+ if (nodeFs.lstatSync(nodePath.join(hostPath, name)).isSymbolicLink()) {
118
+ entries[name] = '';
119
+ }
120
+ } catch (_) {}
121
+ }
60
122
  }
61
123
  }
62
124
  } catch(e) { /* directory unreadable */ }
@@ -74,7 +136,11 @@ class NodeFileSystem extends BaseFileSystem {
74
136
  }
75
137
 
76
138
  try {
77
- return nodeFs.readFileSync(abs, 'utf8');
139
+ const buf = nodeFs.readFileSync(hostPath);
140
+ if (isUtf8Text(buf)) {
141
+ return buf.toString('utf8');
142
+ }
143
+ return new BinaryFile(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
78
144
  } catch(e) {
79
145
  return null;
80
146
  }
@@ -83,14 +149,34 @@ class NodeFileSystem extends BaseFileSystem {
83
149
  setFileByPath(path, content, createDir = false) {
84
150
  const abs = this.absolutePath(path);
85
151
 
86
- if (typeof content === 'function' || content instanceof Uint8Array) {
152
+ if (typeof content === 'function') {
87
153
  this._virtualFiles[abs] = content;
88
154
  return;
89
155
  }
90
156
 
157
+ const hostPath = this._toHostPath(abs);
158
+
159
+ if (content instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(content))) {
160
+ const u8 = content instanceof Uint8Array
161
+ ? Buffer.from(content.buffer, content.byteOffset, content.byteLength)
162
+ : content;
163
+ try {
164
+ if (createDir) {
165
+ nodeFs.mkdirSync(nodePath.dirname(hostPath), { recursive: true });
166
+ }
167
+ nodeFs.writeFileSync(hostPath, u8);
168
+ delete this._virtualFiles[abs];
169
+ this._triggerChange();
170
+ } catch (e) {
171
+ this._virtualFiles[abs] = content;
172
+ }
173
+ return;
174
+ }
175
+
91
176
  if (content !== null && content !== undefined && content.constructor === Object) {
92
177
  try {
93
- nodeFs.mkdirSync(abs, { recursive: createDir });
178
+ nodeFs.mkdirSync(hostPath, { recursive: createDir });
179
+ delete this._virtualFiles[abs];
94
180
  this._triggerChange();
95
181
  } catch (e) {
96
182
  this._virtualFiles[abs] = content;
@@ -100,9 +186,10 @@ class NodeFileSystem extends BaseFileSystem {
100
186
 
101
187
  try {
102
188
  if (createDir) {
103
- nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
189
+ nodeFs.mkdirSync(nodePath.dirname(hostPath), { recursive: true });
104
190
  }
105
- nodeFs.writeFileSync(abs, String(content));
191
+ nodeFs.writeFileSync(hostPath, String(content));
192
+ delete this._virtualFiles[abs];
106
193
  this._triggerChange();
107
194
  } catch (e) {
108
195
  this._virtualFiles[abs] = String(content);
@@ -112,12 +199,13 @@ class NodeFileSystem extends BaseFileSystem {
112
199
  deleteFileByPath(path) {
113
200
  const abs = this.absolutePath(path);
114
201
  delete this._virtualFiles[abs];
202
+ const hostPath = this._toHostPath(abs);
115
203
  try {
116
- const stat = nodeFs.lstatSync(abs);
204
+ const stat = nodeFs.lstatSync(hostPath);
117
205
  if (stat.isDirectory()) {
118
- nodeFs.rmdirSync(abs);
206
+ nodeFs.rmSync(hostPath, { recursive: true, force: true });
119
207
  } else {
120
- nodeFs.unlinkSync(abs);
208
+ nodeFs.unlinkSync(hostPath);
121
209
  }
122
210
  this._triggerChange();
123
211
  } catch(e) { /* may not exist on real fs */ }
@@ -128,8 +216,9 @@ class NodeFileSystem extends BaseFileSystem {
128
216
  if (this._virtualFiles[abs] !== undefined) {
129
217
  return typeof this._virtualFiles[abs] === 'function' ? 0o755 : 0o644;
130
218
  }
219
+ const hostPath = this._toHostPath(abs);
131
220
  try {
132
- return nodeFs.statSync(abs).mode & 0o777;
221
+ return nodeFs.lstatSync(hostPath).mode & 0o777;
133
222
  } catch(e) {
134
223
  return null;
135
224
  }
@@ -140,17 +229,23 @@ class NodeFileSystem extends BaseFileSystem {
140
229
  if (this._virtualFiles[abs] !== undefined) {
141
230
  return;
142
231
  }
232
+ const hostPath = this._toHostPath(abs);
143
233
  try {
144
- nodeFs.chmodSync(abs, mode);
234
+ if (nodeFs.lstatSync(hostPath).isSymbolicLink()) {
235
+ return;
236
+ }
237
+ nodeFs.chmodSync(hostPath, mode);
145
238
  this._triggerChange();
146
- } catch (e) { /* ignore chmod errors on virtualized paths */ }
239
+ } catch (e) { /* ignore chmod errors */ }
147
240
  }
148
241
 
149
242
  getSize(path) {
150
243
  const abs = this.absolutePath(path);
151
244
  if (this._virtualFiles[abs] !== undefined) return 0;
245
+ const resolvedVirtual = this._resolveVirtualPath(abs);
246
+ const hostPath = this._toHostPath(resolvedVirtual);
152
247
  try {
153
- return nodeFs.statSync(abs).size;
248
+ return nodeFs.statSync(hostPath).size;
154
249
  } catch(e) {
155
250
  return 0;
156
251
  }
@@ -158,18 +253,24 @@ class NodeFileSystem extends BaseFileSystem {
158
253
 
159
254
  isSymlink(path) {
160
255
  const abs = this.absolutePath(path);
161
- try { return nodeFs.lstatSync(abs).isSymbolicLink(); } catch(e) { return false; }
256
+ const hostPath = this._toHostPath(abs);
257
+ try { return nodeFs.lstatSync(hostPath).isSymbolicLink(); } catch(e) { return false; }
162
258
  }
163
259
 
164
260
  readSymlink(path) {
165
261
  const abs = this.absolutePath(path);
166
- try { return nodeFs.readlinkSync(abs); } catch(e) { return null; }
262
+ const hostPath = this._toHostPath(abs);
263
+ try { return nodeFs.readlinkSync(hostPath); } catch(e) { return null; }
167
264
  }
168
265
 
169
266
  createSymlink(target, linkPath) {
170
267
  const abs = this.absolutePath(linkPath);
171
- nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
172
- nodeFs.symlinkSync(target, abs);
268
+ const hostPath = this._toHostPath(abs);
269
+ nodeFs.mkdirSync(nodePath.dirname(hostPath), { recursive: true });
270
+ try {
271
+ nodeFs.unlinkSync(hostPath);
272
+ } catch (_) {}
273
+ nodeFs.symlinkSync(target, hostPath);
173
274
  this._triggerChange();
174
275
  }
175
276
 
@@ -192,10 +293,11 @@ class NodeFileSystem extends BaseFileSystem {
192
293
  const parts = abs.split('/');
193
294
  const end = parts.pop();
194
295
  const dirPath = parts.join('/') || '/';
296
+ const hostDirPath = this._toHostPath(dirPath);
195
297
 
196
298
  let dirEntries = [];
197
299
  try {
198
- dirEntries = nodeFs.readdirSync(dirPath);
300
+ dirEntries = nodeFs.readdirSync(hostDirPath);
199
301
  } catch(e) { /* not readable */ }
200
302
 
201
303
  const prefix = dirPath === '/' ? '/' : dirPath + '/';
@@ -224,10 +326,11 @@ class NodeFileSystem extends BaseFileSystem {
224
326
  return {
225
327
  path: initialParts.length ? initialParts.join('/') : null,
226
328
  options: options.map(name => {
227
- const fullPath = nodePath.join(dirPath, name);
228
- if (this._virtualFiles[fullPath] !== undefined) return name;
329
+ const fullVirtual = nodePath.posix.join(dirPath, name);
330
+ if (this._virtualFiles[fullVirtual] !== undefined) return name;
229
331
  try {
230
- return nodeFs.statSync(fullPath).isDirectory() ? name + '/' : name;
332
+ const fullHost = this._toHostPath(fullVirtual);
333
+ return nodeFs.statSync(fullHost).isDirectory() ? name + '/' : name;
231
334
  } catch(e) { return name; }
232
335
  })
233
336
  };
@@ -245,17 +348,48 @@ class NodeFileSystem extends BaseFileSystem {
245
348
  exists(path) {
246
349
  const abs = this.absolutePath(path);
247
350
  if (this._virtualFiles[abs] !== undefined) return true;
248
- try { nodeFs.statSync(abs); return true; } catch(e) { return false; }
351
+ const hostPath = this._toHostPath(abs);
352
+ try {
353
+ if (nodeFs.lstatSync(hostPath).isSymbolicLink()) {
354
+ const resolvedVirtual = this._resolveVirtualPath(abs);
355
+ const resolvedHost = this._toHostPath(resolvedVirtual);
356
+ return nodeFs.existsSync(resolvedHost);
357
+ }
358
+ return nodeFs.existsSync(hostPath);
359
+ } catch(e) { return false; }
360
+ }
361
+
362
+ loadModule(path) {
363
+ const abs = this.absolutePath(path);
364
+ if (this._virtualFiles[abs] !== undefined) {
365
+ const v = this._virtualFiles[abs];
366
+ if (typeof v === 'function') return v;
367
+ return super.loadModule(path);
368
+ }
369
+ const hostPath = this._toHostPath(abs);
370
+ try {
371
+ const mod = require(hostPath);
372
+ return mod && mod.default !== undefined ? mod.default : mod;
373
+ } catch (err) {
374
+ return super.loadModule(path);
375
+ }
249
376
  }
250
377
 
251
378
  stat(path) {
252
379
  const abs = this.absolutePath(path);
253
380
  if (this._virtualFiles[abs] !== undefined) {
254
381
  const v = this._virtualFiles[abs];
255
- return { isDirectory: v !== null && v !== undefined && v.constructor === Object, isFile: typeof v === 'string' || v instanceof Uint8Array, isCommand: typeof v === 'function', isBinary: v instanceof Uint8Array };
382
+ return {
383
+ isDirectory: v !== null && v !== undefined && v.constructor === Object,
384
+ isFile: typeof v === 'string' || v instanceof Uint8Array,
385
+ isCommand: typeof v === 'function',
386
+ isBinary: v instanceof Uint8Array
387
+ };
256
388
  }
389
+ const resolvedVirtual = this._resolveVirtualPath(abs);
390
+ const hostPath = this._toHostPath(resolvedVirtual);
257
391
  try {
258
- const s = nodeFs.statSync(abs);
392
+ const s = nodeFs.statSync(hostPath);
259
393
  return { isDirectory: s.isDirectory(), isFile: s.isFile(), isCommand: false };
260
394
  } catch(e) { return null; }
261
395
  }
package/lib/Readme.md CHANGED
@@ -55,6 +55,7 @@ When `get requiresFilesystem() { return true; }` is set on a command, `this.fs`
55
55
  * `exists(path)` / `stat(path)` / `getSize(path)` / `absolutePath(path)`
56
56
  * `getMode(path)` / `setMode(path, mode)` / `isReadable(path)` / `isWritable(path)` / `isExecutable(path)`
57
57
  * `isSymlink(path)` / `readSymlink(path)` / `createSymlink(target, linkPath)`
58
+ * `loadModule(path)` — evaluates a JS module from the filesystem (virtual evaluation on `FileSystem`, native `require()` on `NodeFileSystem`)
58
59
 
59
60
  ---
60
61
 
@@ -137,6 +138,7 @@ shell.context.setCommand(MyWasmTool);
137
138
 
138
139
  * For POSIX terminal raw mode, baud rates, and `TIOCGWINSZ`, use [**`wasi-termios-brsh`**](https://github.com/eliotstocker/wasi-termios-brsh).
139
140
  * For a complete real-world reference implementation of an interactive C TUI editor with ncurses targeting `brsh`, inspect [**`nano-wasm`**](https://github.com/eliotstocker/nano-wasm).
141
+ * For an interactive game loop with non-blocking event loops, clock sleeps, and 24-bit ANSI streaming, inspect [**`doom-wasm`**](https://github.com/eliotstocker/doom-wasm).
140
142
  * For complete step-by-step instructions on compiling with `wasi-sdk`, configuring `termios`, and instrumenting with `wasm-opt --asyncify`, see [Compiling C / C++ Applications in the main Readme](../Readme.md#compiling-c--c-applications-for-brsh).
141
143
 
142
144
 
@@ -18,12 +18,31 @@ class ScriptCommand extends LocalCommand {
18
18
  }
19
19
 
20
20
  // Only capture input when the sandbox itself has a command waiting for it
21
- // (e.g. an active `read`). This prevents swallowing keystrokes during
22
- // normal command execution.
21
+ // (e.g. an active `read` or interactive TUI/WASM app). This prevents swallowing
22
+ // keystrokes during normal non-interactive command execution.
23
23
  get captureInput() {
24
24
  return !!(this.sandbox
25
25
  && this.sandbox.runningCommand
26
- && this.sandbox.runningCommand.captureInput);
26
+ && (this.sandbox.runningCommand.captureInput || this.sandbox.runningCommand.interactive));
27
+ }
28
+
29
+ get interactive() {
30
+ return !!(this.sandbox
31
+ && this.sandbox.runningCommand
32
+ && this.sandbox.runningCommand.interactive);
33
+ }
34
+
35
+ get _inAltScreen() {
36
+ return Boolean(
37
+ this.__inAltScreen ||
38
+ (this.sandbox
39
+ && this.sandbox.runningCommand
40
+ && this.sandbox.runningCommand._inAltScreen)
41
+ );
42
+ }
43
+
44
+ set _inAltScreen(val) {
45
+ this.__inAltScreen = Boolean(val);
27
46
  }
28
47
 
29
48
  onInput(char) {
@@ -32,6 +51,16 @@ class ScriptCommand extends LocalCommand {
32
51
  }
33
52
  }
34
53
 
54
+ kill(signal = 'SIGINT') {
55
+ if (this.sandbox && this.sandbox.runningCommand && typeof this.sandbox.runningCommand.kill === 'function') {
56
+ this.sandbox.runningCommand.kill(signal);
57
+ }
58
+ if (this.sandbox && typeof this.sandbox.destroy === 'function') {
59
+ this.sandbox.destroy(130);
60
+ }
61
+ super.kill(signal);
62
+ }
63
+
35
64
  run() {
36
65
  const fs = (this.context && this.context.fs) || this.fs;
37
66
  const fsOpts = fs && fs.isRealFilesystem
@@ -44,6 +73,12 @@ class ScriptCommand extends LocalCommand {
44
73
  });
45
74
  this.sandbox.context.source(this.context);
46
75
 
76
+ const cols = (this.stdinStream && this.stdinStream.columns) || 80;
77
+ const rows = (this.stdinStream && this.stdinStream.rows) || 24;
78
+ if (typeof this.sandbox.setTerminalSize === 'function') {
79
+ this.sandbox.setTerminalSize(cols, rows);
80
+ }
81
+
47
82
  if (Array.isArray(this.arguments)) {
48
83
  this.arguments.forEach((arg, i) =>
49
84
  this.sandbox.context.setVar(String(i + 1), arg));
@@ -52,8 +87,66 @@ class ScriptCommand extends LocalCommand {
52
87
  this.sandbox.context.setVar('*', this.arguments.join(' '));
53
88
  }
54
89
 
90
+ // Remove default Command.js parsed keystroke listener so raw TTY chunks pass cleanly
91
+ // to interactive WASM/TUI child commands without double-firing onInput
92
+ if (this._onStdinStreamData && this.stdinStream && typeof this.stdinStream.off === 'function') {
93
+ this.stdinStream.off('data', this._onStdinStreamData);
94
+ }
95
+
96
+ const onParentStdin = (chunk) => {
97
+ if (!this.sandbox || !this.sandbox.runningCommand) return;
98
+ const child = this.sandbox.runningCommand;
99
+ const hasStreamListeners = child.stdinStream && child.stdinStream.listenerCount('data') > 1;
100
+ if (child.interactive || child._inAltScreen || hasStreamListeners) {
101
+ if (child.stdinStream) {
102
+ child.stdinStream.pushData(chunk);
103
+ }
104
+ return;
105
+ }
106
+ if (child.captureInput && typeof child.onInput === 'function') {
107
+ const { parseVtKeys } = require('./TtyStream');
108
+ for (const k of parseVtKeys(chunk)) {
109
+ if (k === '^C') {
110
+ this.kill('SIGINT');
111
+ return;
112
+ }
113
+ if (!child.stdinStream || !child.stdinStream.isRaw) {
114
+ if (k === 'Enter') this.stdout.write('\r\n');
115
+ else if (k === 'Backspace') this.stdout.write('\b \b');
116
+ else if (k.length === 1) this.stdout.write(k);
117
+ }
118
+ child.onInput(k);
119
+ }
120
+ }
121
+ };
122
+
123
+ const onParentResize = () => {
124
+ if (this.sandbox && typeof this.sandbox.setTerminalSize === 'function' && this.stdinStream) {
125
+ this.sandbox.setTerminalSize(this.stdinStream.columns, this.stdinStream.rows);
126
+ }
127
+ };
128
+
129
+ if (this.stdinStream && typeof this.stdinStream.on === 'function') {
130
+ this.stdinStream.on('data', onParentStdin);
131
+ this.stdinStream.on('resize', onParentResize);
132
+ }
133
+
55
134
  this.sandbox.on('stdOut', data => { this.stdOut = data; this.flush(); });
56
135
  this.sandbox.on('stdErr', data => { this.stdErr = data; this.flush(); });
136
+ if (this.sandbox.stdout && typeof this.sandbox.stdout.on === 'function') {
137
+ this.sandbox.stdout.on('data', chunk => {
138
+ if (this.stdout && typeof this.stdout.write === 'function') {
139
+ this.stdout.write(chunk);
140
+ }
141
+ });
142
+ }
143
+ if (this.sandbox.stderr && typeof this.sandbox.stderr.on === 'function') {
144
+ this.sandbox.stderr.on('data', chunk => {
145
+ if (this.stderr && typeof this.stderr.write === 'function') {
146
+ this.stderr.write(chunk);
147
+ }
148
+ });
149
+ }
57
150
 
58
151
  this._scriptFunctions = {};
59
152
 
@@ -63,6 +156,10 @@ class ScriptCommand extends LocalCommand {
63
156
  const interpreter = lines[0].startsWith('#!')
64
157
  ? lines[0].slice(2).split(/\s/)[0]
65
158
  : lines[0];
159
+ if (this.stdinStream && typeof this.stdinStream.off === 'function') {
160
+ this.stdinStream.off('data', onParentStdin);
161
+ this.stdinStream.off('resize', onParentResize);
162
+ }
66
163
  return Promise.reject(`${interpreter}: bad interpreter: No such file or directory`);
67
164
  }
68
165
 
@@ -80,6 +177,12 @@ class ScriptCommand extends LocalCommand {
80
177
  return Promise.reject(e);
81
178
  }
82
179
  })
180
+ .finally(() => {
181
+ if (this.stdinStream && typeof this.stdinStream.off === 'function') {
182
+ this.stdinStream.off('data', onParentStdin);
183
+ this.stdinStream.off('resize', onParentResize);
184
+ }
185
+ })
83
186
  .then(() => {
84
187
  this.exitCode = this.sandbox.lastCode;
85
188
  if(this.source) {
@@ -447,9 +550,17 @@ class ScriptCommand extends LocalCommand {
447
550
  }
448
551
 
449
552
  async _executeFor(node) {
450
- const expanded = node.list.replace(/\${?([\w\d]+)}?/g, (m, name) =>
451
- this.sandbox.context.getVar(name) || '');
452
- const items = expanded.split(/\s+/).filter(Boolean);
553
+ let items;
554
+ if (node.list.trim() === '"$@"') {
555
+ const count = parseInt(this.sandbox.context.getVar('#') || '0', 10);
556
+ items = [];
557
+ for (let idx = 1; idx <= count; idx++) {
558
+ items.push(this.sandbox.context.getVar(String(idx)) || '');
559
+ }
560
+ } else {
561
+ const expanded = await this.sandbox._replaceVariables(node.list);
562
+ items = expanded.split(/\s+/).filter(Boolean);
563
+ }
453
564
  for (const value of items) {
454
565
  this.sandbox.context.setVar(node.variable, value);
455
566
  try {
@@ -569,7 +680,9 @@ class ScriptCommand extends LocalCommand {
569
680
  ? expanded.slice(1, -1) : expanded;
570
681
 
571
682
  for (const clause of node.clauses) {
572
- if (this._matchPattern(clause.pattern, value)) {
683
+ const cleaned = clause.pattern.replace(/^\(\s*/, '');
684
+ const alternatives = cleaned.split('|').map(p => p.trim());
685
+ if (alternatives.some(alt => this._matchPattern(alt, value))) {
573
686
  return this._executeNodes(this._parseLines(clause.bodyLines));
574
687
  }
575
688
  }