brsh 3.9.0 → 3.10.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/Readme.md +22 -4
  3. package/bin/Readme.md +33 -3
  4. package/bin/exportFileSystem.js +127 -110
  5. package/bin/wbt.js +118 -0
  6. package/dist/shell.es.js +4074 -3717
  7. package/dist/shell.es.js.map +1 -1
  8. package/dist/shell.min.js +26 -25
  9. package/dist/shell.min.js.map +1 -1
  10. package/dist/terminal.cjs.js +3 -3
  11. package/dist/terminal.cjs.js.map +1 -1
  12. package/dist/terminal.es.js +55 -33
  13. package/dist/terminal.es.js.map +1 -1
  14. package/dist/terminal.min.js +3 -3
  15. package/dist/terminal.min.js.map +1 -1
  16. package/dist/wbt.es.js +3082 -2710
  17. package/dist/wbt.es.js.map +1 -1
  18. package/dist/wbt.min.js +16 -12
  19. package/dist/wbt.min.js.map +1 -1
  20. package/index.js +102 -80
  21. package/lib/BaseFileSystem.js +57 -2
  22. package/lib/BinaryContainer.js +1 -1
  23. package/lib/Command.js +1 -1
  24. package/lib/Context.js +4 -3
  25. package/lib/FileSystem.js +4 -2
  26. package/lib/InteractiveCommand.js +9 -8
  27. package/lib/JsCommand.js +113 -0
  28. package/lib/NodeFileSystem.js +164 -30
  29. package/lib/Readme.md +1 -0
  30. package/lib/ScriptCommand.js +148 -8
  31. package/lib/Terminal.js +60 -6
  32. package/lib/TtyStream.js +36 -2
  33. package/lib/WasmCommand.js +313 -66
  34. package/lib/buildFilesystemStructure.js +38 -24
  35. package/lib/isUtf8Text.js +47 -0
  36. package/lib/local/which.js +8 -3
  37. package/lib/wbt/index.js +473 -175
  38. package/lib/wbt/registry.js +21 -1
  39. package/package.json +3 -2
  40. package/test/devices-signals.test.js +112 -0
  41. package/test/doom.test.js +7 -4
  42. package/test/exportFileSystem.test.js +37 -15
  43. package/test/js-command.test.js +125 -0
  44. package/test/node-filesystem.test.js +7 -0
  45. package/test/scripts.test.js +30 -0
  46. package/test/terminal.test.js +148 -0
  47. package/test/wasm-cli.test.js +76 -0
  48. package/test/wbt.test.js +418 -10
  49. package/test/wbtCli.test.js +160 -0
package/index.js CHANGED
@@ -4,9 +4,10 @@ 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
- const { TtyStream } = require('./lib/TtyStream');
10
+ const { TtyStream, hasCustomStdinListener } = require('./lib/TtyStream');
10
11
 
11
12
  const HISTORY_FILE = '/.brsh_history';
12
13
 
@@ -44,7 +45,9 @@ class Shell extends EventEmitter {
44
45
  permissions = {},
45
46
  cwd = '/',
46
47
  onFsChange,
47
- useRealFilesystem = false
48
+ useRealFilesystem = false,
49
+ cols,
50
+ rows
48
51
  } = options;
49
52
 
