brsh 3.0.0 → 3.1.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.
package/index.js CHANGED
@@ -1286,6 +1286,26 @@ class Shell extends EventEmitter {
1286
1286
  continue;
1287
1287
  }
1288
1288
 
1289
+ // Escape handling inside double quotes
1290
+ if (doubleQuoteOpen && ch === '\\' && i + 1 < string.length) {
1291
+ const next = string[i + 1];
1292
+ if (next === '"' || next === '\\' || next === '$') {
1293
+ tokenBuffer.push(next);
1294
+ i++;
1295
+ continue;
1296
+ }
1297
+ }
1298
+
1299
+ // Escape handling outside quotes
1300
+ if (!singleQuoteOpen && !doubleQuoteOpen && ch === '\\' && i + 1 < string.length) {
1301
+ const next = string[++i];
1302
+ tokenBuffer.push(next);
1303
+ if (next === '"' || next === "'") {
1304
+ tokenHasQuote = true;
1305
+ }
1306
+ continue;
1307
+ }
1308
+
1289
1309
  // Quote handling
1290
1310
  if (ch === "'" && !doubleQuoteOpen) {
1291
1311
  singleQuoteOpen = !singleQuoteOpen;
package/lib/Readme.md CHANGED
@@ -1,21 +1,120 @@
1
- # Extending Command
1
+ # Writing Custom Commands (`lib/`)
2
+
3
+ `brsh` exposes four command base classes on the `Shell` constructor so you can write everything from simple one-shot utilities to full-screen interactive TUI applications and WebAssembly tools:
4
+
5
+ * `Shell.Command` — Standard CLI command (output lines, exit codes, streaming output, piped stdin, optional filesystem access)
6
+ * `Shell.InteractiveCommand` — Full-screen interactive TUI application (alternate screen buffer `?1049h`, raw key input, terminal dimensions)
7
+ * `Shell.ReplCommand` — Hybrid CLI + interactive full-screen REPL command
8
+ * `Shell.WasmCommand` / `Shell.createWasmCommand` — WASI / Emscripten / ESM WebAssembly command wrapper
9
+
10
+ ---
11
+
12
+ ## 1. Standard Commands (`Shell.Command`)
13
+
14
+ Extend `Shell.Command` and register your class via `shell.context.setCommand(MyCommand)` (or place it in `/bin` inside your virtual filesystem):
2
15
 
3
- to create a new command you will need to extend Command, you can either access command as a Static property of Shell:
4
16
  ```js
5
- class Test extends Shell.Command {
6
- ...
17
+ const Shell = require('brsh');
18
+
19
+ class GreetCommand extends Shell.Command {
20
+ static get name() { return 'greet'; }
21
+ get name() { return 'greet'; }
22
+
23
+ // Set to true if the command needs access to `this.fs` (sandboxed filesystem)
24
+ get requiresFilesystem() { return false; }
25
+
26
+ async run() {
27
+ const target = this.arguments[0] || 'world';
28
+ this.stdOut = `Hello, ${target}!`;
29
+ this.exitCode = 0;
30
+ }
7
31
  }
32
+
33
+ shell.context.setCommand(GreetCommand);
8
34
  ```
9
-
10
- or Require Command directly:
35
+
36
+ ### Properties & Methods on `Command`
37
+
38
+ | Property / Method | Description |
39
+ | --- | --- |
40
+ | `this.arguments` | `Array<String>` of parsed command-line arguments |
41
+ | `this.context` | Read-only shell context (`getVar(name)`, `getAlias(name)`, `getCommand(name)`) |
42
+ | `this.fs` | Sandboxed filesystem instance (only populated when `get requiresFilesystem() { return true; }`) |
43
+ | `this.stdin` | Piped input string when invoked in a pipeline (`cmd1 \| mycmd`), or `this.stdinStream` (`TtyStream`) |
44
+ | `this.stdout` / `this.stderr` | `TtyStream` instances (`columns`, `rows`, `write(chunk)`) |
45
+ | `this.stdOut = line` | Appends a line to standard output |
46
+ | `this.stdErr = line` | Appends a line to standard error |
47
+ | `this.exitCode = code` | Sets the numeric exit code (defaults to `0`, or `127` on unhandled rejection) |
48
+ | `this.flush()` | Immediately flushes any queued `stdOut` / `stdErr` lines to the shell before `run()` finishes (also supports `\r` in-place progress lines) |
49
+ | `this.captureInput` | Return `true` to receive live user keystrokes via `onInput(key)` while the command is running (e.g. `read`) |
50
+
51
+ ### Sandboxed Filesystem API (`this.fs`)
52
+
53
+ When `get requiresFilesystem() { return true; }` is set on a command, `this.fs` provides:
54
+ * `getFileByPath(path)` / `setFileByPath(path, content, createDir)` / `deleteFileByPath(path)`
55
+ * `exists(path)` / `stat(path)` / `getSize(path)` / `absolutePath(path)`
56
+ * `getMode(path)` / `setMode(path, mode)` / `isReadable(path)` / `isWritable(path)` / `isExecutable(path)`
57
+ * `isSymlink(path)` / `readSymlink(path)` / `createSymlink(target, linkPath)`
58
+
59
+ ---
60
+
61
+ ## 2. Full-Screen Interactive Apps (`Shell.InteractiveCommand`)
62
+
63
+ Extend `Shell.InteractiveCommand` for full-screen terminal applications (like `pico`). `InteractiveCommand` automatically switches the terminal into the alternate screen buffer (`\x1b[?1049h`) and raw input mode on start, and restores the primary screen on exit.
64
+
11
65
  ```js
12
- const Command = require('shell.js/lib/Command');
13
-
14
- class Test extends Command {
15
- ...
66
+ class MyEditor extends Shell.InteractiveCommand {
67
+ static get name() { return 'myeditor'; }
68
+ get name() { return 'myeditor'; }
69
+ get requiresFilesystem() { return true; }
70
+
71
+ run() {
72
+ return new Promise((resolve) => {
73
+ this._exit = resolve;
74
+ this.render();
75
+ });
76
+ }
77
+
78
+ onInput(key) {
79
+ if (key === '^X' || key === 'Escape') {
80
+ this._exit();
81
+ return;
82
+ }
83
+ this.render(key);
84
+ }
85
+
86
+ render(lastKey = '') {
87
+ const { cols, rows } = this.terminalSize;
88
+ this.stdOut = `\x1b[2J\x1b[HLast key: ${lastKey} (${cols}x${rows})\nPress Ctrl+X to exit.`;
89
+ this.flush();
90
+ }
16
91
  }
17
92
  ```
18
93
 
19
- for some examples see the [implementation for piratemedia.tv](https://github.com/eliotstocker/piratemedia.tv/tree/master/fs/bin)
94
+ `onInput(key)` receives:
95
+ * Printable characters: `'a'`, `'B'`, `'1'`, `' '`, etc.
96
+ * Named navigation keys: `'ArrowUp'`, `'ArrowDown'`, `'ArrowLeft'`, `'ArrowRight'`, `'Enter'`, `'Backspace'`, `'Delete'`, `'Escape'`, `'Home'`, `'End'`, `'PageUp'`, `'PageDown'`, `'Tab'`
97
+ * Control combinations: `'^A'` through `'^Z'`
98
+
99
+ See [demo/pico.js](../demo/pico.js) for a complete implementation.
100
+
101
+ ---
102
+
103
+ ## 3. Interactive REPL Commands (`Shell.ReplCommand`)
20
104
 
21
- more info coming soon...
105
+ Extend `Shell.ReplCommand` when a command supports both non-interactive CLI invocations (`runNonInteractive()`) and a full-screen interactive REPL with history, scrolling, and multi-line input (either by overriding `shouldBeInteractive()` / `initRepl()` / `evaluateReplLine(line)` or by calling `this.startRepl(opts)` dynamically).
106
+
107
+ ---
108
+
109
+ ## 4. WebAssembly Commands (`Shell.createWasmCommand`)
110
+
111
+ Wrap any WASI `.wasm` binary or ESM/Emscripten module into a `brsh` command:
112
+
113
+ ```js
114
+ const MyWasmTool = Shell.createWasmCommand({
115
+ name: 'mytool',
116
+ wasmUrl: 'https://example.com/mytool.wasm'
117
+ });
118
+
119
+ shell.context.setCommand(MyWasmTool);
120
+ ```
@@ -135,7 +135,11 @@ class WasmCommand extends ScriptCommand {
135
135
  if (outBuf[2]) { this.stdErr = outBuf[2]; outBuf[2] = ''; }
136
136
  };
137
137
 
138
- const stdinBytes = encoder.encode(this.stdin || '');
138
+ const stdinBytes = typeof this.stdin === 'string'
139
+ ? encoder.encode(this.stdin)
140
+ : (this.stdin instanceof Uint8Array
141
+ ? this.stdin
142
+ : (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.stdin) ? new Uint8Array(this.stdin) : new Uint8Array(0)));
139
143
  let stdinPos = 0;
140
144
 
141
145
  // ── Virtual WASI file descriptor table backed by this.context.fs ──
@@ -965,10 +969,26 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
965
969
 
966
970
  try {
967
971
  // 1. Direct `.wasm` URL or persisted raw WASI binary -> run via WasmCommand
968
- if (pkgMeta.type === 'wasm' && (this._persistedWasmBytes || pkgMeta.wasmUrl) && !config.moduleLoader) {
969
- const bytes = this._persistedWasmBytes || await this._fetchWasmBytes(pkgMeta.wasmUrl);
970
- if (isHelp) this._inspectedWasm = inspectWasmBytes(bytes);
971
- await this._runRawWasmBytes(bytes, args);
972
+ if ((pkgMeta.type === 'wasm' || pkgMeta.type === 'custom-wasm') && (this._persistedWasmBytes || pkgMeta.wasmUrl)) {
973
+ let bytes = this._persistedWasmBytes;
974
+ if (!bytes && config.moduleLoader) {
975
+ try {
976
+ const loaded = await config.moduleLoader(pkgMeta.name, pkgMeta.cdnUrl);
977
+ if (loaded instanceof Uint8Array || loaded instanceof ArrayBuffer) {
978
+ bytes = loaded instanceof Uint8Array ? loaded : new Uint8Array(loaded);
979
+ } else if (loaded && (loaded.wasmBytes || loaded.wasm || loaded.wasmBinary)) {
980
+ bytes = loaded.wasmBytes || loaded.wasm || loaded.wasmBinary;
981
+ }
982
+ } catch { /* ignore */ }
983
+ }
984
+ if (!bytes && pkgMeta.wasmUrl) {
985
+ bytes = await this._fetchWasmBytes(pkgMeta.wasmUrl);
986
+ }
987
+ if (bytes) {
988
+ if (isHelp) this._inspectedWasm = inspectWasmBytes(bytes);
989
+ await this._runRawWasmBytes(bytes, args);
990
+ return;
991
+ }
972
992
  } else {
973
993
  const cdnUrl = pkgMeta.cdnUrl || pkgMeta.wasmUrl || `https://esm.sh/${pkgMeta.name}`;
974
994
  const origFetch = typeof globalThis.fetch === 'function' ? globalThis.fetch : null;
@@ -1495,3 +1515,4 @@ WasmCommand.createGenericWasmCommand = createGenericWasmCommand;
1495
1515
  WasmCommand.createCommand = createGenericWasmCommand;
1496
1516
 
1497
1517
  module.exports = WasmCommand;
1518
+
package/lib/wbt/index.js CHANGED
@@ -122,7 +122,7 @@ class Wbt extends LocalCommand {
122
122
  _buildCommandsForPackage(pkgMeta) {
123
123
  const cfg = this.constructor._config || {};
124
124
 
125
- if (pkgMeta.type === 'custom-wasm' && pkgMeta.wasmPath) {
125
+ if ((pkgMeta.type === 'custom-wasm' || pkgMeta.type === 'wasm') && pkgMeta.wasmPath) {
126
126
  const binName = (pkgMeta.bin || pkgMeta.name).toLowerCase();
127
127
  return [{ bin: binName, Cmd: createCustomWasmBinCommand(binName, pkgMeta.wasmPath, pkgMeta) }];
128
128
  }
@@ -1000,7 +1000,8 @@ class Wbt extends LocalCommand {
1000
1000
  ' wabt WebAssembly Binary Toolkit (wat2wasm, wasm2wat)',
1001
1001
  ' quickjs Sandboxed QuickJS JavaScript engine (qjs)',
1002
1002
  ' lua Lua 5.4 WebAssembly interpreter (lua)',
1003
- ' wllama WASM & WebGPU LLM inference engine (wllama, llama, llama-cli)'
1003
+ ' wllama WASM & WebGPU LLM inference engine (wllama, llama, llama-cli)',
1004
+ ' nano GNU nano 8.0 text editor with ncurses (nano, nano-wasm)'
1004
1005
  ].forEach(l => { this.stdOut = l; });
1005
1006
  }
1006
1007
  }
@@ -166,6 +166,19 @@ const DEFAULT_REGISTRY = {
166
166
  type: 'builtin-adapter',
167
167
  adapter: 'wllama',
168
168
  size: '8.8 MB'
169
+ },
170
+ nano: {
171
+ name: 'nano',
172
+ bin: 'nano',
173
+ aliases: ['nano-wasm'],
174
+ version: '8.0.0',
175
+ description: 'GNU nano 8.0 text editor compiled to WebAssembly (wasm32-wasip1) with ncurses',
176
+ details: 'GNU nano is a small, user-friendly command-line text editor compiled to WebAssembly with wide-character ncurses 6.5, built-in terminfo fallbacks (xterm-256color, vt100, etc.), dynamic terminal dimensions (TIOCGWINSZ / LINES & COLUMNS), and zero custom imports (standard wasi_snapshot_preview1).',
177
+ homepage: 'https://github.com/eliotstocker/nano-wasm',
178
+ cdnUrl: 'https://cdn.jsdelivr.net/gh/eliotstocker/nano-wasm@main/dist/nano.wasm',
179
+ wasmUrl: 'https://cdn.jsdelivr.net/gh/eliotstocker/nano-wasm@main/dist/nano.wasm',
180
+ type: 'custom-wasm',
181
+ size: '574 KB'
169
182
  }
170
183
  };
171
184
 
@@ -186,7 +199,8 @@ const PACKAGE_ALIASES = {
186
199
  llama: 'wllama',
187
200
  'llama-cli': 'wllama',
188
201
  'llama.cpp': 'wllama',
189
- '@wllama/wllama': 'wllama'
202
+ '@wllama/wllama': 'wllama',
203
+ 'nano-wasm': 'nano'
190
204
  };
191
205
 
192
206
  function resolvePackageName(name) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "3.0.0",
3
+ "version": "3.1.1",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",
@@ -215,6 +215,55 @@ describe('unclosed quote error', () => {
215
215
  });
216
216
  });
217
217
 
218
+ describe('backslash quote escaping', () => {
219
+ let shell;
220
+ beforeEach(async () => { shell = await createShell(); });
221
+
222
+ it('parses echo "hello \\"world\\"" to [\'echo\', \'hello "world"\']', async () => {
223
+ const cmd = 'echo "hello \\"world\\""';
224
+ const parts = Shell._splitCommand(cmd).map(p => p.value);
225
+ expect(parts).toEqual(['echo', 'hello "world"']);
226
+
227
+ const { output, errors, exitCode } = await run(shell, cmd);
228
+ expect(errors).toHaveLength(0);
229
+ expect(exitCode).toBe(0);
230
+ expect(output).toEqual(['hello "world"']);
231
+ });
232
+
233
+ it('parses echo "Eliot\'s CV with \\"nested quotes\\"" cleanly without throwing quote expression not closed', async () => {
234
+ const cmd = 'echo "Eliot\'s CV with \\"nested quotes\\""';
235
+ const parts = Shell._splitCommand(cmd).map(p => p.value);
236
+ expect(parts).toEqual(['echo', 'Eliot\'s CV with "nested quotes"']);
237
+
238
+ const { output, errors, exitCode } = await run(shell, cmd);
239
+ expect(errors).toHaveLength(0);
240
+ expect(exitCode).toBe(0);
241
+ expect(output).toEqual(['Eliot\'s CV with "nested quotes"']);
242
+ });
243
+
244
+ it('parses echo \'Eliot\'\\\'\'s experience\' correctly into [\'echo\', "Eliot\'s experience"]', async () => {
245
+ const cmd = "echo 'Eliot'\\''s experience'";
246
+ const parts = Shell._splitCommand(cmd).map(p => p.value);
247
+ expect(parts).toEqual(['echo', "Eliot's experience"]);
248
+
249
+ const { output, errors, exitCode } = await run(shell, cmd);
250
+ expect(errors).toHaveLength(0);
251
+ expect(exitCode).toBe(0);
252
+ expect(output).toEqual(["Eliot's experience"]);
253
+ });
254
+
255
+ it('parses echo \\"unquoted\\" to [\'echo\', \'"unquoted"\']', async () => {
256
+ const cmd = 'echo \\"unquoted\\"';
257
+ const parts = Shell._splitCommand(cmd).map(p => p.value);
258
+ expect(parts).toEqual(['echo', '"unquoted"']);
259
+
260
+ const { output, errors, exitCode } = await run(shell, cmd);
261
+ expect(errors).toHaveLength(0);
262
+ expect(exitCode).toBe(0);
263
+ expect(output).toEqual(['"unquoted"']);
264
+ });
265
+ });
266
+
218
267
  describe('output redirection', () => {
219
268
  it('writes command stdout to a file with >', async () => {
220
269
  const shell = await createShell({ filesystem: { home: {} } });
package/test/wbt.test.js CHANGED
@@ -3,9 +3,21 @@ import { describe, it, expect, beforeEach } from 'vitest';
3
3
  import { createShell, run } from './helpers.js';
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
+ const path = require('path');
7
+ const fs = require('fs');
6
8
  const Wbt = require('../lib/wbt/index.js');
7
9
  const { wllamaInstances } = require('../lib/wbt/packages/wllama.js');
8
10
 
11
+ const NANO_WASM_PATH = path.resolve(import.meta.dirname, '../../nano-wasm/dist/nano.wasm');
12
+ const NANO_WASM_BYTES = (() => {
13
+ try {
14
+ if (fs.existsSync(NANO_WASM_PATH)) {
15
+ return new Uint8Array(fs.readFileSync(NANO_WASM_PATH));
16
+ }
17
+ } catch { /* ignore */ }
18
+ return null;
19
+ })();
20
+
9
21
  // Minimal valid WASM binary that exits cleanly with 0 via _start:
10
22
  // (module (func (export "_start")))
11
23
  const MINIMAL_WASM_BYTES = new Uint8Array([
@@ -508,6 +520,13 @@ function createTestWbt() {
508
520
  return null;
509
521
  },
510
522
  fetch: async (url) => {
523
+ if ((url.includes('nano-wasm') || url.includes('nano.wasm')) && NANO_WASM_BYTES) {
524
+ return {
525
+ ok: true,
526
+ status: 200,
527
+ arrayBuffer: async () => NANO_WASM_BYTES.buffer
528
+ };
529
+ }
511
530
  if (url === 'https://example.com/hello.wasm' || /\.wasm(\?.*)?$/i.test(url)) {
512
531
  return {
513
532
  ok: true,
@@ -1192,3 +1211,76 @@ describe('WBT Wllama v3 WASM & WebGPU package (`wllama`, `llama`, `llama-cli`)',
1192
1211
  expect(modelsRes.output.join('\n')).toContain('persisted (fs)');
1193
1212
  });
1194
1213
  });
1214
+
1215
+ describe('WBT GNU nano WASM package (nano / nano-wasm)', () => {
1216
+ let shell;
1217
+
1218
+ beforeEach(async () => {
1219
+ shell = await createShell();
1220
+ shell.context.setCommand(createTestWbt());
1221
+ });
1222
+
1223
+ it('registers nano and nano-wasm in registry, wbt search, and wbt show', async () => {
1224
+ const listRes = await run(shell, 'wbt list');
1225
+ expect(listRes.exitCode).toBe(0);
1226
+ expect(listRes.output.join('\n')).toContain('nano/wasm 8.0.0');
1227
+
1228
+ const searchRes = await run(shell, 'wbt search editor');
1229
+ expect(searchRes.exitCode).toBe(0);
1230
+ expect(searchRes.output.join('\n')).toContain('nano');
1231
+
1232
+ const showRes = await run(shell, 'wbt show nano');
1233
+ expect(showRes.exitCode).toBe(0);
1234
+ expect(showRes.output.join('\n')).toContain('Package: nano');
1235
+ expect(showRes.output.join('\n')).toContain('Version: 8.0.0');
1236
+ expect(showRes.output.join('\n')).toContain('Aliases: nano-wasm');
1237
+
1238
+ const showAliasRes = await run(shell, 'wbt show nano-wasm');
1239
+ expect(showAliasRes.exitCode).toBe(0);
1240
+ expect(showAliasRes.output.join('\n')).toContain('Package: nano');
1241
+ });
1242
+
1243
+ it('installs nano and nano-wasm into /bin and runs --version and --help', async () => {
1244
+ const installRes = await run(shell, 'wbt install nano');
1245
+ expect(installRes.exitCode).toBe(0);
1246
+ expect(shell.context.fs.exists('/var/lib/wbt/wasm/nano.wasm')).toBe(true);
1247
+ expect(shell.context.fs.exists('/bin/nano')).toBe(true);
1248
+ expect(shell.context.fs.exists('/bin/nano-wasm')).toBe(true);
1249
+
1250
+ const verRes = await run(shell, 'nano --version');
1251
+ expect(verRes.exitCode).toBe(0);
1252
+ expect(verRes.output.join('\n')).toMatch(/GNU nano, version 8\.0|nano.*8\.0\.0.*wasm/i);
1253
+
1254
+ const helpRes = await run(shell, 'nano --help');
1255
+ expect(helpRes.exitCode).toBe(0);
1256
+ expect(helpRes.output.join('\n')).toMatch(/Usage:\s+nano/i);
1257
+
1258
+ const aliasVerRes = await run(shell, 'nano-wasm --version');
1259
+ expect(aliasVerRes.exitCode).toBe(0);
1260
+ expect(aliasVerRes.output.join('\n')).toMatch(/GNU nano, version 8\.0|nano.*8\.0\.0.*wasm/i);
1261
+ });
1262
+
1263
+ it('supports wbt run nano --version without permanently installing', async () => {
1264
+ const runRes = await run(shell, 'wbt run nano --version');
1265
+ expect(runRes.exitCode).toBe(0);
1266
+ expect(runRes.output.join('\n')).toMatch(/GNU nano, version 8\.0|nano.*8\.0\.0.*wasm/i);
1267
+ expect(shell.context.fs.exists('/bin/nano')).toBe(false);
1268
+ });
1269
+
1270
+ it('removes nano and unregisters both nano and nano-wasm from /bin', async () => {
1271
+ await run(shell, 'wbt install nano-wasm');
1272
+ expect(shell.context.fs.exists('/bin/nano')).toBe(true);
1273
+ expect(shell.context.fs.exists('/bin/nano-wasm')).toBe(true);
1274
+ expect(shell.context.fs.exists('/var/lib/wbt/wasm/nano.wasm')).toBe(true);
1275
+
1276
+ const rmRes = await run(shell, 'wbt remove nano');
1277
+ expect(rmRes.exitCode).toBe(0);
1278
+ expect(shell.context.fs.exists('/bin/nano')).toBe(false);
1279
+ expect(shell.context.fs.exists('/bin/nano-wasm')).toBe(false);
1280
+ expect(shell.context.fs.exists('/var/lib/wbt/wasm/nano.wasm')).toBe(false);
1281
+ });
1282
+ });
1283
+
1284
+
1285
+
1286
+