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
@@ -187,5 +187,81 @@ describe('Running .wasm files directly as CLI tools in base shell', () => {
187
187
  const res = await run(shell, 'devtool');
188
188
  expect(res.exitCode).toBe(0);
189
189
  });
190
+
191
+ it('passes live stdout COLUMNS and LINES to WASI environ_get over stale context vars', async () => {
192
+ // WASI binary that reads environ_sizes_get + environ_get and writes the environment block to stdout
193
+ const ENV_DUMP_WASM_BYTES = Buffer.from(
194
+ 'AGFzbQEAAAABEgNgAn9/AX9gBH9/f38Bf2AAAAJzAxZ3YXNpX3NuYXBzaG90X3ByZXZpZXcxEWVudmlyb25fc2l6ZXNfZ2V0AAAWd2FzaV9zbmFwc2hvdF9wcmV2aWV3MQtlbnZpcm9uX2dldAAAFndhc2lfc25hcHNob3RfcHJldmlldzEIZmRfd3JpdGUAAQMCAQIFAwEAAQcTAgZtZW1vcnkCAAZfc3RhcnQAAwowAS4AQQBBBBAAGkEQQYAEEAEaQQhBgAQ2AgBBDEEEKAIANgIAQQFBCEEBQQAQAhoL',
195
+ 'base64'
196
+ );
197
+
198
+ const shell = new Shell({
199
+ filesystem: {
200
+ bin: { 'envdump.wasm': ENV_DUMP_WASM_BYTES }
201
+ },
202
+ permissions: {
203
+ '/bin/envdump.wasm': 0o755
204
+ }
205
+ });
206
+
207
+ // Simulate stale 80x24 context vars while live stream dimensions are 132x42
208
+ shell.context.setVar('COLUMNS', '80');
209
+ shell.context.setVar('LINES', '24');
210
+ shell.stdout.columns = 132;
211
+ shell.stdout.rows = 42;
212
+ shell.stdin.columns = 132;
213
+ shell.stdin.rows = 42;
214
+
215
+ const res = await run(shell, 'envdump');
216
+ expect(res.exitCode).toBe(0);
217
+ const rawEnv = res.output.join('\n').replace(/\0/g, '\n');
218
+ expect(rawEnv).toContain('COLUMNS=132');
219
+ expect(rawEnv).toContain('LINES=42');
220
+ expect(rawEnv).not.toContain('COLUMNS=80');
221
+ expect(rawEnv).not.toContain('LINES=24');
222
+ });
223
+
224
+ it('delivers stdin via hasCustomStdinListener and distinguishes poll_oneoff timeout from FD_READ', async () => {
225
+ // Asyncify WASI binary polling FD_READ (type=1) + CLOCK 35ms (type=0) and printing "<nevents>:<event0.type>\n"
226
+ const ASYNC_POLL_WASM_BYTES = Buffer.from(
227
+ 'AGFzbQEAAAABFARgBH9/f38Bf2ABfwBgAABgAAF/AkgCFndhc2lfc25hcHNob3RfcHJldmlldzELcG9sbF9vbmVvZmYAABZ3YXNpX3NuYXBzaG90X3ByZXZpZXcxCGZkX3dyaXRlAAADBwYBAgECAwIFAwEAAgYGAX8BQQALB4YBBwZtZW1vcnkCABVhc3luY2lmeV9zdGFydF91bndpbmQAAhRhc3luY2lmeV9zdG9wX3Vud2luZAADFWFzeW5jaWZ5X3N0YXJ0X3Jld2luZAAEFGFzeW5jaWZ5X3N0b3BfcmV3aW5kAAUSYXN5bmNpZnlfZ2V0X3N0YXRlAAYGX3N0YXJ0AAcK1AEGBgBBASQACwYAQQAkAAsGAEECJAALBgBBACQACwQAIwALsAEAQcAAQgs3AwBByABBAToAAEHQAEEANgIAQfAAQhY3AwBB+ABBADoAAEGAAUEBNgIAQYgBQsCd2BA3AwBBmAFBADsBAEHKAUEJOgAAQcAAQcABQQJBmAIQABojAEEBRgRADwtBrAJBMEGYAigCAGo6AABBrQJBOjoAAEGuAkEwQcoBLQAAajoAAEGvAkEKOgAAQcACQawCNgIAQcQCQQQ2AgBBAUHAAkEBQcgCEAEaCw==',
228
+ 'base64'
229
+ );
230
+
231
+ const shell = new Shell({
232
+ filesystem: {
233
+ bin: { 'asyncpoll.wasm': ASYNC_POLL_WASM_BYTES }
234
+ },
235
+ permissions: {
236
+ '/bin/asyncpoll.wasm': 0o755
237
+ }
238
+ });
239
+
240
+ // 1. No input sent -> clock timeout fires ONLY clock event ("1:0"), NOT false FD_READ
241
+ const rawOut1 = [];
242
+ const onRaw1 = (chunk) => rawOut1.push(String(chunk));
243
+ shell.stdout.on('data', onRaw1);
244
+ const timeoutRes = await run(shell, 'asyncpoll');
245
+ shell.stdout.off('data', onRaw1);
246
+ expect(timeoutRes.exitCode).toBe(0);
247
+ const text1 = rawOut1.join('') + timeoutRes.output.join('');
248
+ expect(text1).toContain('1:0');
249
+ expect(text1).not.toContain('1:1');
250
+
251
+ // 2. Input written while WASM is polling -> delivered via hasCustomStdinListener, wakes FD_READ ("1:1")
252
+ const rawOut2 = [];
253
+ const onRaw2 = (chunk) => rawOut2.push(String(chunk));
254
+ shell.stdout.on('data', onRaw2);
255
+ const cmdPromise = shell.onCommand('asyncpoll');
256
+ await new Promise(r => setTimeout(r, 10));
257
+ shell.write('k');
258
+ await cmdPromise;
259
+ shell.stdout.off('data', onRaw2);
260
+ expect(shell.lastCode).toBe(0);
261
+ const text2 = rawOut2.join('');
262
+ expect(text2).toContain('1:1');
263
+ expect(text2).not.toContain('1:0');
264
+ });
190
265
  });
