brsh 2.5.6 → 2.7.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.
@@ -0,0 +1,190 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Default built-in registry of WebAssembly packages for wbt (Web Binary Tool).
5
+ *
6
+ * Each entry describes a package that can be installed via `wbt install <name>`:
7
+ * - name: canonical package name
8
+ * - bin: primary binary command name registered in PATH (defaults to name)
9
+ * - aliases: optional extra command aliases (e.g. sqlite -> sqlite3, asrun/asnode -> assemblyscript)
10
+ * - version: package version
11
+ * - description: short summary shown in `wbt list` / `wbt search`
12
+ * - details: extended description shown in `wbt show`
13
+ * - homepage: upstream project URL
14
+ * - cdnUrl: primary ESM CDN URL used to load the WASM package at runtime
15
+ * - type: 'builtin-adapter' (uses a built-in Command adapter) | 'custom-wasm' (raw WASI binary)
16
+ */
17
+ const DEFAULT_REGISTRY = {
18
+ pglite: {
19
+ name: 'pglite',
20
+ bin: 'pglite',
21
+ aliases: ['psql', 'pg_ctl'],
22
+ version: '0.2.17',
23
+ description: 'Lightweight WASM Postgres database & daemon in the browser and Node',
24
+ details: 'PGlite is a WASM build of PostgreSQL packaged into a client-side library that runs a full Postgres database in memory, persisted to the brsh filesystem, or as a background server daemon (`pglite serve` / `pg_ctl start`).',
25
+ homepage: 'https://pglite.dev',
26
+ cdnUrl: 'https://esm.sh/@electric-sql/pglite@0.2.17',
27
+ type: 'builtin-adapter',
28
+ adapter: 'pglite',
29
+ size: '3.1 MB'
30
+ },
31
+ sqlite3: {
32
+ name: 'sqlite3',
33
+ bin: 'sqlite3',
34
+ aliases: ['sqlite'],
35
+ version: '1.13.0',
36
+ description: 'SQLite compiled to WebAssembly (via sql.js) with filesystem persistence',
37
+ details: 'SQLite3 WASM allows creating, querying, and modifying SQLite database files directly in the brsh filesystem. Supports interactive SQL shell, piped SQL input, and one-shot queries.',
38
+ homepage: 'https://sql.js.org',
39
+ cdnUrl: 'https://esm.sh/sql.js@1.13.0',
40
+ wasmUrl: 'https://cdn.jsdelivr.net/npm/sql.js@1.13.0/dist/sql-wasm.wasm',
41
+ type: 'generic-runtime',
42
+ repl: { prompt: 'sqlite> ', sessionArg: true },
43
+ size: '680 KB'
44
+ },
45
+ assemblyscript: {
46
+ name: 'assemblyscript',
47
+ bin: 'asc',
48
+ aliases: ['asrun', 'asnode', 'assemblyscript'],
49
+ version: '0.27.31',
50
+ description: 'AssemblyScript compiler (asc) and JIT/AOT runtime runner (asrun / asnode)',
51
+ details: 'AssemblyScript compiles a strict variant of TypeScript to WebAssembly. Includes `asc` (ahead-of-time compiler to .wasm/.wat) and `asrun` / `asnode`.',
52
+ homepage: 'https://www.assemblyscript.org',
53
+ cdnUrl: 'https://esm.sh/assemblyscript@0.27.31/asc',
54
+ type: 'generic-runtime',
55
+ repl: { prompt: 'as> ', evalFlag: '-e' },
56
+ size: '1.4 MB'
57
+ },
58
+ jq: {
59
+ name: 'jq',
60
+ bin: 'jq',
61
+ aliases: [],
62
+ version: '1.7.1',
63
+ description: 'Command-line JSON processor compiled to WebAssembly (jq-web)',
64
+ details: 'jq is like sed for JSON data — you can use it to slice, filter, map, and transform structured JSON data from files or piped standard input.',
65
+ homepage: 'https://jqlang.github.io/jq/',
66
+ cdnUrl: 'https://esm.sh/jq-web@0.5.3',
67
+ type: 'generic-runtime',
68
+ size: '620 KB'
69
+ },
70
+ python3: {
71
+ name: 'python3',
72
+ bin: 'python3',
73
+ aliases: ['python', 'py'],
74
+ version: '3.12.1',
75
+ description: 'CPython 3.12 compiled to WebAssembly (via Pyodide)',
76
+ details: 'Full Python 3.12 runtime in WebAssembly powered by Pyodide. Supports interactive Python REPL (`>>>`), running `.py` scripts from the brsh filesystem, `-c` inline code evaluation, and piped standard input.',
77
+ homepage: 'https://pyodide.org',
78
+ cdnUrl: 'https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.mjs',
79
+ indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.26.4/full/',
80
+ type: 'generic-runtime',
81
+ repl: { prompt: '>>> ', evalFlag: '-c' },
82
+ size: '6.4 MB'
83
+ },
84
+ duckdb: {
85
+ name: 'duckdb',
86
+ bin: 'duckdb',
87
+ aliases: [],
88
+ version: '1.29.0',
89
+ description: 'In-process analytical SQL OLAP database compiled to WebAssembly',
90
+ details: 'DuckDB-WASM executes analytical SQL queries directly in WebAssembly, including querying CSV and JSON files stored in the brsh filesystem, interactive SQL shell, and one-shot / piped queries.',
91
+ homepage: 'https://duckdb.org',
92
+ cdnUrl: 'https://esm.sh/@duckdb/duckdb-wasm@1.29.0',
93
+ type: 'generic-runtime',
94
+ repl: { prompt: 'D ', continuePrompt: ' > ', evalFlag: '-c' },
95
+ size: '4.2 MB'
96
+ },
97
+ graphviz: {
98
+ name: 'graphviz',
99
+ bin: 'dot',
100
+ aliases: ['graphviz'],
101
+ version: '1.13.0',
102
+ description: 'Graphviz graph visualization compiler (`dot`) compiled to WebAssembly',
103
+ details: 'Powered by @hpcc-js/wasm-graphviz. Compiles DOT language graph descriptions (`.dot` / `.gv`) into SVG, DOT, canon, or JSON formats (`dot -Tsvg input.dot -o output.svg`).',
104
+ homepage: 'https://graphviz.org',
105
+ cdnUrl: 'https://esm.sh/@hpcc-js/wasm-graphviz@1.13.0',
106
+ type: 'generic-runtime',
107
+ size: '1.1 MB'
108
+ },
109
+ ffmpeg: {
110
+ name: 'ffmpeg',
111
+ bin: 'ffmpeg',
112
+ aliases: [],
113
+ version: '0.12.10',
114
+ description: 'FFmpeg multimedia framework compiled to WebAssembly (@ffmpeg/ffmpeg)',
115
+ details: 'Record, convert, transcode, and inspect audio, video, and image files directly inside the brsh filesystem using WebAssembly (`ffmpeg -i input.mp4 output.webm`).',
116
+ homepage: 'https://ffmpegwasm.netlify.app',
117
+ cdnUrl: 'https://esm.sh/@ffmpeg/ffmpeg@0.12.10',
118
+ coreUrl: 'https://unpkg.com/@ffmpeg/core@0.12.6/dist/esm/ffmpeg-core.js',
119
+ type: 'generic-runtime',
120
+ size: '8.5 MB'
121
+ },
122
+ wabt: {
123
+ name: 'wabt',
124
+ bin: 'wat2wasm',
125
+ aliases: ['wasm2wat'],
126
+ version: '1.0.36',
127
+ description: 'WebAssembly Binary Toolkit (wat2wasm & wasm2wat)',
128
+ details: 'WABT provides tools for translating between WebAssembly Text Format (.wat) and the WebAssembly binary format (.wasm), as well as inspecting WASM modules.',
129
+ homepage: 'https://github.com/WebAssembly/wabt',
130
+ cdnUrl: 'https://esm.sh/wabt@1.0.36',
131
+ type: 'generic-runtime',
132
+ size: '540 KB'
133
+ },
134
+ quickjs: {
135
+ name: 'quickjs',
136
+ bin: 'qjs',
137
+ aliases: ['quickjs'],
138
+ version: '0.31.0',
139
+ description: 'Sandboxed QuickJS JavaScript engine compiled to WebAssembly',
140
+ details: 'QuickJS is a small and embeddable Javascript engine supporting ES2023. Runs JS code and files inside an isolated WebAssembly sandbox.',
141
+ homepage: 'https://bellard.org/quickjs/',
142
+ cdnUrl: 'https://esm.sh/quickjs-emscripten@0.31.0',
143
+ type: 'generic-runtime',
144
+ repl: { prompt: 'qjs > ', evalFlag: '-e' },
145
+ size: '820 KB'
146
+ },
147
+ lua: {
148
+ name: 'lua',
149
+ bin: 'lua',
150
+ aliases: [],
151
+ version: '5.4.6',
152
+ description: 'Lua 5.4 interpreter compiled to WebAssembly (via wasmoon)',
153
+ details: 'Full Lua 5.4 virtual machine compiled to WebAssembly. Supports interactive REPL, script execution from the brsh filesystem, and `-e` one-liners.',
154
+ homepage: 'https://www.lua.org',
155
+ cdnUrl: 'https://esm.sh/wasmoon@1.16.0',
156
+ type: 'generic-runtime',
157
+ repl: { prompt: 'lua> ', evalFlag: '-e' },
158
+ size: '410 KB'
159
+ }
160
+ };
161
+
162
+ // Map package aliases (e.g. `wbt install sqlite` -> `sqlite3`, `wbt install dot` -> `graphviz`)
163
+ const PACKAGE_ALIASES = {
164
+ sqlite: 'sqlite3',
165
+ 'sqlite-wasm': 'sqlite3',
166
+ psql: 'pglite',
167
+ postgres: 'pglite',
168
+ asc: 'assemblyscript',
169
+ asrun: 'assemblyscript',
170
+ asnode: 'assemblyscript',
171
+ python: 'python3',
172
+ py: 'python3',
173
+ pyodide: 'python3',
174
+ dot: 'graphviz',
175
+ wat2wasm: 'wabt',
176
+ wasm2wat: 'wabt',
177
+ qjs: 'quickjs'
178
+ };
179
+
180
+ function resolvePackageName(name) {
181
+ if (!name) return null;
182
+ const lower = name.toLowerCase();
183
+ return PACKAGE_ALIASES[lower] || lower;
184
+ }
185
+
186
+ module.exports = {
187
+ DEFAULT_REGISTRY,
188
+ PACKAGE_ALIASES,
189
+ resolvePackageName
190
+ };
@@ -0,0 +1,118 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Formats query result rows into a clean ASCII table (similar to psql / sqlite3 -table).
5
+ *
6
+ * @param {string[]} columns
7
+ * @param {Array<Object|Array>} rows
8
+ * @param {Object} [options]
9
+ * @param {boolean} [options.showRowCount=true]
10
+ * @returns {string[]} Array of lines
11
+ */
12
+ function formatTable(columns, rows, options = {}) {
13
+ const { showRowCount = true } = options;
14
+
15
+ if (!columns || columns.length === 0) {
16
+ return [];
17
+ }
18
+
19
+ const colNames = columns.map(c => String(c));
20
+ const widths = colNames.map(c => c.length);
21
+
22
+ const normalizedRows = (rows || []).map(row => {
23
+ return colNames.map((col, idx) => {
24
+ const val = Array.isArray(row) ? row[idx] : row[col];
25
+ const str = val === null || val === undefined ? 'NULL' : String(val);
26
+ if (str.length > widths[idx]) {
27
+ widths[idx] = str.length;
28
+ }
29
+ return str;
30
+ });
31
+ });
32
+
33
+ const lines = [];
34
+ const header = colNames.map((col, i) => ' ' + col.padEnd(widths[i]) + ' ').join('|');
35
+ const separator = widths.map(w => '-'.repeat(w + 2)).join('+');
36
+
37
+ lines.push(header);
38
+ lines.push(separator);
39
+
40
+ for (const r of normalizedRows) {
41
+ lines.push(r.map((cell, i) => ' ' + cell.padEnd(widths[i]) + ' ').join('|'));
42
+ }
43
+
44
+ if (showRowCount) {
45
+ lines.push(`(${normalizedRows.length} row${normalizedRows.length === 1 ? '' : 's'})`);
46
+ }
47
+
48
+ return lines;
49
+ }
50
+
51
+ /**
52
+ * Formats rows in pipe-separated list mode (default sqlite3 style).
53
+ */
54
+ function formatPipeList(columns, rows, showHeader = false) {
55
+ const lines = [];
56
+ const colNames = (columns || []).map(c => String(c));
57
+ if (showHeader && colNames.length > 0) {
58
+ lines.push(colNames.join('|'));
59
+ }
60
+ for (const row of (rows || [])) {
61
+ const vals = colNames.map((col, idx) => {
62
+ const val = Array.isArray(row) ? row[idx] : row[col];
63
+ return val === null || val === undefined ? '' : String(val);
64
+ });
65
+ lines.push(vals.join('|'));
66
+ }
67
+ return lines;
68
+ }
69
+
70
+ /**
71
+ * Formats rows as CSV.
72
+ */
73
+ function formatCsv(columns, rows, showHeader = true) {
74
+ const escapeCsv = (val) => {
75
+ const str = val === null || val === undefined ? '' : String(val);
76
+ if (/[",\r\n]/.test(str)) {
77
+ return '"' + str.replace(/"/g, '""') + '"';
78
+ }
79
+ return str;
80
+ };
81
+
82
+ const lines = [];
83
+ const colNames = (columns || []).map(c => String(c));
84
+ if (showHeader && colNames.length > 0) {
85
+ lines.push(colNames.map(escapeCsv).join(','));
86
+ }
87
+ for (const row of (rows || [])) {
88
+ const vals = colNames.map((col, idx) => {
89
+ const val = Array.isArray(row) ? row[idx] : row[col];
90
+ return escapeCsv(val);
91
+ });
92
+ lines.push(vals.join(','));
93
+ }
94
+ return lines;
95
+ }
96
+
97
+ const {
98
+ readBytesFromFs,
99
+ writeBytesToFs,
100
+ loadModule,
101
+ extractHelpFromText,
102
+ inspectWasmBytes,
103
+ formatWasmHelp
104
+ } = require('../WasmCommand');
105
+
106
+ module.exports = {
107
+ formatTable,
108
+ formatPipeList,
109
+ formatCsv,
110
+ readBytesFromFs,
111
+ writeBytesToFs,
112
+ loadModule,
113
+ extractHelpFromText,
114
+ inspectWasmBytes,
115
+ formatWasmHelp
116
+ };
117
+
118
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "2.5.6",
3
+ "version": "2.7.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",
@@ -14,6 +14,11 @@
14
14
  "import": "./dist/terminal.es.js",
15
15
  "require": "./dist/terminal.min.js",
16
16
  "default": "./dist/terminal.min.js"
17
+ },
18
+ "./wbt": {
19
+ "import": "./dist/wbt.es.js",
20
+ "require": "./lib/wbt/index.js",
21
+ "default": "./dist/wbt.min.js"
17
22
  }
18
23
  },