50
53
  this.context = new Context(Object.assign({}, options, {
@@ -77,15 +80,23 @@ class Shell extends EventEmitter {
77
80
  this._loadingFs = null;
78
81
  this._queuedWhileLoading = false;
79
82
 
80
- this.stdinStream = new TtyStream({ columns: 80, rows: 24 });
83
+ const initCols = (typeof cols === 'number' && cols > 0) ? Math.floor(cols) : 80;
84
+ const initRows = (typeof rows === 'number' && rows > 0) ? Math.floor(rows) : 24;
85
+ if ((typeof cols === 'number' && cols > 0) || (typeof rows === 'number' && rows > 0)) {
86
+ this._terminalSize = { cols: initCols, rows: initRows };
87
+ this.context.setVar('COLUMNS', String(initCols));
88
+ this.context.setVar('LINES', String(initRows));
89
+ }
90
+
91
+ this.stdinStream = new TtyStream({ columns: initCols, rows: initRows });
81
92
  this.stdout = new TtyStream({
82
- columns: 80,
83
- rows: 24,
93
+ columns: initCols,
94
+ rows: initRows,
84
95
  onWrite: (chunk) => this.emit('data', chunk)
85
96
  });
86
97
  this.stderr = new TtyStream({
87
- columns: 80,
88
- rows: 24,
98
+ columns: initCols,
99
+ rows: initRows,
89
100
  onWrite: (chunk) => this.emit('data', chunk)
90
101
  });
91
102
 
@@ -701,6 +712,22 @@ class Shell extends EventEmitter {
701
712
  };
702
713
 
703
714
  this.runningCommand = instance;
715
+ const liveCols = (this.stdout && this.stdout.columns) || (this.stdinStream && this.stdinStream.columns);
716
+ const liveRows = (this.stdout && this.stdout.rows) || (this.stdinStream && this.stdinStream.rows);
717
+ if (liveCols && liveRows) {
718
+ if (instance.stdinStream) {
719
+ instance.stdinStream.columns = liveCols;
720
+ instance.stdinStream.rows = liveRows;
721
+ }
722
+ if (instance.stdout) {
723
+ instance.stdout.columns = liveCols;
724
+ instance.stdout.rows = liveRows;
725
+ }
726
+ if (instance.stderr) {
727
+ instance.stderr.columns = liveCols;
728
+ instance.stderr.rows = liveRows;
729
+ }
730
+ }
704
731
  if(this.runningCommand.on) {
705
732
  this.runningCommand.on('flush', lines => {
706
733
  lines.forEach(routeLine);
@@ -1017,7 +1044,8 @@ class Shell extends EventEmitter {
1017
1044
  || (raw instanceof Uint8Array && raw.length === 1 && raw[0] === 3)
1018
1045
  || ((typeof Buffer !== 'undefined' && Buffer.isBuffer(raw)) && raw.length === 1 && raw[0] === 3);
1019
1046
 
1020
- if (isCtrlC && (!cmd.stdinStream || !cmd.stdinStream.isRaw)) {
1047
+ const cmdIsRaw = Boolean(cmd.isRaw || (cmd.stdinStream && cmd.stdinStream.isRaw));
1048
+ if (isCtrlC && !cmdIsRaw) {
1021
1049
  if (typeof cmd.kill === 'function') {
1022
1050
  cmd.kill('SIGINT');
1023
1051
  }
@@ -1027,7 +1055,7 @@ class Shell extends EventEmitter {
1027
1055
  return;
1028
1056
  }
1029
1057
 
1030
- const hasStreamListeners = cmd.stdinStream && cmd.stdinStream.listenerCount('data') > 1;
1058
+ const hasStreamListeners = hasCustomStdinListener(cmd);
1031
1059
  if (cmd.captureInput || cmd.interactive || cmd._inAltScreen || hasStreamListeners) {
1032
1060
  cmd.stdinStream.pushData(raw);
1033
1061
  return;
@@ -1294,81 +1322,86 @@ class Shell extends EventEmitter {
1294
1322
  return segments;
1295
1323
  }
1296
1324
 
1325
+ _loadJsCommand(scriptPath, content) {
1326
+ if (!this._jsCommandCache) {
1327
+ this._jsCommandCache = new Map();
1328
+ }
1329
+ return JsCommand.load(this.context.fs, scriptPath, content, this._jsCommandCache);
1330
+ }
1331
+
1332
+ _findExecutablePath(basePath) {
1333
+ if (this.context.fs.exists(basePath)) return basePath;
1334
+ if (!basePath.endsWith('.wasm') && this.context.fs.exists(`${basePath}.wasm`)) return `${basePath}.wasm`;
1335
+ if (!basePath.endsWith('.js') && this.context.fs.exists(`${basePath}.js`)) return `${basePath}.js`;
1336
+ return null;
1337
+ }
1338
+
1339
+ _resolveCommandFromPath(binLocation) {
1340
+ const targetPath = this.context.fs.realpath(binLocation);
1341
+ if (!this.context.fs.isExecutable(binLocation) && !this.context.fs.isExecutable(targetPath)) {
1342
+ throw new Error(`${binLocation}: permission denied`);
1343
+ }
1344
+
1345
+ const handle = this.context.fs.getFileByPath(targetPath);
1346
+
1347
+ if (JsCommand.isCommandClass(handle)) {
1348
+ return handle;
1349
+ }
1350
+ if (typeof handle === 'string' && handle.startsWith('#!')) {
1351
+ return ScriptCommand.bind(this, handle);
1352
+ }
1353
+ if (WasmCommand.isWasmFile(targetPath, handle)) {
1354
+ return WasmCommand.bind(null, targetPath);
1355
+ }
1356
+ if (JsCommand.isJsFile(targetPath, handle)) {
1357
+ return this._loadJsCommand(targetPath, handle);
1358
+ }
1359
+
1360
+ return null;
1361
+ }
1362
+
1297
1363
  _parseCommand(command) {
1298
- if(command.startsWith('./') || command.startsWith('/')) {
1299
- const handle = this.context.fs._getFileRaw(command);
1300
- if(!handle) {
1364
+ if (command.startsWith('./') || command.startsWith('/') || command.startsWith('../') || command.includes('/')) {
1365
+ const absPath = this._findExecutablePath(this.context.fs.absolutePath(command));
1366
+ if (!absPath) {
1301
1367
  throw new Error(`${command}: No such file or directory`);
1302
1368
  }
1303
1369
 
1304
- if(handle.constructor === Object) {
1370
+ const stat = this.context.fs.stat(absPath);
1371
+ if (stat && stat.isDirectory) {
1305
1372
  throw new Error(`${command}: is a directory`);
1306
1373
  }
1307
1374
 
1308
- if(handle.prototype && typeof handle.prototype.run === 'function' && typeof handle.prototype.runCommand === 'function') {
1309
- if (!this.context.fs.isExecutable(command)) {
1310
- throw new Error(`${command}: permission denied`);
1311
- }
1312
- return handle;
1375
+ const cmd = this._resolveCommandFromPath(absPath);
1376
+ if (!cmd) {
1377
+ throw new Error(`${command}: permission denied`);
1313
1378
  }
1379
+ return cmd;
1380
+ }
1314
1381
 
1315
- if(handle.constructor === String && handle.startsWith('#!')) {
1316
- if (!this.context.fs.isExecutable(command)) {
1317
- throw new Error(`${command}: permission denied`);
1318
- }
1319
- return ScriptCommand.bind(this, handle);
1320
- }
1382
+ // 1. Built-in registered commands take precedence (mkdir, echo, cat, etc.)
1383
+ const builtin = this.context.getCommand(command)
1384
+ || (!command.endsWith('.wasm') && this.context.getCommand(`${command}.wasm`))
1385
+ || (!command.endsWith('.js') && this.context.getCommand(`${command}.js`));
1321
1386
 
1322
- if(this._isWasmFile(command, handle)) {
1323
- if (!this.context.fs.isExecutable(command)) {
1324
- throw new Error(`${command}: permission denied`);
1325
- }
1326
- return WasmCommand.bind(null, command);
1327
- }
1328
-
1329
- // Executable .js files on the real filesystem: load via require() as a Command class.
1330
- if (this.context.fs.isRealFilesystem && typeof handle === 'string' && command.endsWith('.js')) {
1331
- if (!this.context.fs.isExecutable(command)) {
1332
- throw new Error(`${command}: permission denied`);
1333
- }
1334
- const abs = this.context.fs.absolutePath(command);
1335
- try {
1336
- const mod = require(abs);
1337
- const Cls = mod.default || mod;
1338
- if (typeof Cls === 'function' && typeof Cls.prototype.run === 'function' && typeof Cls.prototype.runCommand === 'function') {
1339
- return Cls;
1340
- }
1341
- } catch(e) {
1342
- // Not a loadable command module — fall through
1343
- }
1344
- }
1345
-
1346
- throw new Error(`${command}: permission denied`);
1387
+ if (JsCommand.isCommandClass(builtin)) {
1388
+ return builtin;
1347
1389
  }
1348
- let cmd = this.context.getCommand(command);
1349
- let cmdName = command;
1350
- if (!cmd && !command.endsWith('.wasm')) {
1351
- cmd = this.context.getCommand(`${command}.wasm`);
1352
- if (cmd) cmdName = `${command}.wasm`;
1390
+ if (typeof builtin === 'string' && builtin.startsWith('#!')) {
1391
+ return ScriptCommand.bind(this, builtin);
1353
1392
  }
1354
1393
 
1355
- if(!cmd) {
1356
- throw new Error(`${command}: Command not found`);
1357
- }
1358
-
1359
- const binLocation = `${this.path}/${cmdName}`;
1360
- if (this._isWasmFile(binLocation, cmd)) {
1361
- if (!this.context.fs.isExecutable(binLocation)) {
1362
- throw new Error(`${command}: permission denied`);
1394
+ // 2. Search PATH directories for installed binaries, symlinks, scripts, and wasm
1395
+ const pathDirs = (this.context.getVar('PATH') || '/bin').split(':').filter(Boolean);
1396
+ for (const dir of pathDirs) {
1397
+ const binLocation = this._findExecutablePath(`${dir}/${command}`);
1398
+ if (binLocation) {
1399
+ const cmd = this._resolveCommandFromPath(binLocation);
1400
+ if (cmd) return cmd;
1363
1401
  }
1364
- return WasmCommand.bind(null, binLocation);
1365
1402
  }
1366
1403
 
1367
- if (typeof cmd === 'string' && cmd.startsWith('#!')) {
1368
- return ScriptCommand.bind(this, cmd);
1369
- }
1370
-
1371
- return cmd;
1404
+ throw new Error(`${command}: Command not found`);
1372
1405
  }
1373
1406
 
1374
1407
  async _parseCommandLine(string) {
@@ -1614,18 +1647,6 @@ class Shell extends EventEmitter {
1614
1647
  return parts;
1615
1648
  }
1616
1649
 
1617
- _isWasmFile(path, content) {
1618
- if (path.endsWith('.wasm') || path.endsWith('.wat')) return true;
1619
- if (content instanceof Uint8Array) {
1620
- return content.length >= 4 && content[0] === 0x00 && content[1] === 0x61 && content[2] === 0x73 && content[3] === 0x6d;
1621
- }
1622
- if (typeof content !== 'string') return false;
1623
- // Binary WASM: magic bytes \0asm
1624
- if (content.charCodeAt(0) === 0 && content.slice(1, 4) === 'asm') return true;
1625
- // WAT text format
1626
- return content.trimStart().startsWith('(module');
1627
- }
1628
-
1629
1650
  static _escapeRegExp(string) {
1630
1651
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1631
1652
  }
@@ -1664,6 +1685,7 @@ Shell.InteractiveCommand = InteractiveCommand;
1664
1685
  Shell.WasmCommand = WasmCommand;
1665
1686
  Shell.createWasmCommand = WasmCommand.createGenericWasmCommand || WasmCommand.createCommand;
1666
1687
  Shell.ReplCommand = require('./lib/ReplCommand');
1688
+ Shell.JsCommand = JsCommand;
1667
1689
  Shell.FS = BaseFileSystem;
1668
1690
  Shell.BinaryContainer = require('./lib/BinaryContainer');
1669
1691
  Shell.Storage = Shell.BinaryContainer.FilesystemStorage;
@@ -9,8 +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',
13
- 'setTtyDevice',
12
+ 'isRealFilesystem', 'isSymlink', 'readSymlink', 'createSymlink', 'realpath',
13
+ 'setTtyDevice', 'loadModule',
14
14
  ]);
15
15
 
16
16
  /**
@@ -34,6 +34,35 @@ const SANDBOX_ALLOWED = new Set([
34
34
  * addFiles(commands)
35
35
  */
36
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
+
37
66
  isReadable(path) {
38
67
  const mode = this.getMode(path);
39
68
  if (mode === null) return false;
@@ -52,12 +81,30 @@ class BaseFileSystem {
52
81
  return (mode & 0o100) !== 0;
53
82
  }
54
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
+
55
100
  // Returns a sandboxed proxy of this filesystem for use by commands.
56
101
  // Only the public API is accessible; raw/internal methods are blocked.
57
102
  sandbox() {
58
103
  const target = this;
104
+ const targetSym = Symbol.for('brsh.fs.target');
59
105
  return new Proxy(Object.create(null), {
60
106
  get(_, prop) {
107
+ if (prop === targetSym) return target;
61
108
  if (!SANDBOX_ALLOWED.has(prop)) return undefined;
62
109
  const val = target[prop];
63
110
  return typeof val === 'function' ? val.bind(target) : val;
@@ -117,6 +164,10 @@ class SymlinkRef {
117
164
  constructor(target) {
118
165
  this.target = target;
119
166
  }
167
+
168
+ toJSON() {
169
+ return { $l: this.target };
170
+ }
120
171
  }
121
172
 
122
173
  /**
@@ -137,7 +188,11 @@ class DeviceFile {
137
188
  }
138
189
  }
139
190
 
191
+ const isUtf8Text = require('./isUtf8Text');
192
+
140
193
  module.exports = BaseFileSystem;
141
194
  module.exports.BinaryFile = BinaryFile;
142
195
  module.exports.SymlinkRef = SymlinkRef;
143
196
  module.exports.DeviceFile = DeviceFile;
197
+ module.exports.isUtf8Text = isUtf8Text;
198
+
@@ -81,7 +81,7 @@ function serializeBinaryFilesystem(filesystem = {}, permissions = {}, options =
81
81
  // If an external commandsBundle is provided, reference by virtualPath;
82
82
  // otherwise store the function's source code so client-side persistence works standalone!
83
83
  if (!options.commandsBundle) {
84
- inlineCommandSources[virtualPath] = node.toString();
84
+ inlineCommandSources[virtualPath] = node.__source || node.toString();
85
85
  }
86
86
  return { $c: virtualPath };
87
87
  }
package/lib/Command.js CHANGED
@@ -33,7 +33,7 @@ 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') {
36
+ if (k === '^C' && !(this.stdinStream && this.stdinStream.isRaw)) {
37
37
  this.kill('SIGINT');
38
38
  return;
39
39
  }
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
  }
@@ -78,8 +78,9 @@ class Context {
78
78
  }
79
79
 
80
80
  source(context) {
81
- this.vars = Object.assign({}, this.vars, context.vars);
82
- this.aliases = Object.assign({}, this.aliases, context.aliases);
81
+ if (!context) return;
82
+ this.vars = Object.assign({}, this.vars, context.vars || {});
83
+ this.aliases = Object.assign({}, this.aliases, context.aliases || {});
83
84
  }
84
85
 
85
86
  clear() {
package/lib/FileSystem.js CHANGED
@@ -12,7 +12,9 @@ const { BinaryFile, SymlinkRef, DeviceFile } = BaseFileSystem;
12
12
  function decodeBinaryFiles(node) {
13
13
  for (const key of Object.keys(node)) {
14
14
  const value = node[key];
15
- if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof SymlinkRef) && !(value instanceof DeviceFile)) {
15
+ if (value && typeof value === 'object' && ('$l' in value)) {
16
+ node[key] = new SymlinkRef(value.$l);
17
+ } else if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof SymlinkRef) && !(value instanceof DeviceFile)) {
16
18
  decodeBinaryFiles(value);
17
19
  } else if (typeof value === 'string' && value.startsWith('data:')) {
18
20
  const semicolon = value.indexOf(';');
@@ -165,7 +167,7 @@ class FileSystem extends BaseFileSystem {
165
167
  return file instanceof SymlinkRef ? file.target : null;
166
168
  }
167
169
  createSymlink(target, linkPath) {
168
- this._setFileRaw(linkPath, new SymlinkRef(target));
170
+ this._setFileRaw(linkPath, new SymlinkRef(target), true);
169
171
  }
170
172
 
171
173
  // Returns type metadata without following the final symlink (like lstat).
@@ -41,13 +41,14 @@ class InteractiveCommand extends Command {
41
41
  * @returns {{ cols: number, rows: number }}
42
42
  */
43
43
  get terminalSize() {
44
- if (this.stdout && this.stdout.columns && this.stdout.rows) {
45
- const cols = parseInt(this.context && this.context.getVar && this.context.getVar('COLUMNS'), 10) || this.stdout.columns || 80;
46
- const rows = parseInt(this.context && this.context.getVar && this.context.getVar('LINES'), 10) || this.stdout.rows || 24;
47
- return { cols, rows };
48
- }
49
- const cols = parseInt(this.context.getVar('COLUMNS'), 10) || 80;
50
- const rows = parseInt(this.context.getVar('LINES'), 10) || 24;
44
+ const cols = (this.stdout && this.stdout.columns)
45
+ || (this.stdinStream && this.stdinStream.columns)
46
+ || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('COLUMNS'), 10))
47
+ || 80;
48
+ const rows = (this.stdout && this.stdout.rows)
49
+ || (this.stdinStream && this.stdinStream.rows)
50
+ || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('LINES'), 10))
51
+ || 24;
51
52
  return { cols, rows };
52
53
  }
53
54
 
@@ -62,7 +63,7 @@ class InteractiveCommand extends Command {
62
63
  if (!this._inAltScreen) return;
63
64
  this._inAltScreen = false;
64
65
  if (this.stdinStream) this.stdinStream.setRawMode(false);
65
- if (this.stdout) this.stdout.write('\x1b[?1049l\x1b[?25h');
66
+ if (this.stdout) this.stdout.write('\x1b[0m\x1b[?1l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l\x1b[?25h');
66
67
  }
67
68
 
68
69
  kill(signal = 'SIGINT') {
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+
3
+ const WasmCommand = require('./WasmCommand');
4
+
5
+ /**
6
+ * Handles loading, evaluating, and wrapping JavaScript commands and modules
7
+ * stored on the brsh virtual or real filesystem.
8
+ */
9
+ class JsCommand {
10
+ static isCommandClass(fn) {
11
+ return typeof fn === 'function'
12
+ && Boolean(fn.prototype)
13
+ && typeof fn.prototype.run === 'function'
14
+ && typeof fn.prototype.runCommand === 'function';
15
+ }
16
+
17
+ static isJsFile(scriptPath, content) {
18
+ if (typeof content === 'function') return true;
19
+ if (scriptPath && scriptPath.endsWith('.js')) return true;
20
+ return typeof content === 'string' && (content.includes('export') || content.includes('module.exports'));
21
+ }
22
+
23
+ /**
24
+ * Loads a JavaScript module from the filesystem, evaluates it,
25
+ * and returns an executable Command class.
26
+ *
27
+ * @param {Object} fs - The filesystem instance (BaseFileSystem / NodeFileSystem)
28
+ * @param {string} scriptPath - Absolute path to the .js script
29
+ * @param {string|Function|null} content - Optional pre-read content or function
30
+ * @param {Map} [cache] - Optional cache Map to store evaluated classes by scriptPath
31
+ * @returns {Function} Executable Command constructor
32
+ */
33
+ static load(fs, scriptPath, content = null, cache = null) {
34
+ const fileContent = content !== null && content !== undefined
35
+ ? content
36
+ : (fs && typeof fs.getFileByPath === 'function' ? fs.getFileByPath(scriptPath) : null);
37
+
38
+ if (cache && cache.has(scriptPath)) {
39
+ const cached = cache.get(scriptPath);
40
+ if (cached && cached.content === fileContent) {
41
+ return cached.Cmd;
42
+ }
43
+ }
44
+
45
+ if (typeof fileContent === 'function') {
46
+ const Cmd = JsCommand.isCommandClass(fileContent)
47
+ ? fileContent
48
+ : JsCommand.wrapModule(fs, scriptPath, fileContent);
49
+ if (cache) {
50
+ cache.set(scriptPath, { content: fileContent, Cmd });
51
+ }
52
+ return Cmd;
53
+ }
54
+
55
+ let exported = null;
56
+ try {
57
+ if (fs && typeof fs.loadModule === 'function') {
58
+ exported = fs.loadModule(scriptPath);
59
+ } else {
60
+ const nodeReq = typeof require !== 'undefined' ? require : null;
61
+ if (nodeReq) {
62
+ exported = nodeReq(scriptPath);
63
+ } else {
64
+ throw new Error('loadModule is not available on filesystem');
65
+ }
66
+ }
67
+ } catch (e) {
68
+ throw new Error(`${scriptPath}: Failed to evaluate script: ${e.message}`);
69
+ }
70
+
71
+ const Cmd = JsCommand.isCommandClass(exported)
72
+ ? exported
73
+ : JsCommand.wrapModule(fs, scriptPath, exported);
74
+
75
+ if (cache) {
76
+ cache.set(scriptPath, { content: fileContent, Cmd });
77
+ }
78
+ return Cmd;
79
+ }
80
+
81
+ /**
82
+ * Wraps a non-Command export (e.g. exported function or module object)
83
+ * as an executable GenericWasmCommand, automatically detecting any sibling .wasm binary.
84
+ *
85
+ * @param {Object} fs - The filesystem instance
86
+ * @param {string} scriptPath - Absolute path to the .js file
87
+ * @param {*} exported - The module's exported value
88
+ * @returns {Function} Executable Command constructor
89
+ */
90
+ static wrapModule(fs, scriptPath, exported) {
91
+ const binName = scriptPath.split('/').pop().replace(/\.js$/i, '').toLowerCase();
92
+ const siblingWasmPath = scriptPath.replace(/\.js$/i, '.wasm');
93
+ const hasSiblingWasm = fs && typeof fs.exists === 'function' && fs.exists(siblingWasmPath);
94
+ const wasmBytes = (hasSiblingWasm && typeof fs.getFileByPath === 'function')
95
+ ? fs.getFileByPath(siblingWasmPath)
96
+ : null;
97
+
98
+ const pkgMeta = {
99
+ name: binName,
100
+ bin: binName,
101
+ wasmPath: hasSiblingWasm ? siblingWasmPath : null,
102
+ wasmBytes: wasmBytes || null
103
+ };
104
+
105
+ const config = {
106
+ moduleLoader: async () => exported
107
+ };
108
+
109
+ return WasmCommand.createGenericWasmCommand(pkgMeta, config, binName);
110
+ }
111
+ }
112
+
113
+ module.exports = JsCommand;