brsh 2.6.0 → 2.8.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/Readme.md +145 -1
  3. package/bin/Readme.md +6 -3
  4. package/bin/brsh-shell.js +68 -9
  5. package/bin/exportFileSystem.js +192 -80
  6. package/dist/shell.es.js +2497 -1300
  7. package/dist/shell.es.js.map +1 -1
  8. package/dist/shell.min.js +21 -14
  9. package/dist/shell.min.js.map +1 -1
  10. package/dist/terminal.cjs.js +101 -0
  11. package/dist/terminal.cjs.js.map +1 -0
  12. package/dist/terminal.es.js +290 -6965
  13. package/dist/terminal.es.js.map +1 -1
  14. package/dist/terminal.min.js +4 -25
  15. package/dist/terminal.min.js.map +1 -1
  16. package/dist/wbt.es.js +3974 -0
  17. package/dist/wbt.es.js.map +1 -0
  18. package/dist/wbt.min.js +10 -0
  19. package/dist/wbt.min.js.map +1 -0
  20. package/index.js +160 -20
  21. package/lib/BinaryContainer.js +528 -0
  22. package/lib/Command.js +2 -1
  23. package/lib/FileSystem.js +31 -0
  24. package/lib/NodeFileSystem.js +19 -9
  25. package/lib/ReplCommand.js +520 -0
  26. package/lib/ScriptCommand.js +1 -1
  27. package/lib/Terminal.js +45 -10
  28. package/lib/WasmCommand.js +1123 -35
  29. package/lib/buildFilesystemStructure.js +15 -4
  30. package/lib/local/curl.js +60 -2
  31. package/lib/wbt/index.js +756 -0
  32. package/lib/wbt/packages/wllama.js +1051 -0
  33. package/lib/wbt/registry.js +193 -0
  34. package/lib/wbt/utils.js +118 -0
  35. package/package.json +11 -3
  36. package/test/binary-filesystem.test.js +248 -0
  37. package/test/curl.test.js +166 -0
  38. package/test/exportFileSystem.test.js +78 -0
  39. package/test/terminal.test.js +113 -0
  40. package/test/wasm-cli.test.js +127 -0
  41. package/test/wbt.test.js +1175 -0
  42. package/vite.config.demo.js +4 -0
  43. package/vite.config.js +4 -0
  44. package/vite.config.terminal.js +16 -12
  45. package/vite.config.wbt.js +21 -0
  46. package/vitest.config.js +6 -0