19
24
  "bin": {
@@ -24,10 +29,12 @@
24
29
  "start": "node bin/exportFileSystem.js ./demo/filesystem -o ./demo/fs.js -v fs && vite --config vite.config.js demo/",
25
30
  "build:demofs": "node bin/exportFileSystem.js ./demo/filesystem -o ./dist-demo/fs.js -v fs",
26
31
  "build:demo": "vite build --config vite.config.demo.js && npm run build:demofs",
27
- "build": "npm run build:shell && npm run build:terminal",
32
+ "build": "npm run build:shell && npm run build:terminal && npm run build:wbt",
28
33
  "build:shell": "vite build --config vite.config.shell.js",
29
34
  "build:terminal": "vite build --config vite.config.terminal.js",
35
+ "build:wbt": "vite build --config vite.config.wbt.js",
30
36
  "shell": "node bin/brsh-shell.js",
37
+ "demo:shell": "node bin/brsh-shell.js --demo",
31
38
  "test": "vitest run",
32
39
  "test:watch": "vitest",
33
40
  "prepublishOnly": "npm run build"
@@ -3,6 +3,7 @@ import { describe, it, expect } from 'vitest';
3
3
  import { createShell, run } from './helpers.js';
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
+ const Shell = require('../index.js');
6
7
  const FileSystem = require('../lib/FileSystem.js');
7
8
  const { BinaryFile, SymlinkRef } = require('../lib/FileSystem.js');
8
9
 
@@ -172,3 +173,250 @@ describe('FileSystem virtual symlinks', () => {
172
173
  expect(output.join('')).toBe('symlinked content');
173
174
  });
174
175
  });
