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.
package/index.js CHANGED
@@ -4,6 +4,7 @@ const Context = require('./lib/Context');
4
4
  const LocalCommand = require('./lib/local/LocalCommand');
5
5
  const ScriptCommand = require('./lib/ScriptCommand');
6
6
  const WasmCommand = require('./lib/WasmCommand');
7
+ const JsCommand = require('./lib/JsCommand');
7
8
  const Command = require('./lib/Command');
8
9
  const InteractiveCommand = require('./lib/InteractiveCommand');
9
10
  const { TtyStream } = require('./lib/TtyStream');
@@ -142,6 +143,13 @@ class Shell extends EventEmitter {
142
143
  this._initializing = false;
143
144
  }
144
145
  }
146
+
147
+ if (this.context.fs && typeof this.context.fs.setTtyDevice === 'function') {
148
+ this.context.fs.setTtyDevice({
149
+ write: (chunk) => this.stdout.write(chunk),
150
+ read: () => ''
151
+ });
152
+ }
145
153
  }
146
154
 
147
155
  async _initAsyncFilesystem(filesystemSource, permissions, cwd) {
@@ -188,6 +196,12 @@ class Shell extends EventEmitter {
188
196
  if (savedOnChange && this.context.fs) {
189
197
  this.context.fs._onChange = () => savedOnChange(this.context.fs.getRaw(), this.context.fs.getRawPermissions());
190
198
  }
199
+ if (this.context.fs && typeof this.context.fs.setTtyDevice === 'function') {
200
+ this.context.fs.setTtyDevice({
201
+ write: (chunk) => this.stdout.write(chunk),
202
+ read: () => ''
203
+ });
204
+ }
191
205
  } catch (err) {
192
206
  this.emit('stdErr', err.message || String(err));
193
207
  } finally {
@@ -1000,6 +1014,20 @@ class Shell extends EventEmitter {
1000
1014
 
1001
1015
  if (this.runningCommand) {
1002
1016
  const cmd = this.runningCommand;
1017
+ const isCtrlC = (typeof raw === 'string' && raw === '\x03')
1018
+ || (raw instanceof Uint8Array && raw.length === 1 && raw[0] === 3)
1019
+ || ((typeof Buffer !== 'undefined' && Buffer.isBuffer(raw)) && raw.length === 1 && raw[0] === 3);
1020
+
1021
+ if (isCtrlC && (!cmd.stdinStream || !cmd.stdinStream.isRaw)) {
1022
+ if (typeof cmd.kill === 'function') {
1023
+ cmd.kill('SIGINT');
1024
+ }
1025
+ if (!cmd.interactive && !cmd._inAltScreen) {
1026
+ this.stdout.write('^C\r\n');
1027
+ }
1028
+ return;
1029
+ }
1030
+
1003
1031
  const hasStreamListeners = cmd.stdinStream && cmd.stdinStream.listenerCount('data') > 1;
1004
1032
  if (cmd.captureInput || cmd.interactive || cmd._inAltScreen || hasStreamListeners) {
1005
1033
  cmd.stdinStream.pushData(raw);
@@ -1267,81 +1295,86 @@ class Shell extends EventEmitter {
1267
1295
  return segments;
1268
1296
  }
1269
1297
 
1298
+ _loadJsCommand(scriptPath, content) {
1299
+ if (!this._jsCommandCache) {
1300
+ this._jsCommandCache = new Map();
1301
+ }
1302
+ return JsCommand.load(this.context.fs, scriptPath, content, this._jsCommandCache);
1303
+ }
1304
+
1305
+ _findExecutablePath(basePath) {
1306
+ if (this.context.fs.exists(basePath)) return basePath;
1307
+ if (!basePath.endsWith('.wasm') && this.context.fs.exists(`${basePath}.wasm`)) return `${basePath}.wasm`;
1308
+ if (!basePath.endsWith('.js') && this.context.fs.exists(`${basePath}.js`)) return `${basePath}.js`;
1309
+ return null;
1310
+ }
1311
+
1312
+ _resolveCommandFromPath(binLocation) {
1313
+ const targetPath = this.context.fs.realpath(binLocation);
1314
+ if (!this.context.fs.isExecutable(binLocation) && !this.context.fs.isExecutable(targetPath)) {
1315
+ throw new Error(`${binLocation}: permission denied`);
1316
+ }
1317
+
1318
+ const handle = this.context.fs.getFileByPath(targetPath);
1319
+
1320
+ if (JsCommand.isCommandClass(handle)) {
1321
+ return handle;
1322
+ }
1323
+ if (typeof handle === 'string' && handle.startsWith('#!')) {
1324
+ return ScriptCommand.bind(this, handle);
1325
+ }
1326
+ if (WasmCommand.isWasmFile(targetPath, handle)) {
1327
+ return WasmCommand.bind(null, targetPath);
1328
+ }
1329
+ if (JsCommand.isJsFile(targetPath, handle)) {
1330
+ return this._loadJsCommand(targetPath, handle);
1331
+ }
1332
+
1333
+ return null;
1334
+ }
1335
+
1270
1336
  _parseCommand(command) {
1271
- if(command.startsWith('./') || command.startsWith('/')) {
1272
- const handle = this.context.fs._getFileRaw(command);
1273
- if(!handle) {
1337
+ if (command.startsWith('./') || command.startsWith('/') || command.startsWith('../') || command.includes('/')) {
1338
+ const absPath = this._findExecutablePath(this.context.fs.absolutePath(command));
1339
+ if (!absPath) {
1274
1340
  throw new Error(`${command}: No such file or directory`);
1275
1341
  }
1276
1342
 
1277
- if(handle.constructor === Object) {
1343
+ const stat = this.context.fs.stat(absPath);
1344
+ if (stat && stat.isDirectory) {
1278
1345
  throw new Error(`${command}: is a directory`);
1279
1346
  }
1280
1347
 
1281
- if(handle.prototype && typeof handle.prototype.run === 'function' && typeof handle.prototype.runCommand === 'function') {
1282
- if (!this.context.fs.isExecutable(command)) {
1283
- throw new Error(`${command}: permission denied`);
1284
- }
1285
- return handle;
1286
- }
1287
-
1288
- if(handle.constructor === String && handle.startsWith('#!')) {
1289
- if (!this.context.fs.isExecutable(command)) {
1290
- throw new Error(`${command}: permission denied`);
1291
- }
1292
- return ScriptCommand.bind(this, handle);
1293
- }
1294
-
1295
- if(this._isWasmFile(command, handle)) {
1296
- if (!this.context.fs.isExecutable(command)) {
1297
- throw new Error(`${command}: permission denied`);
1298
- }
1299
- return WasmCommand.bind(null, command);
1348
+ const cmd = this._resolveCommandFromPath(absPath);
1349
+ if (!cmd) {
1350
+ throw new Error(`${command}: permission denied`);
1300
1351
  }
1352
+ return cmd;
1353
+ }
1301
1354
 
1302
- // Executable .js files on the real filesystem: load via require() as a Command class.
1303
- if (this.context.fs.isRealFilesystem && typeof handle === 'string' && command.endsWith('.js')) {
1304
- if (!this.context.fs.isExecutable(command)) {
1305
- throw new Error(`${command}: permission denied`);
1306
- }
1307
- const abs = this.context.fs.absolutePath(command);
1308
- try {
1309
- const mod = require(abs);
1310
- const Cls = mod.default || mod;
1311
- if (typeof Cls === 'function' && typeof Cls.prototype.run === 'function' && typeof Cls.prototype.runCommand === 'function') {
1312
- return Cls;
1313
- }
1314
- } catch(e) {
1315
- // Not a loadable command module — fall through
1316
- }
1317
- }
1355
+ // 1. Built-in registered commands take precedence (mkdir, echo, cat, etc.)
1356
+ const builtin = this.context.getCommand(command)
1357
+ || (!command.endsWith('.wasm') && this.context.getCommand(`${command}.wasm`))
1358
+ || (!command.endsWith('.js') && this.context.getCommand(`${command}.js`));
1318
1359
 
1319
- throw new Error(`${command}: permission denied`);
1320
- }
1321
- let cmd = this.context.getCommand(command);
1322
- let cmdName = command;
1323
- if (!cmd && !command.endsWith('.wasm')) {
1324
- cmd = this.context.getCommand(`${command}.wasm`);
1325
- if (cmd) cmdName = `${command}.wasm`;
1360
+ if (JsCommand.isCommandClass(builtin)) {
1361
+ return builtin;
1326
1362
  }
1327
-
1328
- if(!cmd) {
1329
- throw new Error(`${command}: Command not found`);
1363
+ if (typeof builtin === 'string' && builtin.startsWith('#!')) {
1364
+ return ScriptCommand.bind(this, builtin);
1330
1365
  }
1331
1366
 
1332
- const binLocation = `${this.path}/${cmdName}`;
1333
- if (this._isWasmFile(binLocation, cmd)) {
1334
- if (!this.context.fs.isExecutable(binLocation)) {
1335
- throw new Error(`${command}: permission denied`);
1367
+ // 2. Search PATH directories for installed binaries, symlinks, scripts, and wasm
1368
+ const pathDirs = (this.context.getVar('PATH') || '/bin').split(':').filter(Boolean);
1369
+ for (const dir of pathDirs) {
1370
+ const binLocation = this._findExecutablePath(`${dir}/${command}`);
1371
+ if (binLocation) {
1372
+ const cmd = this._resolveCommandFromPath(binLocation);
1373
+ if (cmd) return cmd;
1336
1374
  }
1337
- return WasmCommand.bind(null, binLocation);
1338
- }
1339
-
1340
- if (typeof cmd === 'string' && cmd.startsWith('#!')) {
1341
- return ScriptCommand.bind(this, cmd);
1342
1375
  }
1343
1376
 
1344
- return cmd;
1377
+ throw new Error(`${command}: Command not found`);
1345
1378
  }
1346
1379
 
1347
1380
  async _parseCommandLine(string) {
@@ -1587,18 +1620,6 @@ class Shell extends EventEmitter {
1587
1620
  return parts;
1588
1621
  }
1589
1622
 
1590
- _isWasmFile(path, content) {
1591
- if (path.endsWith('.wasm') || path.endsWith('.wat')) return true;
1592
- if (content instanceof Uint8Array) {
1593
- return content.length >= 4 && content[0] === 0x00 && content[1] === 0x61 && content[2] === 0x73 && content[3] === 0x6d;
1594
- }
1595
- if (typeof content !== 'string') return false;
1596
- // Binary WASM: magic bytes \0asm
1597
- if (content.charCodeAt(0) === 0 && content.slice(1, 4) === 'asm') return true;
1598
- // WAT text format
1599
- return content.trimStart().startsWith('(module');
1600
- }
1601
-
1602
1623
  static _escapeRegExp(string) {
1603
1624
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1604
1625
  }
@@ -1637,6 +1658,7 @@ Shell.InteractiveCommand = InteractiveCommand;
1637
1658
  Shell.WasmCommand = WasmCommand;
1638
1659
  Shell.createWasmCommand = WasmCommand.createGenericWasmCommand || WasmCommand.createCommand;
1639
1660
  Shell.ReplCommand = require('./lib/ReplCommand');
1661
+ Shell.JsCommand = JsCommand;
1640
1662
  Shell.FS = BaseFileSystem;
1641
1663
  Shell.BinaryContainer = require('./lib/BinaryContainer');
1642
1664
  Shell.Storage = Shell.BinaryContainer.FilesystemStorage;
@@ -9,7 +9,8 @@ const SANDBOX_ALLOWED = new Set([
9
9
  'getMode', 'setMode',
10
10
  'isReadable', 'isWritable', 'isExecutable',
11
11
  'getSize', 'autoComplete',
12
- 'isRealFilesystem', 'isSymlink', 'readSymlink', 'createSymlink',
12
+ 'isRealFilesystem', 'isSymlink', 'readSymlink', 'createSymlink', 'realpath',
13
+ 'setTtyDevice', 'loadModule',
13
14
  ]);
14
15
 
15
16
  /**
@@ -33,6 +34,35 @@ const SANDBOX_ALLOWED = new Set([
33
34
  * addFiles(commands)
34
35
  */
35
36
  class BaseFileSystem {
37
+ /**
38
+ * Loads and evaluates a JavaScript module from the filesystem at `path`,
39
+ * returning its default or CommonJS export.
40
+ * Subclasses (like NodeFileSystem) can override this to use native module loaders.
41
+ */
42
+ loadModule(path) {
43
+ const content = this.getFileByPath(path);
44
+ if (content === null || content === undefined) {
45
+ throw new Error(`${path}: No such file or directory`);
46
+ }
47
+ if (typeof content === 'function') {
48
+ return content;
49
+ }
50
+ let code = typeof content === 'string' ? content : new TextDecoder().decode(content);
51
+ if (/^\s*export\s+default\s+/m.test(code)) {
52
+ code = code.replace(/^\s*export\s+default\s+/m, 'module.exports = ');
53
+ }
54
+
55
+ const moduleObj = { exports: {} };
56
+ const Command = require('./Command');
57
+ const LocalCommand = require('./local/LocalCommand');
58
+ const WasmCommand = require('./WasmCommand');
59
+ const InteractiveCommand = require('./InteractiveCommand');
60
+ const ReplCommand = require('./ReplCommand');
61
+ const fn = new Function('module', 'exports', 'require', 'Command', 'LocalCommand', 'WasmCommand', 'InteractiveCommand', 'ReplCommand', code);
62
+ fn(moduleObj, moduleObj.exports, require, Command, LocalCommand, WasmCommand, InteractiveCommand, ReplCommand);
63
+ return moduleObj.exports.default !== undefined ? moduleObj.exports.default : moduleObj.exports;
64
+ }
65
+
36
66
  isReadable(path) {
37
67
  const mode = this.getMode(path);
38
68
  if (mode === null) return false;
@@ -51,6 +81,22 @@ class BaseFileSystem {
51
81
  return (mode & 0o100) !== 0;
52
82
  }
53
83
 
84
+ /**
85
+ * Resolves symbolic links along `path`, returning the target absolute path.
86
+ */
87
+ realpath(path, maxHops = 10) {
88
+ let current = this.absolutePath(path);
89
+ let hops = 0;
90
+ while (hops++ < maxHops && typeof this.isSymlink === 'function' && this.isSymlink(current)) {
91
+ const link = this.readSymlink(current);
92
+ if (!link) break;
93
+ current = link.startsWith('/')
94
+ ? this.absolutePath(link)
95
+ : this.absolutePath(`${current.split('/').slice(0, -1).join('/')}/${link}`);
96
+ }
97
+ return current;
98
+ }
99
+
54
100
  // Returns a sandboxed proxy of this filesystem for use by commands.
55
101
  // Only the public API is accessible; raw/internal methods are blocked.
56
102
  sandbox() {
@@ -116,8 +162,35 @@ class SymlinkRef {
116
162
  constructor(target) {
117
163
  this.target = target;
118
164
  }
165
+
166
+ toJSON() {
167
+ return { $l: this.target };
168
+ }
119
169
  }
120
170
 
171
+ /**
172
+ * Represents a virtual character device node (e.g. /dev/null, /dev/zero, /dev/urandom, /dev/tty).
173
+ */
174
+ class DeviceFile {
175
+ constructor(name, options = {}) {
176
+ this.name = name;
177
+ this.read = typeof options.read === 'function' ? options.read : (() => '');
178
+ this.write = typeof options.write === 'function' ? options.write : (() => {});
179
+ this.mode = options.mode !== undefined ? options.mode : 0o666;
180
+ this.isCharacterDevice = true;
181
+ }
182
+
183
+ toString() {
184
+ const val = this.read();
185
+ return val != null ? (typeof val === 'string' ? val : val.toString()) : '';
186
+ }
187
+ }
188
+
189
+ const isUtf8Text = require('./isUtf8Text');
190
+
121
191
  module.exports = BaseFileSystem;
122
192
  module.exports.BinaryFile = BinaryFile;
123
193
  module.exports.SymlinkRef = SymlinkRef;
194
+ module.exports.DeviceFile = DeviceFile;
195
+ module.exports.isUtf8Text = isUtf8Text;
196
+
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { BinaryFile, SymlinkRef } = require('./BaseFileSystem');
3
+ const { BinaryFile, SymlinkRef, DeviceFile } = require('./BaseFileSystem');
4
4
 
5
5
  // 4-byte magic: "BRFS" (0x42, 0x52, 0x46, 0x53)
6
6
  const MAGIC = new Uint8Array([0x42, 0x52, 0x46, 0x53]);
@@ -63,6 +63,11 @@ function serializeBinaryFilesystem(filesystem = {}, permissions = {}, options =
63
63
  return { $l: node.target };
64
64
  }
65
65
 
66
+ if (node instanceof DeviceFile) {
67
+ // Devices are in-memory virtual overlays and must never be persisted
68
+ return null;
69
+ }
70
+
66
71
  if (node instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(node))) {
67
72
  const u8 = node instanceof Uint8Array
68
73
  ? new Uint8Array(node.buffer, node.byteOffset, node.byteLength)
@@ -225,6 +230,10 @@ function deserializeBinaryFilesystem(input, customCommandMap = {}) {
225
230
  return new SymlinkRef(entry.$l);
226
231
  }
227
232
 
233
+ if ('$dev' in entry) {
234
+ return new DeviceFile(entry.$dev);
235
+ }
236
+
228
237
  if ('$c' in entry) {
229
238
  const cmdPath = entry.$c;
230
239
  if (bundledCommands[cmdPath]) {
package/lib/Command.js CHANGED
@@ -33,6 +33,10 @@ class Command extends EventEmitter {
33
33
  if (!this.captureInput) return;
34
34
  const keys = parseVtKeys(chunk);
35
35
  for (const k of keys) {
36
+ if (k === '^C') {
37
+ this.kill('SIGINT');
38
+ return;
39
+ }
36
40
  if (!this.interactive && !this.stdinStream.isRaw) {
37
41
  if (k === 'Enter') this.stdout.write('\r\n');
38
42
  else if (k === 'Backspace') this.stdout.write('\b \b');
@@ -52,28 +56,66 @@ class Command extends EventEmitter {
52
56
  return Promise.reject("Command not implemented...");
53
57
  }
54
58
 
59
+ kill(signal = 'SIGINT') {
60
+ const sigNames = {
61
+ 'SIGHUP': 129,
62
+ 'SIGINT': 130,
63
+ 'SIGQUIT': 131,
64
+ 'SIGKILL': 137,
65
+ 'SIGTERM': 143,
66
+ 'SIGWINCH': 156,
67
+ };
68
+ const code = (typeof signal === 'number') ? signal : (sigNames[signal] || 130);
69
+ this.exitCode = code;
70
+ this.emit('signal', signal);
71
+ if (signal === 'SIGINT' || signal === 'SIGTERM' || signal === 'SIGKILL' || signal === 'SIGQUIT') {
72
+ this.emit('abort');
73
+ if (this._abortController) {
74
+ this._abortController.abort();
75
+ }
76
+ }
77
+ }
78
+
55
79
  runCommand() {
56
- return Promise.resolve()
57
- .then(() => this.run())
58
- .then(d => {
59
- if(d) {
60
- d.split(/\r?\n/).forEach(line => this.stdOut = line);
61
- }
62
- return this.result;
63
- })
64
- .catch(e => {
65
- // Re-throw shell control-flow signals (break, continue, return,
66
- // errexit) so they propagate correctly through function calls
67
- // and nested script execution.
68
- if (e && e.__type) {
69
- throw e;
70
- }
71
- if(e) {
72
- this.stdErr = e.message || e;
73
- }
74
- this.exitCode = 127;
75
- return this.result;
76
- });
80
+ return new Promise((resolve) => {
81
+ let settled = false;
82
+ const onAbort = () => {
83
+ if (settled) return;
84
+ settled = true;
85
+ resolve(this.result);
86
+ };
87
+ this.once('abort', onAbort);
88
+
89
+ Promise.resolve()
90
+ .then(() => this.run())
91
+ .then(d => {
92
+ if (settled) return;
93
+ settled = true;
94
+ this.removeListener('abort', onAbort);
95
+ if(d) {
96
+ d.split(/\r?\n/).forEach(line => this.stdOut = line);
97
+ }
98
+ resolve(this.result);
99
+ })
100
+ .catch(e => {
101
+ if (settled) return;
102
+ settled = true;
103
+ this.removeListener('abort', onAbort);
104
+ // Re-throw shell control-flow signals (break, continue, return,
105
+ // errexit) so they propagate correctly through function calls
106
+ // and nested script execution.
107
+ if (e && e.__type) {
108
+ throw e;
109
+ }
110
+ if(e) {
111
+ this.stdErr = e.message || e;
112
+ }
113
+ if (this.result.getExitCode() === 0) {
114
+ this.exitCode = 127;
115
+ }
116
+ resolve(this.result);
117
+ });
118
+ });
77
119
  }
78
120
 
79
121
  onInput(char) {
package/lib/Context.js CHANGED
@@ -9,7 +9,7 @@ class Context {
9
9
 
10
10
  this.vars = {};
11
11
  this.aliases = {};
12
- this.fs = new FileSystem(cwd, {}, {}, onFsChange || null);
12
+ this.fs = (this.options && this.options.fs) ? this.options.fs : new FileSystem(cwd, {}, {}, onFsChange || null);
13
13
  this._clearFn = clearFn;
14
14
  this._destroyFn = destroyFn;
15
15
  }