brsh 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -5,6 +5,7 @@ const LocalCommand = require('./lib/local/LocalCommand');
5
5
  const ScriptCommand = require('./lib/ScriptCommand');
6
6
  const WasmCommand = require('./lib/WasmCommand');
7
7
  const Command = require('./lib/Command');
8
+ const InteractiveCommand = require('./lib/InteractiveCommand');
8
9
 
9
10
  const builtins = require('./lib/builtins');
10
11
  const localCommands = require('./lib/local');
@@ -79,6 +80,17 @@ class Shell extends EventEmitter {
79
80
  }
80
81
  }
81
82
 
83
+ setTerminalSize(cols, rows) {
84
+ this._terminalSize = { cols, rows };
85
+ this.context.setVar('COLUMNS', String(cols));
86
+ this.context.setVar('LINES', String(rows));
87
+ this.emit('resize', { cols, rows });
88
+ }
89
+
90
+ get terminalSize() {
91
+ return this._terminalSize || { cols: 80, rows: 24 };
92
+ }
93
+
82
94
  _loadDefaultCommands() {
83
95
  localCommands.forEach(command => {
84
96
  this.context.setCommand(command);
@@ -233,6 +245,9 @@ class Shell extends EventEmitter {
233
245
  this._emitOutput(lines);
234
246
  });
235
247
  }
248
+ if (instance.interactive) {
249
+ this.emit('interactive');
250
+ }
236
251
 
237
252
  return instance.runCommand().then(result => {
238
253
  const stdOutput = result.getStdOutput();
@@ -444,7 +459,11 @@ class Shell extends EventEmitter {
444
459
  }
445
460
 
446
461
  _evalArithmetic(expr) {
447
- const expanded = expr.replace(/\${?([\w\d]+)}?/g, (m, name) =>
462
+ // First expand $VAR and ${VAR} references
463
+ let expanded = expr.replace(/\${?([\w\d]+)}?/g, (m, name) =>
464
+ String(parseInt(this.context.getVar(name)) || 0));
465
+ // Then expand bare variable names (e.g. I in $((I+1)))
466
+ expanded = expanded.replace(/\b([A-Za-z_]\w*)\b/g, (m, name) =>
448
467
  String(parseInt(this.context.getVar(name)) || 0));
449
468
  if (!/^[\d\s+\-*/%()]+$/.test(expanded.trim())) return 0;
450
469
  try {
@@ -607,6 +626,7 @@ Shell.STATUS_WORKING = 'WORKING';
607
626
  Shell.STATUS_DESTROYED = 'DESTROYED';
608
627
 
609
628
  Shell.Command = Command;
629
+ Shell.InteractiveCommand = InteractiveCommand;
610
630
  Shell.FS = BaseFileSystem;
611
631
 
612
632
  global.shell = Shell;
package/lib/Command.js CHANGED
@@ -29,6 +29,12 @@ class Command extends EventEmitter {
29
29
  return this.result;
30
30
  })
31
31
  .catch(e => {
32
+ // Re-throw shell control-flow signals (break, continue, return,
33
+ // errexit) so they propagate correctly through function calls
34
+ // and nested script execution.
35
+ if (e && e.__type) {
36
+ throw e;
37
+ }
32
38
  if(e) {
33
39
  this.stdErr = e.message || e;
34
40
  }
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ const LocalCommand = require('./local/LocalCommand');
4
+
5
+ /**
6
+ * Base class for interactive full-screen terminal applications (e.g. text editors).
7
+ *
8
+ * Subclasses:
9
+ * - Must implement `run()` — return a Promise that resolves when the app exits.
10
+ * - Must implement `onInput(key)` — receives keystroke strings:
11
+ * - Printable characters: 'a', 'B', '1', ' ', etc.
12
+ * - Special keys: 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
13
+ * 'Enter', 'Backspace', 'Delete', 'Escape',
14
+ * 'Home', 'End', 'PageUp', 'PageDown', 'Tab'
15
+ * - Ctrl combos: '^A' through '^Z' (caret + uppercase letter)
16
+ * - Should render by setting `this.stdOut = screenString` then calling `this.flush()`.
17
+ * Start the screen string with '\x1b[2J\x1b[H' to signal a full-screen replace.
18
+ * Send the entire screen as ONE stdOut assignment (multi-line string) for efficiency.
19
+ *
20
+ * Terminal size is available via `this.terminalSize` → `{ cols, rows }`.
21
+ */
22
+ class InteractiveCommand extends LocalCommand {
23
+ /**
24
+ * Tells Shell to route all keystrokes here via onInput().
25
+ */
26
+ get captureInput() {
27
+ return true;
28
+ }
29
+
30
+ /**
31
+ * Tells Shell/Terminal that this command owns the full screen.
32
+ * Terminal will hide the normal <ul> output list and show a <pre>
33
+ * rendering surface for the duration of this command.
34
+ */
35
+ get interactive() {
36
+ return true;
37
+ }
38
+
39
+ /**
40
+ * Current terminal dimensions reported by the host Terminal, or 80×24 fallback.
41
+ * @returns {{ cols: number, rows: number }}
42
+ */
43
+ get terminalSize() {
44
+ const cols = parseInt(this.context.getVar('COLUMNS'), 10) || 80;
45
+ const rows = parseInt(this.context.getVar('LINES'), 10) || 24;
46
+ return { cols, rows };
47
+ }
48
+ }
49
+
50
+ module.exports = InteractiveCommand;
@@ -63,6 +63,9 @@ class ScriptCommand extends LocalCommand {
63
63
  this.sandbox.lastCode = e.code;
64
64
  } else if (e && e.__type === 'errexit') {
65
65
  this.sandbox.lastCode = e.code;
66
+ } else if (e && (e.__type === 'break' || e.__type === 'continue')) {
67
+ this.stdErr = `${e.__type}: only meaningful in a for or while loop`;
68
+ this.sandbox.lastCode = 1;
66
69
  } else {
67
70
  return Promise.reject(e);
68
71
  }
@@ -221,10 +224,10 @@ class ScriptCommand extends LocalCommand {
221
224
  return { node: { type: 'for', variable, list, bodyLines }, consumed: i - start };
222
225
  }
223
226
 
224
- _executeNodes(nodes) {
225
- return nodes.reduce((chain, node) => {
226
- return chain.then(() => this._executeNode(node));
227
- }, Promise.resolve());
227
+ async _executeNodes(nodes) {
228
+ for (const node of nodes) {
229
+ await this._executeNode(node);
230
+ }
228
231
  }
229
232
 
230
233
  _executeNode(node) {
@@ -268,6 +271,17 @@ class ScriptCommand extends LocalCommand {
268
271
  const code = match ? parseInt(match[1], 10) : 0;
269
272
  return Promise.reject({ __type: 'return', code });
270
273
  }
274
+ // Intercept 'break [n]' and 'continue [n]' loop control signals
275
+ if (/^break(\s+\d+)?\s*$/.test(node.line.trim())) {
276
+ const match = node.line.trim().match(/^break\s+(\d+)/);
277
+ const count = match ? parseInt(match[1], 10) : 1;
278
+ return Promise.reject({ __type: 'break', count });
279
+ }
280
+ if (/^continue(\s+\d+)?\s*$/.test(node.line.trim())) {
281
+ const match = node.line.trim().match(/^continue\s+(\d+)/);
282
+ const count = match ? parseInt(match[1], 10) : 1;
283
+ return Promise.reject({ __type: 'continue', count });
284
+ }
271
285
  // xtrace (-x): print each command to stderr before executing
272
286
  const flags = this.sandbox.context.getVar('-') || '';
273
287
  if (flags.includes('x')) {
@@ -289,43 +303,58 @@ class ScriptCommand extends LocalCommand {
289
303
  return Promise.resolve();
290
304
  }
291
305
 
292
- _executeIf(node) {
293
- const tryClause = (i) => {
294
- if (i >= node.clauses.length) {
295
- return node.elseLines.length > 0
296
- ? this._executeNodes(this._parseLines(node.elseLines))
297
- : Promise.resolve();
306
+ async _executeIf(node) {
307
+ for (const clause of node.clauses) {
308
+ await this.sandbox.onCommand(clause.condition, false);
309
+ if (this.sandbox.lastCode === 0) {
310
+ return this._executeNodes(this._parseLines(clause.bodyLines));
298
311
  }
299
- const clause = node.clauses[i];
300
- return this.sandbox.onCommand(clause.condition, false).then(() => {
301
- if (this.sandbox.lastCode === 0) {
302
- return this._executeNodes(this._parseLines(clause.bodyLines));
303
- }
304
- return tryClause(i + 1);
305
- });
306
- };
307
- return tryClause(0);
312
+ }
313
+ if (node.elseLines.length > 0) {
314
+ return this._executeNodes(this._parseLines(node.elseLines));
315
+ }
308
316
  }
309
317
 
310
- _executeWhile(node) {
311
- const step = () => this.sandbox.onCommand(node.condition, false).then(() => {
312
- if (this.sandbox.lastCode === 0) {
313
- return this._executeNodes(this._parseLines(node.bodyLines)).then(step);
318
+ async _executeWhile(node) {
319
+ while (true) {
320
+ await this.sandbox.onCommand(node.condition, false);
321
+ if (this.sandbox.lastCode !== 0) break;
322
+ try {
323
+ await this._executeNodes(this._parseLines(node.bodyLines));
324
+ } catch (e) {
325
+ if (e && e.__type === 'break') {
326
+ if (e.count <= 1) break;
327
+ throw { __type: 'break', count: e.count - 1 };
328
+ }
329
+ if (e && e.__type === 'continue') {
330
+ if (e.count <= 1) continue;
331
+ throw { __type: 'continue', count: e.count - 1 };
332
+ }
333
+ throw e;
314
334
  }
315
- });
316
- return step();
335
+ }
317
336
  }
318
337
 
319
- _executeFor(node) {
338
+ async _executeFor(node) {
320
339
  const expanded = node.list.replace(/\${?([\w\d]+)}?/g, (m, name) =>
321
340
  this.sandbox.context.getVar(name) || '');
322
341
  const items = expanded.split(/\s+/).filter(Boolean);
323
- return items.reduce((chain, value) => {
324
- return chain.then(() => {
325
- this.sandbox.context.setVar(node.variable, value);
326
- return this._executeNodes(this._parseLines(node.bodyLines));
327
- });
328
- }, Promise.resolve());
342
+ for (const value of items) {
343
+ this.sandbox.context.setVar(node.variable, value);
344
+ try {
345
+ await this._executeNodes(this._parseLines(node.bodyLines));
346
+ } catch (e) {
347
+ if (e && e.__type === 'break') {
348
+ if (e.count <= 1) break;
349
+ throw { __type: 'break', count: e.count - 1 };
350
+ }
351
+ if (e && e.__type === 'continue') {
352
+ if (e.count <= 1) continue;
353
+ throw { __type: 'continue', count: e.count - 1 };
354
+ }
355
+ throw e;
356
+ }
357
+ }
329
358
  }
330
359
 
331
360
  _parseFunction(lines, start) {
@@ -421,19 +450,18 @@ class ScriptCommand extends LocalCommand {
421
450
  return this._executeNodes(this._parseLines(bodyLines));
422
451
  }
423
452
 
424
- _executeCase(node) {
425
- return this.sandbox._replaceVariables(node.word).then(expanded => {
426
- // Strip outer quotes produced by variable expansion
427
- const value = ((expanded.startsWith('"') && expanded.endsWith('"'))
428
- || (expanded.startsWith("'") && expanded.endsWith("'")))
429
- ? expanded.slice(1, -1) : expanded;
453
+ async _executeCase(node) {
454
+ const expanded = await this.sandbox._replaceVariables(node.word);
455
+ // Strip outer quotes produced by variable expansion
456
+ const value = ((expanded.startsWith('"') && expanded.endsWith('"'))
457
+ || (expanded.startsWith("'") && expanded.endsWith("'")))
458
+ ? expanded.slice(1, -1) : expanded;
430
459
 
431
- for (const clause of node.clauses) {
432
- if (this._matchPattern(clause.pattern, value)) {
433
- return this._executeNodes(this._parseLines(clause.bodyLines));
434
- }
460
+ for (const clause of node.clauses) {
461
+ if (this._matchPattern(clause.pattern, value)) {
462
+ return this._executeNodes(this._parseLines(clause.bodyLines));
435
463
  }
436
- });
464
+ }
437
465
  }
438
466
 
439
467
  _matchPattern(pattern, value) {
package/lib/Terminal.js CHANGED
@@ -142,6 +142,25 @@ class Terminal {
142
142
  this._cmdList.classList.add('terminal--wrap');
143
143
  }
144
144
  parent.appendChild(this._cmdList);
145
+
146
+ // Full-screen surface for interactive commands (pico, etc.)
147
+ this._screen = document.createElement('pre');
148
+ this._screen.className = 'terminal__screen';
149
+ this._screen.style.fontFamily = `'${font}', monospace`;
150
+ parent.appendChild(this._screen);
151
+
152
+ // Hidden single-character span for measuring character cell dimensions
153
+ this._charMeasure = document.createElement('span');
154
+ this._charMeasure.className = 'terminal__char-measure';
155
+ this._charMeasure.textContent = 'X';
156
+ this._charMeasure.setAttribute('aria-hidden', 'true');
157
+ parent.appendChild(this._charMeasure);
158
+
159
+ // Measure on first paint, then track container resizes
160
+ setTimeout(() => this._measureAndSetSize(), 0);
161
+ if (typeof ResizeObserver !== 'undefined') {
162
+ new ResizeObserver(() => this._measureAndSetSize()).observe(parent);
163
+ }
145
164
  }
146
165
 
147
166
  _newPrompt(callback) {
@@ -272,6 +291,9 @@ class Terminal {
272
291
 
273
292
  _statusCheck(status) {
274
293
  if(status === Shell.STATUS_READY) {
294
+ if (this._interactive) {
295
+ this._exitInteractiveMode();
296
+ }
275
297
  this._working = false;
276
298
  if (!this._historyLoaded) {
277
299
  this._loadHistory();
@@ -339,17 +361,27 @@ class Terminal {
339
361
  this.cli.on('status', this._statusCheck.bind(this));
340
362
 
341
363
  this.cli.on('stdOut', line => {
342
- this._print(line, 'out');
364
+ if (this._interactive) {
365
+ this._renderInteractiveScreen(line);
366
+ } else {
367
+ this._print(line, 'out');
368
+ }
343
369
  });
344
370
 
345
371
  this.cli.on('stdErr', line => {
346
- this._print(line, 'err');
372
+ if (!this._interactive) {
373
+ this._print(line, 'err');
374
+ }
347
375
  });
348
376
 
349
377
  this.cli.on('clear', () => {
350
378
  this._clearOutput();
351
379
  });
352
380
 
381
+ this.cli.on('interactive', () => {
382
+ this._enterInteractiveMode();
383
+ });
384
+
353
385
  this.cli.on('exit', code => {
354
386
  delete this.cli;
355
387
  if(typeof this._exitFn === 'function') {
@@ -362,6 +394,14 @@ class Terminal {
362
394
 
363
395
  _listenForKeyEvents(onUpdate, el) {
364
396
  window.addEventListener('keydown', e => {
397
+ // Interactive mode: route ALL keystrokes to the running command
398
+ if (this._interactive) {
399
+ e.preventDefault();
400
+ const key = this._buildInteractiveKey(e);
401
+ if (key) this.cli.onInput(key);
402
+ return;
403
+ }
404
+
365
405
  if (e.keyCode === 9) {
366
406
  e.preventDefault();
367
407
  }
@@ -379,22 +419,23 @@ class Terminal {
379
419
  }
380
420
  });
381
421
 
382
- el.addEventListener('keyup', (e) => this._keyEvent(onUpdate, e.key));
422
+ el.addEventListener('keyup', (e) => {
423
+ if (this._interactive) return;
424
+ this._keyEvent(onUpdate, e.key);
425
+ });
383
426
 
384
427
  window.addEventListener('paste', (e) => {
385
428
  e.preventDefault();
429
+ if (this._interactive) return;
386
430
  const text = (e.clipboardData || window.clipboardData).getData('text');
387
431
  if (!text) return;
388
432
 
389
- // Split on newlines; each newline acts as Enter (submits a command)
390
433
  const segments = text.split(/\r?\n/);
391
434
  segments.forEach((segment, idx) => {
392
- // Bulk-insert characters for this segment
393
435
  const chars = segment.split('');
394
436
  this._buffer.splice(this._cursorPos, 0, ...chars);
395
437
  this._cursorPos += chars.length;
396
438
 
397
- // Newline between segments → submit as Enter
398
439
  if (idx < segments.length - 1) {
399
440
  this._keyEvent(onUpdate, 'Enter');
400
441
  }
@@ -404,6 +445,18 @@ class Terminal {
404
445
  });
405
446
  }
406
447
 
448
+ _buildInteractiveKey(e) {
449
+ const key = e.key;
450
+ // Skip bare modifier keys
451
+ if (['Control', 'Alt', 'Shift', 'Meta'].includes(key)) return null;
452
+ // Ctrl+letter → caret notation '^X'
453
+ if (e.ctrlKey && key.length === 1) {
454
+ return '^' + key.toUpperCase();
455
+ }
456
+ // All other keys passed as e.key strings ('ArrowUp', 'Enter', 'a', etc.)
457
+ return key;
458
+ }
459
+
407
460
  _wordLeft() {
408
461
  let pos = this._cursorPos;
409
462
  while (pos > 0 && this._buffer[pos - 1] === ' ') pos--;
@@ -520,6 +573,48 @@ class Terminal {
520
573
  }
521
574
  }
522
575
  }
576
+ _enterInteractiveMode() {
577
+ this._interactive = true;
578
+ this._cmdList.style.display = 'none';
579
+ this._screen.style.display = 'block';
580
+ this._clearCursor();
581
+ }
582
+
583
+ _exitInteractiveMode() {
584
+ this._interactive = false;
585
+ this._screen.style.display = 'none';
586
+ this._screen.innerHTML = '';
587
+ this._cmdList.style.display = '';
588
+ }
589
+
590
+ _renderInteractiveScreen(text) {
591
+ // Strip ANSI clear-screen and cursor-home/position sequences used as
592
+ // full-screen replace signal. AnsiUp handles colours; we just drop the
593
+ // cursor-control codes before passing to it.
594
+ const cleaned = text
595
+ .replace(/\x1b\[\d*J/g, '') // erase in display (\x1b[2J etc.)
596
+ .replace(/\x1b\[\d+;\d+H/g, '') // cursor position row;col
597
+ .replace(/\x1b\[H/g, ''); // cursor home (no args)
598
+ try {
599
+ this._screen.innerHTML = this._ansi.ansi_to_html(cleaned);
600
+ } catch(e) {
601
+ this._screen.textContent = cleaned;
602
+ }
603
+ }
604
+
605
+ _measureAndSetSize() {
606
+ if (!this._charMeasure || !this.cli) return;
607
+ const charRect = this._charMeasure.getBoundingClientRect();
608
+ const containerRect = this._el.getBoundingClientRect();
609
+ if (!charRect.width || !charRect.height || !containerRect.width) return;
610
+ const cols = Math.max(1, Math.floor(containerRect.width / charRect.width));
611
+ const rows = Math.max(1, Math.floor(containerRect.height / charRect.height));
612
+ if (cols !== this._lastCols || rows !== this._lastRows) {
613
+ this._lastCols = cols;
614
+ this._lastRows = rows;
615
+ this.cli.setTerminalSize(cols, rows);
616
+ }
617
+ }
523
618
  }
524
619
 
525
620
  module.exports = Terminal;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "2.4.0",
3
+ "version": "2.5.0",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",
@@ -1,11 +1,41 @@
1
+ :root {
2
+ --terminal-cursor-bg: #000;
3
+ --terminal-cursor-color: #fff;
4
+ }
5
+
1
6
  .terminal__cursor {
2
7
  display: inline-block;
3
8
  }
4
9
 
10
+ /* Full-screen rendering surface for interactive commands */
11
+ .terminal__screen {
12
+ display: none;
13
+ margin: 0;
14
+ padding: 0;
15
+ white-space: pre;
16
+ overflow: hidden;
17
+ flex: 1;
18
+ line-height: 1.15em;
19
+ }
20
+
21
+ /* Hidden span used to measure character cell dimensions */
22
+ .terminal__char-measure {
23
+ position: absolute;
24
+ visibility: hidden;
25
+ pointer-events: none;
26
+ white-space: pre;
27
+ line-height: 1.15em;
28
+ }
29
+
5
30
  .terminal__cursor.blink {
6
31
  animation: 1s blink 500ms step-end infinite;
7
32
  }
8
33
 
34
+ .terminal__cursor.block {
35
+ background-color: var(--terminal-cursor-bg);
36
+ color: var(--terminal-cursor-color);
37
+ }
38
+
9
39
  .terminal__line {
10
40
  white-space: pre;
11
41
  overflow: hidden;
@@ -21,10 +51,12 @@
21
51
 
22
52
  @keyframes blink {
23
53
  from, to {
24
- opacity: 0;
54
+ background-color: var(--terminal-cursor-bg);
55
+ color: var(--terminal-cursor-color);
25
56
  }
26
57
  50% {
27
- opacity: 1;
58
+ background-color: transparent;
59
+ color: inherit;
28
60
  }
29
61
  }
30
62
 
@@ -1,10 +1,11 @@
1
1
  import { createRequire } from 'module';
2
2
  import { describe, it, expect, beforeEach, afterEach } from 'vitest';
3
3
  import { spawnSync } from 'child_process';
4
- import { mkdtempSync, writeFileSync, mkdirSync, chmodSync, readFileSync, rmSync } from 'fs';
4
+ import { mkdtempSync, writeFileSync, mkdirSync, chmodSync, readFileSync, rmSync, statSync } from 'fs';
5
5
  import { tmpdir } from 'os';
6
6
  import { join, resolve } from 'path';
7
7
  import { fileURLToPath } from 'url';
8
+ import { createContext, runInContext } from 'vm';
8
9
 
9
10
  const require = createRequire(import.meta.url);
10
11
  const { buildStructure } = require('../lib/buildFilesystemStructure.js');
@@ -244,3 +245,96 @@ describe('exportFileSystem CLI', () => {
244
245
  expect(() => new Function(content)).not.toThrow();
245
246
  });
246
247
  });
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // CLI integration tests – --compress (-c) flag
251
+ // ---------------------------------------------------------------------------
252
+
253
+ describe('exportFileSystem CLI --compress', () => {
254
+ let root;
255
+ let outDir;
256
+
257
+ beforeEach(() => {
258
+ root = tmpDir();
259
+ outDir = tmpDir();
260
+ writeFileSync(join(root, 'hello.txt'), 'Hello World');
261
+ writeFileSync(join(root, 'app.js'), 'module.exports = function() {}');
262
+ });
263
+
264
+ afterEach(() => {
265
+ rmSync(root, { recursive: true, force: true });
266
+ rmSync(outDir, { recursive: true, force: true });
267
+ });
268
+
269
+ it('builds successfully with --compress flag', () => {
270
+ const outFile = join(outDir, 'fs.js');
271
+ const r = runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
272
+ expect(r.status).toBe(0);
273
+ expect(r.stdout).toContain('Build succeeded');
274
+ });
275
+
276
+ it('compressed output is valid JavaScript', () => {
277
+ const outFile = join(outDir, 'fs.js');
278
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
279
+ const content = readFileSync(outFile, 'utf8');
280
+ expect(() => new Function(content)).not.toThrow();
281
+ });
282
+
283
+ it('compressed output contains DecompressionStream reference', () => {
284
+ const outFile = join(outDir, 'fs.js');
285
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
286
+ const content = readFileSync(outFile, 'utf8');
287
+ expect(content).toContain('DecompressionStream');
288
+ });
289
+
290
+ it('compressed output does not contain plain text file content', () => {
291
+ const outFile = join(outDir, 'fs.js');
292
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
293
+ const content = readFileSync(outFile, 'utf8');
294
+ expect(content).not.toContain('Hello World');
295
+ });
296
+
297
+ it('compressed output is smaller than uncompressed for text-heavy filesystem', () => {
298
+ const textRoot = tmpDir();
299
+ try {
300
+ for (let i = 0; i < 20; i++) {
301
+ writeFileSync(join(textRoot, `doc${i}.txt`), `${'Content line repeated many times.\n'.repeat(200)} document ${i}`);
302
+ }
303
+ const compressedOut = join(outDir, 'compressed.js');
304
+ const uncompressedOut = join(outDir, 'uncompressed.js');
305
+ runCLI([textRoot, '-v', 'FS', '-o', compressedOut, '--compress']);
306
+ runCLI([textRoot, '-v', 'FS', '-o', uncompressedOut]);
307
+ expect(statSync(compressedOut).size).toBeLessThan(statSync(uncompressedOut).size);
308
+ } finally {
309
+ rmSync(textRoot, { recursive: true, force: true });
310
+ }
311
+ });
312
+
313
+ it('compressed output resolves to an object with filesystem and permissions', async () => {
314
+ const outFile = join(outDir, 'fs.js');
315
+ runCLI([root, '-v', 'TestFS', '-o', outFile, '--compress']);
316
+ const content = readFileSync(outFile, 'utf8');
317
+ const ctx = createContext({
318
+ atob: globalThis.atob,
319
+ DecompressionStream: globalThis.DecompressionStream,
320
+ Response: globalThis.Response,
321
+ TextDecoder: globalThis.TextDecoder,
322
+ Uint8Array,
323
+ Set,
324
+ Object,
325
+ });
326
+ runInContext(content, ctx);
327
+ const result = await ctx.TestFS;
328
+ expect(result).toHaveProperty('filesystem');
329
+ expect(result).toHaveProperty('permissions');
330
+ expect(result.filesystem['hello.txt']).toBe('Hello World');
331
+ });
332
+
333
+ it('compressed output with JS command files still bundles the command code', () => {
334
+ const outFile = join(outDir, 'fs.js');
335
+ runCLI([root, '-v', 'FS', '-o', outFile, '--compress']);
336
+ const content = readFileSync(outFile, 'utf8');
337
+ // app.js exports a function – its compiled form should appear in the bundle
338
+ expect(content.length).toBeGreaterThan(0);
339
+ });
340
+ });