package/CHANGELOG.md CHANGED
@@ -1,3 +1,23 @@
1
+ # [2.8.0](https://github.com/eliotstocker/Brsh-JS/compare/v2.7.0...v2.8.0) (2026-11-08)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **ci:** add pretest build and ensure dist/terminal.cjs.js exists for tests ([cb88ea4](https://github.com/eliotstocker/Brsh-JS/commit/cb88ea45f338db25efc0d7c65953f101d990be07))
7
+
8
+
9
+ ### Features
10
+
11
+ * **terminal:** externalize Shell dependency to reduce bundle size ([d2f8dd9](https://github.com/eliotstocker/Brsh-JS/commit/d2f8dd93155d55f1c843192a0d195032c7db95e3))
12
+ * **wbt:** add wllama v3 WebAssembly and WebGPU LLM inference adapter ([#26](https://github.com/eliotstocker/Brsh-JS/issues/26)) ([b7f647d](https://github.com/eliotstocker/Brsh-JS/commit/b7f647d703b4b0f67232f2a234737889e04c0689))
13
+
14
+ # [2.7.0](https://github.com/eliotstocker/Brsh-JS/compare/v2.6.0...v2.7.0) (2026-11-07)
15
+
16
+
17
+ ### Features
18
+
19
+ * add optional Web Binary Tool (wbt) WASM package manager ([#25](https://github.com/eliotstocker/Brsh-JS/issues/25)) ([3407c84](https://github.com/eliotstocker/Brsh-JS/commit/3407c84557f45c927778ca160e79ca057290e9e3))
20
+
1
21
  # [2.6.0](https://github.com/eliotstocker/Brsh-JS/compare/v2.5.6...v2.6.0) (2026-11-07)
2
22
 
3
23
 
package/Readme.md CHANGED
@@ -26,11 +26,14 @@ You may also use it as a node module. Install via npm:
26
26
  npm i brsh
27
27
  ```
28
28
 
29
- Import the terminal in your code:
29
+ Import both Shell and Terminal in your code:
30
30
  ```js
31
31
  // ESM
32
+ import Shell from 'brsh';
32
33
  import Terminal from 'brsh/terminal';
34
+
33
35
  // CJS
36
+ const Shell = require('brsh');
34
37
  const Terminal = require('brsh/terminal');
35
38
  ```
36
39
 
@@ -56,6 +59,8 @@ All [Shell options](#shell-options) are also accepted and forwarded directly to
56
59
  | option | required | default | description |
57
60
  | ------ | -------- | ------- | ----------- |
58
61
  | el | Yes | | A HTMLElement to fill with the terminal emulator |
62
+ | cli | No | | An existing `Shell` instance to attach the terminal emulator to |
63
+ | Shell | No | | A custom `Shell` class constructor to use when creating the underlying shell |
59
64
  | font | No | `Roboto Mono` | Name of a Google Webfont to use for the console font; a monospace font is recommended |
60
65
  | cursor | No | `none` | One of: `none`, `block`, `blink`. If `block` or `blink`, a cursor block character is shown at the end of the current line |
61
66
  | outputAnimation | No | `none` | One of: `none`, `type`. If `type`, each character is appended in order for a retro typing effect |
@@ -208,6 +213,145 @@ Scripts run in a sub-shell and do not share context with the parent. To persist
208
213
 
209
214
  **Note:** when using [exportFileSystem](bin/Readme.md), do not give scripts a `.js` extension — that causes them to be loaded as JavaScript modules rather than script strings.
210
215
 
216
+ ## Web Binary Tool (`wbt`) — Optional WASM Binary Manager
217
+
218
+ `wbt` is an optional, APT-style binary manager for `brsh` that lets users install and run WebAssembly binaries (such as `wllama`, `sqlite3`, `assemblyscript` / `asc`, `jq`, `python3`, `duckdb`, `graphviz`, `ffmpeg`, `wabt`, `quickjs`, `lua`, or custom `.wasm`/`.wat` URLs). It is **not** included in the default shell bundle unless you explicitly register it.
219
+
220
+ ### Enabling `wbt`
221
+
222
+ ```js
223
+ // ESM
224
+ import Terminal from 'brsh/terminal';
225
+ import Wbt from 'brsh/wbt';
226
+
227
+ const term = new Terminal({ el: document.body });
228
+ term.cli.context.setCommand(Wbt);
229
+ ```
230
+
231
+ ```js
232
+ // CJS
233
+ const Shell = require('brsh');
234
+ const Wbt = require('brsh/wbt');
235
+
236
+ const shell = new Shell({ filesystem: {} });
237
+ shell.context.setCommand(Wbt);
238
+ ```
239
+
240
+ ### Loading WASM CLI Tools without `wbt` (Base Shell)
241
+
242
+ You can also register WASM CLI binaries directly into any `Shell` instance without `wbt`:
243
+
244
+ ```js
245
+ import Shell from 'brsh';
246
+
247
+ // 1. From a WASM URL or bytes
248
+ const MyTool = Shell.createWasmCommand({
249
+ name: 'mytool',
250
+ wasmUrl: 'https://example.com/mytool.wasm'
251
+ });
252
+ shell.context.setCommand(MyTool);
253
+
254
+ // 2. Or place any raw .wasm / .wat binary into /bin in your virtual filesystem:
255
+ shell.onCommand('tool.wasm --help');
256
+ ```
257
+
258
+ ### Usage in the shell
259
+
260
+ ```sh
261
+ # List available or installed WASM packages
262
+ wbt list
263
+ wbt list --installed
264
+
265
+ # Search and inspect packages
266
+ wbt search sql
267
+ wbt show sqlite3
268
+
269
+ # Install curated WASM packages into /bin
270
+ wbt install wllama sqlite3 assemblyscript jq python3 duckdb graphviz ffmpeg
271
+
272
+ # Run Wllama v3 (llama.cpp WASM + WebGPU) for one-shot completions or interactive chat REPL!
273
+ wllama -m /home/model.gguf -p "Explain WebGPU in one sentence."
274
+ wllama pull https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories15M.gguf -o /home/model.gguf
275
+ wllama -m /home/model.gguf # launches interactive multi-turn chat REPL
276
+
277
+ # Run SQLite3 (persists database files directly in the brsh filesystem)
278
+ sqlite3 /home/app.db "CREATE TABLE notes (id INT, body TEXT); INSERT INTO notes VALUES (1, 'Hello WASM');"
279
+ sqlite3 -table /home/app.db "SELECT * FROM notes;"
280
+ echo "SELECT * FROM notes;" | sqlite3 -csv /home/app.db
281
+
282
+ # Run AssemblyScript directly like ts-node / node (`asrun` / `asnode`), or compile to .wasm (`asc`)
283
+ asrun -e "console.log('Hello from AssemblyScript!')"
284
+ asrun /home/script.ts
285
+ asc /home/hello.ts -o /home/hello.wasm && /home/hello.wasm
286
+
287
+ # Other built-in WASM tools: jq, python3 (Pyodide), duckdb, dot (Graphviz), ffmpeg
288
+ cat data.json | jq -r ".user.name"
289
+ python3 -c "print([x * x for x in range(5)])"
290
+ duckdb -c "SELECT 42 AS answer"
291
+ dot -Tsvg graph.dot -o graph.svg
292
+ ffmpeg -i input.mp4 output.webm
293
+
294
+ # Install any generic Emscripten / WASI package or custom .wasm URL at runtime (no custom wrapper needed!)
295
+ wbt install npm:cowsay-wasm
296
+ wbt install mytool https://example.com/mytool.wasm
297
+ mytool
298
+
299
+ # Remove an installed binary
300
+ wbt remove sqlite3
301
+ ```
302
+
303
+ ## Binary Filesystem Container (`.brfs`) & Client-Side Persistence
304
+
305
+ While `brsh` continues to support standard JS object filesystems (and legacy `.brsh` compressed JS bundles), it also supports an **Indexed Binary Container (`.brfs`)** format (`BRFS` magic header + JSON metadata/permissions index + contiguous raw binary payload with zero base64 overhead) as well as **IndexedDB client-side persistence**.
306
+
307
+ ### Exporting a `.brfs` Binary Container
308
+
309
+ ```shell
310
+ # Standalone .brfs binary container (load via fetch('/fs.brfs').then(r => r.arrayBuffer()))
311
+ exportFileSystem ./filesystem -o ./fs.brfs
312
+
313
+ # Or generate a JS loader that fetches and mounts ./fs.brfs automatically
314
+ exportFileSystem ./filesystem -o ./fs.js -v fs --binary
315
+ ```
316
+
317
+ ### Mounting & Snapshot Serialization
318
+
319
+ ```js
320
+ // Pass a .brfs URL directly to Terminal or Shell (no JS loader needed!):
321
+ const term = new Terminal({
322
+ el: document.body,
323
+ filesystem: '/fs.brfs'
324
+ });
325
+
326
+ // Or pass a pre-fetched ArrayBuffer / Uint8Array (raw or gzip-compressed):
327
+ const bytes = new Uint8Array(await (await fetch('/fs.brfs')).arrayBuffer());
328
+ const shell = new Shell({ filesystem: bytes });
329
+
330
+ // Export the live filesystem (including runtime changes, permissions, symlinks, and binaries) to a .brfs Uint8Array:
331
+ const snapshot = shell.context.fs.toBinaryContainer();
332
+ ```
333
+
334
+ ### Client-Side Persistence (IndexedDB)
335
+
336
+ Use `Shell.Storage` (`FilesystemStorage`) to persist user changes across page reloads in IndexedDB:
337
+
338
+ ```js
339
+ const Terminal = require('brsh/terminal');
340
+ const Shell = require('brsh');
341
+
342
+ const term = new Terminal({
343
+ el: document.body,
344
+ // Loads saved snapshot from IndexedDB if present, otherwise fetches '/fs.brfs'
345
+ filesystem: Shell.Storage.loadOrFetch('my-app', '/fs.brfs'),
346
+ // Automatically persists binary container to IndexedDB whenever files or permissions change
347
+ onFsChange: Shell.Storage.createAutoSave('my-app')
348
+ });
349
+
350
+ // Or manually save/load at any time:
351
+ await Shell.Storage.save(term.cli, 'my-app');
352
+ const savedFs = await Shell.Storage.load('my-app');
353
+ ```
354
+
211
355
  ## More Examples
212
356
  On my website I have extended the functionality adding some simple extra utilities such as an ANSI image viewer and a markdown parser based on open-source node CLI utilities.
213
357
 
package/bin/Readme.md CHANGED
@@ -7,8 +7,9 @@ the export file system command can be used to export a local folder structure fo
7
7
  it will travers the directory structure from the provided base path, and import all files based on the following rules:
8
8
 
9
9
  * Javascript files (.js): imported as node modules, whatever they export will be available to Shell JS, this is really useful for adding new commands just make sure you set module.exports to your Command class
10
- * Image files (.jpg, .png, .bmp): imported as base64 representations of the binary data, this is useful if you wish to display/manipulate data around these sorts of files
11
- * all other files: imported as string representations of the data inside
10
+ * WebAssembly files (.wasm): automatically wrapped as executable `WasmCommand` binaries (especially when placed in `/bin`) or stored as raw binary files
11
+ * Binary files (.jpg, .png, .bmp, .pdf, .zip, etc.): stored as `BinaryFile` instances (or raw zero-overhead byte slices when using `--binary` / `.brfs`)
12
+ * all other files: imported as UTF-8 string representations of the data inside (preserving Unix file permissions and symlinks)
12
13
 
13
14
  ## CLI options
14
15
 
@@ -16,7 +17,9 @@ it will travers the directory structure from the provided base path, and import
16
17
  | ---- | ----- | -------- | ----------- |
17
18
  | root | | `String` path | also the default option, this is the path to the root of your file system |
18
19
  | variable | v | `String` name | final variable output name for instance if set to `filesystem` when this file is loaded in a browser it will be accessible at `window.filesystem` |
19
- | output | o | `String` path | path for the output javascript file (if not set will output to stdout) |
20
+ | output | o | `String` path | path for the output file (`.js` bundle or standalone `.brfs` binary container; if not set will output to stdout) |
21
+ | binary | b | | emit an indexed `BRFS` binary container (`.brfs`) with raw binary payloads, permissions, and symlinks instead of base64-in-JS |
22
+ | compress | c | | emit a gzip-compressed bundle alongside a browser decompression loader (legacy `.brsh` / `.brfs` mode) |
20
23
  | pretty | p | | if pretty is set we will disable code uglification and pretify the json directory structure |
21
24
  | hyperlinks | h | | enable experimental hyperlink support for application (this will pass through an environment variable to your filesystem FORCE_HYPERLINK some libraries will pick up on this and pass back ansi links) |
22
25
 
package/bin/brsh-shell.js CHANGED
@@ -11,9 +11,27 @@
11
11
  // brsh-shell -i -c "cmd" force interactive after running -c
12
12
 
13
13
  const Shell = require('../index.js');
14
+ const Wbt = require('../lib/wbt');
15
+ const Pico = require('../demo/pico');
16
+ const { buildStructure } = require('../lib/buildFilesystemStructure');
14
17
  const readline = require('readline');
15
18
  const nodePath = require('path');
16
19
 
20
+ function resolveRequireNodes(node) {
21
+ if (!node || typeof node !== 'object') return node;
22
+ for (const [k, v] of Object.entries(node)) {
23
+ if (typeof v === 'string') {
24
+ const m = v.match(/^require\('(.*)'\)$/);
25
+ if (m) {
26
+ try { node[k] = require(m[1]); } catch { /* ignore */ }
27
+ }
28
+ } else if (v && typeof v === 'object') {
29
+ resolveRequireNodes(v);
30
+ }
31
+ }
32
+ return node;
33
+ }
34
+
17
35
  // ── CLI argument parsing ──────────────────────────────────────────────────────
18
36
 
19
37
  const argv = process.argv.slice(2);
@@ -22,6 +40,7 @@ let scriptFile = null; // positional script path
22
40
  let scriptArgs = []; // args after the script filename
23
41
  const shellFlags = []; // single-char flags to activate via `set`
24
42
  let forceInteractive = false;
43
+ let demoMode = false;
25
44
 
26
45
  for (let i = 0; i < argv.length; i++) {
27
46
  const arg = argv[i];
@@ -29,6 +48,10 @@ for (let i = 0; i < argv.length; i++) {
29
48
  if (scriptFile) scriptArgs = argv.slice(i + 1);
30
49
  break;
31
50
  }
51
+ if (arg === '--demo') {
52
+ demoMode = true;
53
+ continue;
54
+ }
32
55
  if (arg === '-c') {
33
56
  commandString = argv[++i] !== undefined ? argv[i] : '';
34
57
  continue;
@@ -52,11 +75,29 @@ const isInteractive = forceInteractive || (commandString === null && scriptFile
52
75
 
53
76
  // ── Shell setup ───────────────────────────────────────────────────────────────
54
77
 
55
- const shell = new Shell({
56
- useRealFilesystem: true,
57
- cwd: process.cwd(),
58
- hostname: require('os').hostname().split('.')[0]
59
- });
78
+ let shellOptions;
79
+ if (demoMode) {
80
+ const demoDir = nodePath.resolve(__dirname, '../demo/filesystem');
81
+ const { filesystem, permissions } = buildStructure(demoDir);
82
+ resolveRequireNodes(filesystem);
83
+ shellOptions = {
84
+ filesystem,
85
+ permissions,
86
+ profile: '/root/.profile',
87
+ cwd: '/root',
88
+ hostname: 'brsh'
89
+ };
90
+ } else {
91
+ shellOptions = {
92
+ useRealFilesystem: true,
93
+ cwd: process.cwd(),
94
+ hostname: require('os').hostname().split('.')[0]
95
+ };
96
+ }
97
+
98
+ const shell = new Shell(shellOptions);
99
+ shell.context.setCommand(Wbt);
100
+ shell.context.setCommand(Pico);
60
101
 
61
102
  let destroyed = false;
62
103
  let rl;
@@ -72,14 +113,28 @@ function reportSize() {
72
113
 
73
114
  process.stdout.on('resize', () => { if (inInteractiveApp) reportSize(); });
74
115
 
116
+ let inProgressLine = false;
75
117
  shell.on('stdOut', line => {
76
118
  if (inInteractiveApp) {
77
119
  process.stdout.write(line);
120
+ } else if (typeof line === 'string' && line.startsWith('\r')) {
121
+ inProgressLine = true;
122
+ process.stdout.write('\r\x1b[K' + line.slice(1));
78
123
  } else {
124
+ if (inProgressLine) {
125
+ process.stdout.write('\n');
126
+ inProgressLine = false;
127
+ }
79
128
  process.stdout.write(line + '\n');
80
129
  }
81
130
  });
82
- shell.on('stdErr', line => process.stderr.write(line + '\n'));
131
+ shell.on('stdErr', line => {
132
+ if (inProgressLine) {
133
+ process.stdout.write('\n');
134
+ inProgressLine = false;
135
+ }
136
+ process.stderr.write(line + '\n');
137
+ });
83
138
 
84
139
  shell.on('exit', code => {
85
140
  destroyed = true;
@@ -118,9 +173,13 @@ async function runNonInteractive() {
118
173
  }
119
174
 
120
175
  if (!isInteractive) {
121
- shell.once('status', status => {
122
- if (status === Shell.STATUS_READY) runNonInteractive();
123
- });
176
+ const onReady = status => {
177
+ if (status === Shell.STATUS_READY) {
178
+ shell.removeListener('status', onReady);
179
+ runNonInteractive();
180
+ }
181
+ };
182
+ shell.on('status', onReady);
124
183
  return;
125
184
  }
126
185
 
@@ -9,6 +9,7 @@ const cla = require('command-line-args');
9
9
  const tmp = require('tmp');
10
10
  const { polyfillNode } = require('esbuild-plugin-polyfill-node');
11
11
  const { buildStructure } = require('../lib/buildFilesystemStructure');
12
+ const { serializeBinaryFilesystem } = require('../lib/BinaryContainer');
12
13
 
13
14
  let options;
14
15
  try {
@@ -22,7 +23,7 @@ try {
22
23
  {
23
24
  name: 'variable',
24
25
  alias: 'v',
25
- required: true,
26
+ required: false,
26
27
  type: String
27
28
  },
28
29
  {
@@ -44,6 +45,11 @@ try {
44
45
  name: 'compress',
45
46
  alias: 'c',
46
47
  type: Boolean
48
+ },
49
+ {
50
+ name: 'binary',
51
+ alias: 'b',
52
+ type: Boolean
47
53
  }
48
54
  ]);
49
55
  } catch(e) {
@@ -56,7 +62,10 @@ if(!options.root) {
56
62
  process.exit(1);
57
63
  }
58
64
 
59
- if(!options.variable) {
65
+ const isStandaloneBrfsOutput = Boolean(options.output && options.output.endsWith('.brfs'));
66
+ const useBinaryContainer = Boolean(options.binary || isStandaloneBrfsOutput);
67
+
68
+ if(!options.variable && !isStandaloneBrfsOutput) {
60
69
  console.log('missing required --variable (-v) flag');
61
70
  process.exit(1);
62
71
  }
@@ -77,20 +86,11 @@ try {
77
86
  }
78
87
  const { filesystem, permissions } = struct;
79
88
 
80
- if (options.compress && !options.output) {
81
- console.log('--compress requires --output (-o) to be set');
89
+ if ((options.compress || options.binary) && !options.output) {
90
+ console.log('--compress / --binary requires --output (-o) to be set');
82
91
  process.exit(1);
83
92
  }
84
93
 
85
- const fsJson = JSON.stringify(filesystem, null, options.pretty ? 2 : null);
86
- const permJson = JSON.stringify(permissions, null, options.pretty ? 2 : null);
87
- const fsJS = fsJson.replace(/"(require\('.*?'\))"/gm, '$1');
88
-
89
- const JS = `module.exports = { filesystem: ${fsJS}, permissions: ${permJson} }`;
90
-
91
- const tf = tmp.fileSync({ postfix: '.tmp.js' });
92
- fs.writeFileSync(tf.name, JS);
93
-
94
94
  const alias = {
95
95
  'supports-color': 'supports-color/index',
96
96
  };
@@ -114,6 +114,7 @@ const textLoaderPlugin = {
114
114
  && !filename.endsWith('.bmp')
115
115
  && !filename.endsWith('.webp')
116
116
  && !filename.endsWith('.ico')
117
+ && !filename.endsWith('.wasm')
117
118
  ) {
118
119
  const contents = await fs.promises.readFile(args.path, 'utf8');
119
120
  return { contents, loader: 'text' };
@@ -122,73 +123,184 @@ const textLoaderPlugin = {
122
123
  }
123
124
  };
124
125
 
125
- esbuild.build({
126
- entryPoints: [tf.name],
127
- bundle: true,
128
- format: 'iife',
129
- platform: 'browser',
130
- treeShaking: true,
131
- outfile: options.output,
132
- allowOverwrite: true,
133
- globalName: options.variable,
134
- minify: true,
135
- sourcemap: false,
136
- loader: {
137
- '.gif': 'binary',
138
- '.png': 'binary',
139
- '.jpg': 'binary',
140
- '.jpeg': 'binary',
141
- '.bmp': 'binary',
142
- '.webp': 'binary',
143
- '.ico': 'binary'
144
- },
145
- plugins: [
146
- textLoaderPlugin,
147
- polyfillNode()
148
- ],
149
- define: {
150
- 'process.env.NODE_ENV': JSON.stringify('production'),
151
- 'process.env.COLORTERM': JSON.stringify('truecolor'),
152
- 'process.env.TERM': JSON.stringify('color'),
153
- 'process.env.FORCE_HYPERLINK': options.hyperlinks ? JSON.stringify('true') : JSON.stringify('false'),
154
- },
155
- alias,
156
- })
157
- .then(() => {
158
- if (options.compress) {
159
- // Post-process: gzip the entire esbuild output.
160
- // The compressed bytes are written to <output>.gz as raw binary.
161
- // The JS file is replaced with a tiny loader that fetches the .gz,
162
- // decompresses it, and executes it — no base64 overhead.
163
- const bundle = fs.readFileSync(options.output, 'utf8');
164
- // Append a return statement so new Function() can hand back the value
165
- const codeToCompress = bundle + `\nreturn ${options.variable};`;
166
- const compressed = zlib.gzipSync(Buffer.from(codeToCompress, 'utf8'));
167
- const gzPath = options.output.replace(/\.js$/, '') + '.brfs';
168
- fs.writeFileSync(gzPath, compressed);
169
-
170
- const varName = options.variable;
171
- // The loader captures document.currentScript.src synchronously
172
- // (unavailable once the async IIFE runs) and derives the .brfs URL.
173
- const loader =
174
- `globalThis.${varName}=(function(){` +
175
- `var s=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:` +
176
- `typeof location!=="undefined"?location.href:null;` +
177
- `if(!s)throw new Error("${varName}: cannot resolve .brfs URL");` +
178
- `var u=s.replace(/\\.js(\\?[^#]*)?$/,".brfs");` +
179
- `return fetch(u)` +
180
- `.then(function(r){return r.arrayBuffer();})` +
181
- `.then(function(b){` +
182
- `var ds=new DecompressionStream("gzip");` +
183
- `var w=ds.writable.getWriter();` +
184
- `w.write(new Uint8Array(b));` +
185
- `w.close();` +
186
- `return new Response(ds.readable).text();` +
187
- `})` +
188
- `.then(function(code){return new Function(code)();});` +
189
- `})();`;
190
- fs.writeFileSync(options.output, loader);
191
- console.log(`Compressed bundle written to ${gzPath}`);
126
+ /**
127
+ * Extracts all `require('...')` JS command entries from `filesystem`, replaces them with dummy
128
+ * function markers in `filesystem` so `serializeBinaryFilesystem` emits `{ "$c": virtualPath }`,
129
+ * and returns a Map of `virtualPath -> require('...')` for esbuild bundling.
130
+ */
131
+ function extractJsCommandsForBinary(node, prefix = '', map = {}) {
132
+ for (const [k, v] of Object.entries(node)) {
133
+ const vPath = `${prefix}/${k}`;
134
+ if (typeof v === 'string' && /^require\('.*'\)$/.test(v)) {
135
+ map[vPath] = v;
136
+ node[k] = function __brfsCommandPlaceholder() {};
137
+ } else if (v && typeof v === 'object' && !(v instanceof Uint8Array)) {
138
+ extractJsCommandsForBinary(v, vPath, map);
192
139
  }
140
+ }
141
+ return map;
142
+ }
143
+
144
+ async function buildBinaryContainerMode() {
145
+ const cmdMap = extractJsCommandsForBinary(filesystem);
146
+ let commandsBundle = null;
147
+
148
+ if (Object.keys(cmdMap).length > 0) {
149
+ const entriesCode = Object.entries(cmdMap)
150
+ .map(([vPath, reqExpr]) => `${JSON.stringify(vPath)}: ${reqExpr}`)
151
+ .join(',\n');
152
+ const cmdEntryJs = `module.exports = {\n${entriesCode}\n};`;
153
+ const tfCmd = tmp.fileSync({ postfix: '.cmd.tmp.js' });
154
+ const tfOut = tmp.fileSync({ postfix: '.cmd.out.js' });
155
+ fs.writeFileSync(tfCmd.name, cmdEntryJs);
156
+
157
+ await esbuild.build({
158
+ entryPoints: [tfCmd.name],
159
+ bundle: true,
160
+ format: 'iife',
161
+ platform: 'browser',
162
+ treeShaking: true,
163
+ outfile: tfOut.name,
164
+ allowOverwrite: true,
165
+ globalName: '__brfs_cmds',
166
+ minify: !options.pretty,
167
+ sourcemap: false,
168
+ plugins: [textLoaderPlugin, polyfillNode()],
169
+ define: {
170
+ 'process.env.NODE_ENV': JSON.stringify('production'),
171
+ 'process.env.COLORTERM': JSON.stringify('truecolor'),
172
+ 'process.env.TERM': JSON.stringify('color'),
173
+ 'process.env.FORCE_HYPERLINK': options.hyperlinks ? JSON.stringify('true') : JSON.stringify('false'),
174
+ },
175
+ alias,
176
+ });
177
+
178
+ commandsBundle = fs.readFileSync(tfOut.name, 'utf8') + '\nreturn __brfs_cmds;';
179
+ }
180
+
181
+ const rawContainer = serializeBinaryFilesystem(filesystem, permissions, { commandsBundle });
182
+ const finalBytes = options.compress ? zlib.gzipSync(Buffer.from(rawContainer)) : Buffer.from(rawContainer);
183
+
184
+ if (isStandaloneBrfsOutput) {
185
+ fs.writeFileSync(options.output, finalBytes);
186
+ console.log(`Binary container written to ${options.output}`);
193
187
  console.log('Build succeeded');
188
+ return;
189
+ }
190
+
191
+ // Output is a `.js` file with `--binary`: write `.brfs` alongside a tiny browser loader
192
+ const brfsPath = options.output.replace(/\.js$/, '') + '.brfs';
193
+ fs.writeFileSync(brfsPath, finalBytes);
194
+
195
+ const varName = options.variable;
196
+ const loader =
197
+ `globalThis.${varName}=(function(){` +
198
+ `var s=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:` +
199
+ `typeof location!=="undefined"?location.href:null;` +
200
+ `if(!s)throw new Error("${varName}: cannot resolve .brfs URL");` +
201
+ `var u=s.replace(/\\.js(\\?[^#]*)?$/,".brfs");` +
202
+ `return fetch(u)` +
203
+ `.then(function(r){return r.arrayBuffer();})` +
204
+ `.then(function(b){` +
205
+ `var u8=new Uint8Array(b);` +
206
+ `if(u8[0]===0x1f&&u8[1]===0x8b){` +
207
+ `var ds=new DecompressionStream("gzip");` +
208
+ `var w=ds.writable.getWriter();` +
209
+ `w.write(u8);w.close();` +
210
+ `return new Response(ds.readable).arrayBuffer().then(function(ab){return {filesystem:new Uint8Array(ab),permissions:{}};});` +
211
+ `}` +
212
+ `return {filesystem:u8,permissions:{}};` +
213
+ `});` +
214
+ `})();`;
215
+ fs.writeFileSync(options.output, loader);
216
+ console.log(`Binary container written to ${brfsPath}`);
217
+ console.log('Build succeeded');
218
+ }
219
+
220
+ if (useBinaryContainer) {
221
+ buildBinaryContainerMode().catch(err => {
222
+ console.error(err);
223
+ process.exit(1);
194
224
  });
225
+ } else {
226
+ const fsJson = JSON.stringify(filesystem, null, options.pretty ? 2 : null);
227
+ const permJson = JSON.stringify(permissions, null, options.pretty ? 2 : null);
228
+ const fsJS = fsJson.replace(/"(require\('.*?'\))"/gm, '$1');
229
+
230
+ const JS = `module.exports = { filesystem: ${fsJS}, permissions: ${permJson} }`;
231
+
232
+ const tf = tmp.fileSync({ postfix: '.tmp.js' });
233
+ fs.writeFileSync(tf.name, JS);
234
+
235
+ esbuild.build({
236
+ entryPoints: [tf.name],
237
+ bundle: true,
238
+ format: 'iife',
239
+ platform: 'browser',
240
+ treeShaking: true,
241
+ outfile: options.output,
242
+ allowOverwrite: true,
243
+ globalName: options.variable,
244
+ minify: true,
245
+ sourcemap: false,
246
+ loader: {
247
+ '.gif': 'binary',
248
+ '.png': 'binary',
249
+ '.jpg': 'binary',
250
+ '.jpeg': 'binary',
251
+ '.bmp': 'binary',
252
+ '.webp': 'binary',
253
+ '.ico': 'binary',
254
+ '.wasm': 'binary'
255
+ },
256
+ plugins: [
257
+ textLoaderPlugin,
258
+ polyfillNode()
259
+ ],
260
+ define: {
261
+ 'process.env.NODE_ENV': JSON.stringify('production'),
262
+ 'process.env.COLORTERM': JSON.stringify('truecolor'),
263
+ 'process.env.TERM': JSON.stringify('color'),
264
+ 'process.env.FORCE_HYPERLINK': options.hyperlinks ? JSON.stringify('true') : JSON.stringify('false'),
265
+ },
266
+ alias,
267
+ })
268
+ .then(() => {
269
+ if (options.compress) {
270
+ // Post-process: gzip the entire esbuild output.
271
+ // The compressed bytes are written to <output>.brfs as raw binary.
272
+ // The JS file is replaced with a tiny loader that fetches the .brfs,
273
+ // decompresses it, and executes it — no base64 overhead.
274
+ const bundle = fs.readFileSync(options.output, 'utf8');
275
+ // Append a return statement so new Function() can hand back the value
276
+ const codeToCompress = bundle + `\nreturn ${options.variable};`;
277
+ const compressed = zlib.gzipSync(Buffer.from(codeToCompress, 'utf8'));
278
+ const gzPath = options.output.replace(/\.js$/, '') + '.brfs';
279
+ fs.writeFileSync(gzPath, compressed);
280
+
281
+ const varName = options.variable;
282
+ // The loader captures document.currentScript.src synchronously
283
+ // (unavailable once the async IIFE runs) and derives the .brfs URL.
284
+ const loader =
285
+ `globalThis.${varName}=(function(){` +
286
+ `var s=typeof document!=="undefined"&&document.currentScript?document.currentScript.src:` +
287
+ `typeof location!=="undefined"?location.href:null;` +
288
+ `if(!s)throw new Error("${varName}: cannot resolve .brfs URL");` +
289
+ `var u=s.replace(/\\.js(\\?[^#]*)?$/,".brfs");` +
290
+ `return fetch(u)` +
291
+ `.then(function(r){return r.arrayBuffer();})` +
292
+ `.then(function(b){` +
293
+ `var ds=new DecompressionStream("gzip");` +
294
+ `var w=ds.writable.getWriter();` +
295
+ `w.write(new Uint8Array(b));` +
296
+ `w.close();` +
297
+ `return new Response(ds.readable).text();` +
298
+ `})` +
299
+ `.then(function(code){return new Function(code)();});` +
300
+ `})();`;
301
+ fs.writeFileSync(options.output, loader);
302
+ console.log(`Compressed bundle written to ${gzPath}`);
303
+ }
304
+ console.log('Build succeeded');
305
+ });
306
+ }