176
+
177
+ describe('BRFS Indexed Binary Container & Client-Side Persistence', () => {
178
+ const {
179
+ isBinaryContainer,
180
+ serializeBinaryFilesystem,
181
+ deserializeBinaryFilesystem,
182
+ FilesystemStorage
183
+ } = require('../lib/BinaryContainer.js');
184
+
185
+ it('serializes text files, binary files, directories, symlinks, and permissions without base64 bloat', () => {
186
+ const rawPngBytes = new Uint8Array(Buffer.from(RED_PNG_B64, 'base64'));
187
+ const fs = new FileSystem('/', {
188
+ readme: 'Hello BRFS!',
189
+ img: RED_PNG_DATA_URI,
190
+ bin: {
191
+ 'script.sh': '#!/sh.js\necho "from container"'
192
+ }
193
+ }, {
194
+ '/readme': 0o644,
195
+ '/bin/script.sh': 0o755
196
+ });
197
+ fs.createSymlink('/readme', '/readme-link');
198
+
199
+ const containerBytes = fs.toBinaryContainer();
200
+ expect(containerBytes instanceof Uint8Array).toBe(true);
201
+ expect(isBinaryContainer(containerBytes)).toBe(true);
202
+ // Header magic "BRFS"
203
+ expect(String.fromCharCode(...containerBytes.subarray(0, 4))).toBe('BRFS');
204
+
205
+ // Deserialize back into a fresh FileSystem
206
+ const restored = new FileSystem('/', containerBytes);
207
+ expect(restored.getFileByPath('/readme')).toBe('Hello BRFS!');
208
+ expect(restored.getMode('/bin/script.sh')).toBe(0o755);
209
+ expect(restored.isSymlink('/readme-link')).toBe(true);
210
+ expect(restored.getFileByPath('/readme-link')).toBe('Hello BRFS!');
211
+
212
+ const restoredImg = restored.getFileByPath('/img');
213
+ expect(restoredImg instanceof BinaryFile).toBe(true);
214
+ expect(restoredImg.length).toBe(rawPngBytes.length);
215
+ expect(restoredImg.toString()).toBe(RED_PNG_DATA_URI);
216
+ });
217
+
218
+ it('boots a Shell directly from a serialized BRFS Uint8Array container and preserves executable permissions', async () => {
219
+ const shell1 = await createShell({
220
+ filesystem: {
221
+ home: {
222
+ 'hello.sh': '#!/sh.js\necho "persisted script works"',
223
+ 'notes.txt': 'initial note'
224
+ }
225
+ },
226
+ permissions: {
227
+ '/home/hello.sh': 0o755
228
+ }
229
+ });
230
+
231
+ await run(shell1, 'echo "updated note" > /home/notes.txt');
232
+ await run(shell1, 'ln -s /home/notes.txt /home/link.txt');
233
+
234
+ // Save snapshot using FilesystemStorage.save()
235
+ const snapshotBytes = await FilesystemStorage.save(shell1);
236
+ expect(isBinaryContainer(snapshotBytes)).toBe(true);
237
+
238
+ // Restore into a brand-new Shell instance by passing snapshotBytes as `filesystem`
239
+ const shell2 = await createShell({
240
+ filesystem: snapshotBytes
241
+ });
242
+
243
+ const noteRes = await run(shell2, 'cat /home/link.txt');
244
+ expect(noteRes.output.join('')).toBe('updated note');
245
+
246
+ const scriptRes = await run(shell2, '/home/hello.sh');
247
+ expect(scriptRes.exitCode).toBe(0);
248
+ expect(scriptRes.output).toContain('persisted script works');
249
+ });
250
+
251
+ it('supports createAutoSave onFsChange hook emitting binary snapshots', async () => {
252
+ const snapshots = [];
253
+ const onFsChange = FilesystemStorage.createAutoSave('test-key', (bytes) => {
254
+ snapshots.push(bytes);
255
+ });
256
+
257
+ const shell = await createShell({
258
+ filesystem: { home: {} },
259
+ onFsChange
260
+ });
261
+
262
+ await run(shell, 'echo "hello auto-save" > /home/auto.txt');
263
+ // Wait a microtask tick for debounced _triggerChange
264
+ await new Promise(r => setTimeout(r, 10));
265
+
266
+ expect(snapshots.length).toBeGreaterThan(0);
267
+ const latest = snapshots[snapshots.length - 1];
268
+ expect(isBinaryContainer(latest)).toBe(true);
269
+
270
+ const decoded = deserializeBinaryFilesystem(latest);
271
+ expect(decoded.filesystem.home['auto.txt']).toBe('hello auto-save');
272
+ });
273
+
274
+ it('accepts a URL string directly in new Shell({ filesystem: "/fs.brfs" }) without a JS loader', async () => {
275
+ const containerBytes = serializeBinaryFilesystem(
276
+ {
277
+ home: {
278
+ '.profile': '#!/sh.js\nexport FROM_PROFILE="loaded"',
279
+ 'greeting.txt': 'hello from url brfs'
280
+ }
281
+ },
282
+ {
283
+ '/home/greeting.txt': 0o640
284
+ }
285
+ );
286
+
287
+ const origFetch = global.fetch;
288
+ global.fetch = async (url) => {
289
+ if (url === 'https://example.test/fs.brfs' || url === '/fs.brfs') {
290
+ return {
291
+ ok: true,
292
+ status: 200,
293
+ arrayBuffer: async () => containerBytes.buffer.slice(
294
+ containerBytes.byteOffset,
295
+ containerBytes.byteOffset + containerBytes.byteLength
296
+ )
297
+ };
298
+ }
299
+ throw new Error(`Unexpected URL: ${url}`);
300
+ };
301
+
302
+ try {
303
+ class ExtraCmd extends Shell.Command {
304
+ static get name() { return 'extracmd'; }
305
+ get name() { return 'extracmd'; }
306
+ run() {
307
+ this.stdOut = 'extra command works';
308
+ }
309
+ }
310
+
311
+ const shell = new Shell({
312
+ filesystem: '/fs.brfs',
313
+ cwd: '/home',
314
+ profile: '/home/.profile'
315
+ });
316
+ // Register a command synchronously while /fs.brfs is still being fetched
317
+ shell.context.setCommand(ExtraCmd);
318
+
319
+ // Commands called immediately automatically wait for /fs.brfs to finish mounting
320
+ const catRes = await run(shell, 'cat greeting.txt');
321
+ expect(catRes.exitCode).toBe(0);
322
+ expect(catRes.output.join('')).toBe('hello from url brfs');
323
+
324
+ const envRes = await run(shell, 'echo $FROM_PROFILE');
325
+ expect(envRes.output.join('')).toBe('loaded');
326
+
327
+ const cmdRes = await run(shell, 'extracmd');
328
+ expect(cmdRes.exitCode).toBe(0);
329
+ expect(cmdRes.output.join('')).toBe('extra command works');
330
+
331
+ expect(shell.context.fs.getMode('/home/greeting.txt')).toBe(0o640);
332
+ } finally {
333
+ global.fetch = origFetch;
334
+ }
335
+ });
336
+
337
+ it('accepts a Promise (such as Shell.Storage.loadOrFetch) or gzipped .brfs bytes directly', async () => {
338
+ const zlib = require('zlib');
339
+ const containerBytes = serializeBinaryFilesystem(
340
+ { data: { 'msg.txt': 'compressed brfs works' } },
341
+ { '/data/msg.txt': 0o600 }
342
+ );
343
+ const gzippedBytes = new Uint8Array(zlib.gzipSync(Buffer.from(containerBytes)));
344
+
345
+ const shell = new Shell({
346
+ filesystem: FilesystemStorage.loadOrFetch('non-existent-key', Promise.resolve(gzippedBytes)),
347
+ cwd: '/data'
348
+ });
349
+
350
+ const res = await run(shell, 'cat msg.txt');
351
+ expect(res.exitCode).toBe(0);
352
+ expect(res.output.join('')).toBe('compressed brfs works');
353
+ expect(shell.context.fs.getMode('/data/msg.txt')).toBe(0o600);
354
+ });
355
+
356
+ it('persists and restores from IndexedDB via FilesystemStorage.save / load / loadOrFetch', async () => {
357
+ // Minimal in-memory IndexedDB mock
358
+ const stores = new Map();
359
+ const origIdb = global.indexedDB;
360
+ global.indexedDB = {
361
+ open(_dbName, _version) {
362
+ const req = {};
363
+ setTimeout(() => {
364
+ if (!stores.has('snapshots')) {
365
+ stores.set('snapshots', new Map());
366
+ if (req.onupgradeneeded) {
367
+ req.result = { createObjectStore: (name) => stores.set(name, new Map()) };
368
+ req.onupgradeneeded();
369
+ }
370
+ }
371
+ req.result = {
372
+ createObjectStore: (name) => stores.set(name, new Map()),
373
+ transaction: (storeName) => {
374
+ const tx = {
375
+ objectStore: () => ({
376
+ put: (val, key) => {
377
+ stores.get(storeName).set(key, val);
378
+ setTimeout(() => tx.oncomplete && tx.oncomplete(), 0);
379
+ },
380
+ get: (key) => {
381
+ const getReq = {};
382
+ setTimeout(() => {
383
+ getReq.result = stores.get(storeName).get(key);
384
+ if (getReq.onsuccess) getReq.onsuccess();
385
+ }, 0);
386
+ return getReq;
387
+ }
388
+ }),
389
+ close: () => {}
390
+ };
391
+ return tx;
392
+ },
393
+ close: () => {}
394
+ };
395
+ if (req.onsuccess) req.onsuccess();
396
+ }, 0);
397
+ return req;
398
+ }
399
+ };
400
+
401
+ try {
402
+ const shell1 = await createShell({
403
+ filesystem: { home: { 'idb.txt': 'saved in indexeddb' } },
404
+ permissions: { '/home/idb.txt': 0o640 }
405
+ });
406
+ await FilesystemStorage.save(shell1, 'idb-test-key');
407
+
408
+ // Verify loadOrFetch prefers the IndexedDB snapshot over fallback
409
+ const shell2 = new Shell({
410
+ filesystem: FilesystemStorage.loadOrFetch('idb-test-key', { home: { 'idb.txt': 'fallback' } }),
411
+ cwd: '/home'
412
+ });
413
+ const res = await run(shell2, 'cat idb.txt');
414
+ expect(res.exitCode).toBe(0);
415
+ expect(res.output.join('')).toBe('saved in indexeddb');
416
+ expect(shell2.context.fs.getMode('/home/idb.txt')).toBe(0o640);
417
+ } finally {
418
+ global.indexedDB = origIdb;
419
+ }
420
+ });
421
+ });
422
+