191
266
 
267
+
package/test/wbt.test.js CHANGED
@@ -559,6 +559,45 @@ function createTestWbt() {
559
559
  arrayBuffer: async () => NANO_WASM_BYTES.buffer
560
560
  };
561
561
  }
562
+ if (url.includes('/bin/freedoom')) {
563
+ const scriptPath = path.resolve(import.meta.dirname, '../../eliotstocker/doom-wasm/bin/freedoom');
564
+ const scriptText = fs.existsSync(scriptPath)
565
+ ? fs.readFileSync(scriptPath, 'utf8')
566
+ : [
567
+ '#!/bin/sh',
568
+ 'WAD_DIR="/usr/share/games/doom"',
569
+ 'WAD_NAME="freedoom1.wad"',
570
+ 'WAD_URL="https://raw.githubusercontent.com/redox-os/freedoom/master/freedoom1.wad"',
571
+ 'EXTRA_ARGS=""',
572
+ 'for ARG in $@',
573
+ 'do',
574
+ ' case "$ARG" in',
575
+ ' --phase2|--freedoom2|-2)',
576
+ ' WAD_NAME="freedoom2.wad"',
577
+ ' WAD_URL="https://raw.githubusercontent.com/redox-os/freedoom/master/freedoom2.wad"',
578
+ ' ;;',
579
+ ' --help|-h)',
580
+ ' echo "Usage: freedoom [--phase1 | --phase2] [doom options...]"',
581
+ ' return 0',
582
+ ' ;;',
583
+ ' *)',
584
+ ' EXTRA_ARGS="$EXTRA_ARGS $ARG"',
585
+ ' ;;',
586
+ ' esac',
587
+ 'done',
588
+ 'WAD_FILE="$WAD_DIR/$WAD_NAME"',
589
+ 'if [ ! -f "$WAD_FILE" ]; then',
590
+ ' mkdir -p "$WAD_DIR"',
591
+ ' curl -# -L -o "$WAD_FILE" "$WAD_URL"',
592
+ 'fi',
593
+ 'doom -iwad "$WAD_FILE" -nosound $EXTRA_ARGS'
594
+ ].join('\n');
595
+ return {
596
+ ok: true,
597
+ status: 200,
598
+ text: async () => scriptText
599
+ };
600
+ }
562
601
  if (url === 'https://example.com/hello.wasm' || /\.wasm(\?.*)?$/i.test(url)) {
563
602
  return {
564
603
  ok: true,
@@ -689,13 +728,13 @@ describe('WBT CLI subcommands (list, search, show, install, remove, update)', ()
689
728
  const installRes = await run(shell, 'wbt install sqlite3');
690
729
  expect(installRes.exitCode).toBe(0);
691
730
  expect(fetchedUrls.some(u => u.includes('sql-wasm.wasm'))).toBe(true);
692
- expect(shell.context.fs.exists('/var/lib/wbt/wasm/sqlite3.wasm')).toBe(true);
731
+ expect(shell.context.fs.exists('/usr/lib/sqlite3/sqlite3.wasm')).toBe(true);
693
732
 
694
733
  const showRes = await run(shell, 'wbt show sqlite3');
695
- expect(showRes.output.join('\n')).toContain('WASM-File: /var/lib/wbt/wasm/sqlite3.wasm');
734
+ expect(showRes.output.join('\n')).toContain('WASM-File: /usr/lib/sqlite3/sqlite3.wasm');
696
735
 
697
736
  await run(shell, 'wbt remove sqlite3');
698
- expect(shell.context.fs.exists('/var/lib/wbt/wasm/sqlite3.wasm')).toBe(false);
737
+ expect(shell.context.fs.exists('/usr/lib/sqlite3/sqlite3.wasm')).toBe(false);
699
738
  });
700
739
 
701
740
  it('removes an installed package and unregisters its binary from /bin', async () => {
@@ -722,15 +761,19 @@ describe('WBT CLI subcommands (list, search, show, install, remove, update)', ()
722
761
  expect(showCustom.output.join('\n')).toContain('Remote registry test package');
723
762
  });
724
763
 
725
- it('restores installed commands from /var/lib/wbt/installed.json via Wbt.restoreInstalled', async () => {
764
+ it('treats /usr/lib/<pkg>/ as the single source of truth without creating /var/lib/wbt/installed.json', async () => {
726
765
  await run(shell, 'wbt install sqlite3');
766
+ expect(shell.context.fs.exists('/var/lib/wbt/installed.json')).toBe(false);
767
+ expect(shell.context.fs.exists('/usr/lib/sqlite3/package.json')).toBe(true);
768
+
727
769
  const rawFs = shell.context.fs.getRaw();
728
770
  const rawPerms = shell.context.fs.getRawPermissions();
729
771
 
730
- const savedInstalledJson = rawFs.var.lib.wbt['installed.json'];
772
+ // Restore filesystem into a new shell from the directory structure alone
731
773
  const shell2 = await createShell({
732
774
  filesystem: {
733
- var: { lib: { wbt: { 'installed.json': savedInstalledJson } } }
775
+ usr: rawFs.usr,
776
+ bin: rawFs.bin
734
777
  },
735
778
  permissions: rawPerms
736
779
  });
@@ -1366,7 +1409,7 @@ describe('WBT GNU nano WASM package (nano / nano-wasm)', () => {
1366
1409
  it('installs nano and nano-wasm into /bin and runs --version and --help', async () => {
1367
1410
  const installRes = await run(shell, 'wbt install nano');
1368
1411
  expect(installRes.exitCode).toBe(0);
1369
- expect(shell.context.fs.exists('/var/lib/wbt/wasm/nano.wasm')).toBe(true);
1412
+ expect(shell.context.fs.exists('/usr/lib/nano/nano.wasm')).toBe(true);
1370
1413
  expect(shell.context.fs.exists('/bin/nano')).toBe(true);
1371
1414
  expect(shell.context.fs.exists('/bin/nano-wasm')).toBe(true);
1372
1415
 
@@ -1394,18 +1437,18 @@ describe('WBT GNU nano WASM package (nano / nano-wasm)', () => {
1394
1437
  await run(shell, 'wbt install nano-wasm');
1395
1438
  expect(shell.context.fs.exists('/bin/nano')).toBe(true);
1396
1439
  expect(shell.context.fs.exists('/bin/nano-wasm')).toBe(true);
1397
- expect(shell.context.fs.exists('/var/lib/wbt/wasm/nano.wasm')).toBe(true);
1440
+ expect(shell.context.fs.exists('/usr/lib/nano/nano.wasm')).toBe(true);
1398
1441
 
1399
1442
  const rmRes = await run(shell, 'wbt remove nano');
1400
1443
  expect(rmRes.exitCode).toBe(0);
1401
1444
  expect(shell.context.fs.exists('/bin/nano')).toBe(false);
1402
1445
  expect(shell.context.fs.exists('/bin/nano-wasm')).toBe(false);
1403
- expect(shell.context.fs.exists('/var/lib/wbt/wasm/nano.wasm')).toBe(false);
1446
+ expect(shell.context.fs.exists('/usr/lib/nano/nano.wasm')).toBe(false);
1404
1447
  });
1405
1448
 
1406
1449
  it('runs nano even when invoked with readonlyContext without context.fs', async () => {
1407
1450
  await run(shell, 'wbt install nano');
1408
- const NanoCmd = shell.context.fs.getFileByPath('/bin/nano');
1451
+ const NanoCmd = shell._resolveCommandFromPath('/bin/nano');
1409
1452
  expect(NanoCmd).toBeDefined();
1410
1453
 
1411
1454
  const readonlyCtx = Object.freeze({
@@ -1500,6 +1543,371 @@ describe('WBT GNU nano WASM package (nano / nano-wasm)', () => {
1500
1543
  });
1501
1544
  });
1502
1545
 
1546
+ describe('WBT filesystem installer architecture (installer, not runtime)', () => {
1547
+ let shell;
1548
+
1549
+ beforeEach(async () => {
1550
+ shell = await createShell({ filesystem: { home: {} } });
1551
+ shell.context.setCommand(createTestWbt());
1552
+ });
1553
+
1554
+ it('installs pure WASM to /usr/lib/<pkg>/<bin>.wasm and symlinks into /bin/<cmd>', async () => {
1555
+ const installRes = await run(shell, 'wbt install nano');
1556
+ expect(installRes.exitCode).toBe(0);
1557
+
1558
+ // Binary placed in /usr/lib/nano/nano.wasm
1559
+ expect(shell.context.fs.exists('/usr/lib/nano/nano.wasm')).toBe(true);
1560
+ expect(shell.context.fs.isExecutable('/usr/lib/nano/nano.wasm')).toBe(true);
1561
+
1562
+ // Symlinks in /bin
1563
+ expect(shell.context.fs.isSymlink('/bin/nano')).toBe(true);
1564
+ expect(shell.context.fs.readSymlink('/bin/nano')).toBe('/usr/lib/nano/nano.wasm');
1565
+ expect(shell.context.fs.isSymlink('/bin/nano-wasm')).toBe(true);
1566
+ expect(shell.context.fs.readSymlink('/bin/nano-wasm')).toBe('/usr/lib/nano/nano.wasm');
1567
+
1568
+ // Verify /var/lib/wbt is not created
1569
+ expect(shell.context.fs.exists('/var/lib/wbt')).toBe(false);
1570
+ });
1571
+
1572
+ it('runs WASM command directly from /bin without wbt registered in context', async () => {
1573
+ await run(shell, 'wbt install nano');
1574
+
1575
+ // Persist filesystem as BRFS binary container (the official format for brsh persistence)
1576
+ const containerBytes = shell.context.fs.toBinaryContainer();
1577
+
1578
+ // Create a completely fresh shell with the restored filesystem and NO wbt command registered
1579
+ const cleanShell = await createShell({
1580
+ filesystem: containerBytes
1581
+ });
1582
+ if (cleanShell.context.fs.exists('/bin/wbt')) {
1583
+ cleanShell.context.fs.deleteFileByPath('/bin/wbt');
1584
+ }
1585
+
1586
+ // Verify wbt is NOT in cleanShell
1587
+ expect(cleanShell.context.getCommand('wbt')).toBeNull();
1588
+
1589
+ // Invoking bare command 'nano --version' runs WASM directly through Shell & WasmCommand
1590
+ const res = await run(cleanShell, 'nano --version');
1591
+ expect(res.exitCode).toBe(0);
1592
+ expect(res.output.join('\n')).toMatch(/GNU nano, version 8\.0|nano.*8\.0\.[0-9]+.*wasm/i);
1593
+
1594
+ // Invoking via full path '/bin/nano --version' also runs WASM directly
1595
+ const binRes = await run(cleanShell, '/bin/nano --version');
1596
+ expect(binRes.exitCode).toBe(0);
1597
+ expect(binRes.output.join('\n')).toMatch(/GNU nano, version 8\.0|nano.*8\.0\.[0-9]+.*wasm/i);
1598
+
1599
+ // Invoking via alias 'nano-wasm --version' also runs WASM directly
1600
+ const aliasRes = await run(cleanShell, 'nano-wasm --version');
1601
+ expect(aliasRes.exitCode).toBe(0);
1602
+ expect(aliasRes.output.join('\n')).toMatch(/GNU nano, version 8\.0|nano.*8\.0\.[0-9]+.*wasm/i);
1603
+ });
1604
+
1605
+ it('auto-wires sibling JS and WASM in /usr/lib/<pkg>/ without wbt runtime', async () => {
1606
+ const dummyWasmBytes = new Uint8Array([
1607
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
1608
+ 0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
1609
+ 0x03, 0x02, 0x01, 0x00,
1610
+ 0x07, 0x0a, 0x01, 0x06, 0x5f, 0x73, 0x74, 0x61, 0x72, 0x74, 0x00, 0x00,
1611
+ 0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b
1612
+ ]);
1613
+
1614
+ const jsCode = `
1615
+ module.exports = async function(Module) {
1616
+ return {
1617
+ exec: async function(args) {
1618
+ return 0;
1619
+ }
1620
+ };
1621
+ };
1622
+ `;
1623
+
1624
+ // Co-locate .wasm and .js in /usr/lib/mytool/
1625
+ const WasmCmd = shell.constructor.WasmCommand;
1626
+ WasmCmd.writeBytesToFs(shell.context.fs, '/usr/lib/mytool/mytool.wasm', dummyWasmBytes);
1627
+ shell.context.fs.setFileByPath('/usr/lib/mytool/mytool.js', jsCode, true);
1628
+ shell.context.fs.setMode('/usr/lib/mytool/mytool.wasm', 0o755);
1629
+ shell.context.fs.setMode('/usr/lib/mytool/mytool.js', 0o755);
1630
+
1631
+ // Create symlink /bin/mytool -> /usr/lib/mytool/mytool.js
1632
+ shell.context.fs.createSymlink('/usr/lib/mytool/mytool.js', '/bin/mytool');
1633
+ shell.context.fs.setMode('/bin/mytool', 0o755);
1634
+
1635
+ const execRes = await run(shell, 'mytool hello world');
1636
+ expect(execRes.exitCode).toBe(0);
1637
+ });
1638
+
1639
+ it('registers doom package with aliases doom-wasm, doom-ascii, and freedoom launcher script', async () => {
1640
+ const BaseWbt = createTestWbt();
1641
+ const registry = BaseWbt.DEFAULT_REGISTRY;
1642
+ expect(registry.doom).toBeDefined();
1643
+ expect(registry.doom.bin).toBe('doom');
1644
+ expect(registry.doom.aliases).toContain('doom-wasm');
1645
+ expect(registry.doom.aliases).toContain('doom-ascii');
1646
+ expect(registry.doom.scripts).toBeDefined();
1647
+ expect(registry.doom.scripts.freedoom).toContain('/bin/freedoom');
1648
+ expect(registry.doom.type).toBe('custom-wasm');
1649
+
1650
+ // Test search by script name 'freedoom'
1651
+ const searchRes = await run(shell, 'wbt search freedoom');
1652
+ expect(searchRes.exitCode).toBe(0);
1653
+ expect(searchRes.output.join('\n')).toContain('doom/wasm');
1654
+
1655
+ // Test show
1656
+ const showRes = await run(shell, 'wbt show freedoom');
1657
+ expect(showRes.exitCode).toBe(0);
1658
+ expect(showRes.output.join('\n')).toContain('Package: doom');
1659
+ expect(showRes.output.join('\n')).toContain('Aliases: doom-wasm, doom-ascii');
1660
+ expect(showRes.output.join('\n')).toContain('Scripts: freedoom');
1661
+ expect(showRes.output.join('\n')).toContain('doom.wasm');
1662
+ });
1663
+
1664
+ it('installs freedoom launcher script alongside doom, auto-downloads freedoom1.wad if missing, and reuses cached WAD on second run', async () => {
1665
+ // Ephemeral wbt run freedoom --help works even before installing doom
1666
+ const ephemeralHelp = await run(shell, 'wbt run freedoom --help');
1667
+ expect(ephemeralHelp.exitCode).toBe(0);
1668
+ expect(ephemeralHelp.output.join('\n')).toContain('Usage: freedoom');
1669
+ expect(shell.context.fs.exists('/bin/freedoom')).toBe(false);
1670
+
1671
+ const installRes = await run(shell, 'wbt install doom');
1672
+ expect(installRes.exitCode).toBe(0);
1673
+
1674
+ expect(shell.context.fs.exists('/usr/lib/doom/doom.wasm')).toBe(true);
1675
+ expect(shell.context.fs.exists('/usr/lib/doom/freedoom')).toBe(true);
1676
+ expect(shell.context.fs.isSymlink('/bin/doom')).toBe(true);
1677
+ expect(shell.context.fs.isSymlink('/bin/freedoom')).toBe(true);
1678
+ expect(shell.context.fs.readSymlink('/bin/freedoom')).toBe('/usr/lib/doom/freedoom');
1679
+
1680
+ // Help works without fetching WAD
1681
+ const helpRes = await run(shell, 'freedoom --help');
1682
+ expect(helpRes.exitCode).toBe(0);
1683
+ expect(helpRes.output.join('\n')).toContain('Usage: freedoom');
1684
+ expect(shell.context.fs.exists('/usr/share/games/doom/freedoom1.wad')).toBe(false);
1685
+
1686
+ // Mock global fetch for curl WAD download
1687
+ const origFetch = globalThis.fetch;
1688
+ let wad1FetchCount = 0;
1689
+ let wad2FetchCount = 0;
1690
+ const fakeWadBytes = new Uint8Array([0x49, 0x57, 0x41, 0x44, 0x00, 0x00, 0x00, 0x00]); // "IWAD\0\0\0\0"
1691
+ globalThis.fetch = async (url) => {
1692
+ if (String(url).includes('freedoom1.wad')) {
1693
+ wad1FetchCount++;
1694
+ return new Response(fakeWadBytes, {
1695
+ status: 200,
1696
+ headers: { 'content-type': 'application/octet-stream', 'content-length': String(fakeWadBytes.length) }
1697
+ });
1698
+ }
1699
+ if (String(url).includes('freedoom2.wad')) {
1700
+ wad2FetchCount++;
1701
+ return new Response(fakeWadBytes, {
1702
+ status: 200,
1703
+ headers: { 'content-type': 'application/octet-stream', 'content-length': String(fakeWadBytes.length) }
1704
+ });
1705
+ }
1706
+ return origFetch(url);
1707
+ };
1708
+
1709
+ try {
1710
+ // First run: downloads freedoom1.wad to /usr/share/games/doom/freedoom1.wad and runs doom
1711
+ const run1 = await run(shell, 'freedoom');
1712
+ expect(run1.exitCode).toBe(0);
1713
+ expect(wad1FetchCount).toBe(1);
1714
+ expect(shell.context.fs.exists('/usr/share/games/doom/freedoom1.wad')).toBe(true);
1715
+
1716
+ // Second run: WAD already exists at /usr/share/games/doom/freedoom1.wad -> skips download!
1717
+ const run2 = await run(shell, 'freedoom');
1718
+ expect(run2.exitCode).toBe(0);
1719
+ expect(wad1FetchCount).toBe(1);
1720
+
1721
+ // Phase 2: downloads freedoom2.wad to /usr/share/games/doom/freedoom2.wad
1722
+ const runPhase2 = await run(shell, 'freedoom --phase2');
1723
+ expect(runPhase2.exitCode).toBe(0);
1724
+ expect(wad2FetchCount).toBe(1);
1725
+ expect(shell.context.fs.exists('/usr/share/games/doom/freedoom2.wad')).toBe(true);
1726
+ } finally {
1727
+ globalThis.fetch = origFetch;
1728
+ }
1729
+
1730
+ // Removing doom removes /bin/freedoom and /usr/lib/doom/freedoom cleanly
1731
+ const rmRes = await run(shell, 'wbt remove doom');
1732
+ expect(rmRes.exitCode).toBe(0);
1733
+ expect(shell.context.fs.exists('/bin/freedoom')).toBe(false);
1734
+ expect(shell.context.fs.isSymlink('/bin/freedoom')).toBe(false);
1735
+ expect(shell.context.fs.exists('/usr/lib/doom/freedoom')).toBe(false);
1736
+ });
1737
+
1738
+ it('forwards interactive TTY input and raw ANSI stdout cleanly when an interactive WASM binary is launched inside a shell script', async () => {
1739
+ await run(shell, 'wbt install nano');
1740
+
1741
+ // Create a wrapper shell script similar to freedoom
1742
+ shell.context.fs._setFileRaw('/bin/edit-note', '#!/bin/sh\nnano /home/script-note.txt\n', true);
1743
+ shell.context.fs.setMode('/bin/edit-note', 0o755);
1744
+
1745
+ const rawChunks = [];
1746
+ const onData = (chunk) => rawChunks.push(typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk));
1747
+ shell.stdout.on('data', onData);
1748
+
1749
+ const cmdPromise = shell.onCommand('edit-note');
1750
+ await new Promise(r => setTimeout(r, 120));
1751
+
1752
+ for (const ch of 'Via wrapper!') {
1753
+ shell.write(ch);
1754
+ await new Promise(r => setTimeout(r, 8));
1755
+ }
1756
+ await new Promise(r => setTimeout(r, 30));
1757
+
1758
+ // Save: Ctrl+O, Enter, Exit: Ctrl+X
1759
+ shell.write('\x0f');
1760
+ await new Promise(r => setTimeout(r, 30));
1761
+ shell.write('\r');
1762
+ await new Promise(r => setTimeout(r, 30));
1763
+ shell.write('\x18');
1764
+
1765
+ await cmdPromise;
1766
+ shell.stdout.off('data', onData);
1767
+
1768
+ expect(shell.lastCode).toBe(0);
1769
+ expect(rawChunks.join('')).toContain('\x1b[?1049h');
1770
+ const saved = shell.context.fs.getFileByPath('/home/script-note.txt');
1771
+ expect(saved).toContain('Via wrapper!');
1772
+ });
1773
+
1774
+ it('Wbt.restoreInstalled is a safe no-op on already-restored filesystems', async () => {
1775
+ await run(shell, 'wbt install nano');
1776
+ expect(shell.context.fs.isSymlink('/bin/nano')).toBe(true);
1777
+
1778
+ const BaseWbt = createTestWbt();
1779
+ BaseWbt.restoreInstalled(shell);
1780
+
1781
+ // /bin/nano remains a symlink to /usr/lib/nano/nano.wasm
1782
+ expect(shell.context.fs.isSymlink('/bin/nano')).toBe(true);
1783
+ expect(shell.context.fs.readSymlink('/bin/nano')).toBe('/usr/lib/nano/nano.wasm');
1784
+ });
1785
+
1786
+ it('cleans up temporary files in /tmp after wbt run', async () => {
1787
+ const runRes = await run(shell, 'wbt run nano --version');
1788
+ expect(runRes.exitCode).toBe(0);
1789
+ expect(runRes.output.join('\n')).toMatch(/GNU nano, version 8\.0|nano.*8\.0\.[0-9]+.*wasm/i);
1790
+
1791
+ // Not installed permanently
1792
+ expect(shell.context.fs.exists('/bin/nano')).toBe(false);
1793
+
1794
+ // Check that /tmp does not contain lingering .wbt-run- directories
1795
+ const tmpDir = shell.context.fs.getFileByPath('/tmp') || {};
1796
+ const tmpKeys = Object.keys(tmpDir);
1797
+ expect(tmpKeys.some(k => k.startsWith('.wbt-run-'))).toBe(false);
1798
+ });
1799
+
1800
+ it('persists interactive: true in /usr/lib/<pkg>/package.json so standalone WasmCommand detects interactivity immediately', async () => {
1801
+ await run(shell, 'wbt install nano');
1802
+ await run(shell, 'wbt install doom');
1803
+
1804
+ const nanoPkgJson = JSON.parse(shell.context.fs.getFileByPath('/usr/lib/nano/package.json'));
1805
+ const doomPkgJson = JSON.parse(shell.context.fs.getFileByPath('/usr/lib/doom/package.json'));
1806
+ expect(nanoPkgJson.interactive).toBe(true);
1807
+ expect(doomPkgJson.interactive).toBe(true);
1808
+
1809
+ const WasmCommand = shell.constructor.WasmCommand;
1810
+ const doomCmd = new WasmCommand('/usr/lib/doom/doom.wasm', [], shell.context);
1811
+ expect(doomCmd.interactive).toBe(true);
1812
+ expect(doomCmd.captureInput).toBe(true);
1813
+ });
1814
+
1815
+ it('does not duplicate stdin keystrokes and forwards live stdout resizes during wbt run', async () => {
1816
+ if (!NANO_WASM_BYTES) return;
1817
+ shell.setTerminalSize(110, 36);
1818
+
1819
+ const cmdPromise = shell.onCommand('wbt run nano /wbt-run-note.txt');
1820
+ await new Promise(r => setTimeout(r, 80));
1821
+
1822
+ // Resize terminal mid-run -> forwarded to ephemeral wbt run subcommand without error
1823
+ shell.setTerminalSize(124, 40);
1824
+ await new Promise(r => setTimeout(r, 20));
1825
+
1826
+ for (const ch of 'Single echo!') {
1827
+ shell.write(ch);
1828
+ await new Promise(r => setTimeout(r, 6));
1829
+ }
1830
+ await new Promise(r => setTimeout(r, 30));
1503
1831
 
1832
+ // Save: Ctrl+O, Enter, Exit: Ctrl+X
1833
+ shell.write('\x0f');
1834
+ await new Promise(r => setTimeout(r, 30));
1835
+ shell.write('\r');
1836
+ await new Promise(r => setTimeout(r, 30));
1837
+ shell.write('\x18');
1504
1838
 
1839
+ await cmdPromise;
1840
+ expect(shell.lastCode).toBe(0);
1841
+ const saved = shell.context.fs.getFileByPath('/wbt-run-note.txt');
1842
+ expect(saved).toContain('Single echo!');
1843
+ expect(saved).not.toContain('SSiinnggllee');
1844
+ });
1845
+
1846
+ it('extends standard Command rather than LocalCommand for both Wbt and GenericWasmCommand', () => {
1847
+ const Command = require('../lib/Command.js');
1848
+ const LocalCommand = require('../lib/local/LocalCommand.js');
1849
+ const GenericCmd = Wbt.createGenericWasmCommand({ name: 'demo-tool' });
1850
+
1851
+ expect(Wbt.prototype instanceof Command).toBe(true);
1852
+ expect(Wbt.prototype instanceof LocalCommand).toBe(false);
1853
+ expect(GenericCmd.prototype instanceof Command).toBe(true);
1854
+ expect(GenericCmd.prototype instanceof LocalCommand).toBe(false);
1855
+ });
1856
+
1857
+ it('works across separate built ESM bundles (dist/shell.es.js + dist/wbt.es.js) and runs installed binaries without wbt at runtime', async () => {
1858
+ const distShellPath = path.resolve(import.meta.dirname, '../dist/shell.es.js');
1859
+ const distWbtPath = path.resolve(import.meta.dirname, '../dist/wbt.es.js');
1860
+ if (!fs.existsSync(distShellPath) || !fs.existsSync(distWbtPath)) return;
1861
+
1862
+ const ShellMod = await import(distShellPath);
1863
+ const WbtMod = await import(distWbtPath);
1864
+ const BundledShell = ShellMod.default?.default ?? ShellMod.default ?? ShellMod;
1865
+ const BundledWbt = WbtMod.default?.default ?? WbtMod.default ?? WbtMod;
1866
+
1867
+ const ConfiguredBundledWbt = BundledWbt.configure({
1868
+ fetch: async (url) => {
1869
+ if (url.endsWith('freedoom')) {
1870
+ return {
1871
+ ok: true,
1872
+ status: 200,
1873
+ text: async () => '#!/bin/sh\necho "freedoom-bundle-ok:$1"\n'
1874
+ };
1875
+ }
1876
+ return {
1877
+ ok: true,
1878
+ status: 200,
1879
+ arrayBuffer: async () => MINIMAL_WASM_BYTES.buffer.slice(0)
1880
+ };
1881
+ }
1882
+ });
1883
+
1884
+ const s1 = new BundledShell({ filesystem: {}, interactive: false });
1885
+ s1.context.setCommand(ConfiguredBundledWbt);
1886
+
1887
+ const listRes = await run(s1, 'wbt list');
1888
+ expect(listRes.exitCode).toBe(0);
1889
+ expect(listRes.output.join('\n')).toContain('doom/wasm');
1890
+
1891
+ // Ephemeral script execution via `wbt run` with readonlyContext across bundles
1892
+ const runRes = await run(s1, 'wbt run freedoom hello');
1893
+ expect(runRes.exitCode).toBe(0);
1894
+ expect(runRes.output.join('\n')).toContain('freedoom-bundle-ok:hello');
1895
+
1896
+ // Install into filesystem via `wbt install`, serialize to .brfs, and boot a fresh Shell WITHOUT Wbt
1897
+ const installRes = await run(s1, 'wbt install doom');
1898
+ expect(installRes.exitCode).toBe(0);
1899
+
1900
+ const containerBytes = s1.context.fs.toBinaryContainer();
1901
+ const s2 = await BundledShell.fromContainer(containerBytes, { interactive: false });
1902
+ // Ensure Wbt is NOT registered in s2
1903
+ expect(s2.context.getCommand('wbt')).toBeNull();
1904
+
1905
+ const nativeRes = await run(s2, 'freedoom from-container');
1906
+ expect(nativeRes.exitCode).toBe(0);
1907
+ expect(nativeRes.output.join('\n')).toContain('freedoom-bundle-ok:from-container');
1908
+
1909
+ const wasmRes = await run(s2, 'doom');
1910
+ expect(wasmRes.exitCode).toBe(0);
1911
+ });
1912
+ });
1505
1913