brsh 3.8.1 → 3.10.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.
@@ -36,23 +36,59 @@ const FDFLAGS_SYNC = 1 << 4;
36
36
 
37
37
  class WasmCommand extends ScriptCommand {
38
38
  // this.script = filepath (set by ScriptCommand parent constructor)
39
+ constructor(script, args, context) {
40
+ super(script, args, context);
41
+ this._ensurePkgMeta();
42
+ }
43
+
44
+ _ensurePkgMeta() {
45
+ if (this._pkgMeta === undefined && this.script) {
46
+ const fs = (this.context && this.context.fs) || this.fs;
47
+ if (fs) {
48
+ this._pkgMeta = readSiblingPkgMeta(fs, this.script);
49
+ }
50
+ }
51
+ return this._pkgMeta || null;
52
+ }
39
53
 
40
- get name() { return 'wasm'; }
54
+ get name() {
55
+ const meta = this._ensurePkgMeta();
56
+ if (meta && meta.bin) return String(meta.bin).toLowerCase();
57
+ if (this.script) return this.script.split('/').pop().replace(/\.(wasm|wat)$/i, '').toLowerCase();
58
+ return 'wasm';
59
+ }
41
60
  get requiresFilesystem() { return true; }
42
61
 
43
62
  get interactive() {
44
63
  const isHelpOrVersion = (this.arguments || []).some(a => a === '--help' || a === '-h' || a === '--version' || a === '-V' || a === '-v');
45
64
  if (isHelpOrVersion) return false;
46
65
  if (this._isInteractive !== undefined) return Boolean(this._isInteractive);
47
- if (this._pkgMeta && this._pkgMeta.interactive !== undefined) return Boolean(this._pkgMeta.interactive);
48
- const name = (this.script || this.name || '').toLowerCase();
49
- return name === 'nano' || name.endsWith('/nano') || name.endsWith('nano.wasm');
66
+ const meta = this._ensurePkgMeta();
67
+ if (meta && (meta.interactive || meta.wasm?.interactive)) return true;
68
+ if (this._inspectedWasm && this._inspectedWasm.isInteractive) return true;
69
+ return false;
50
70
  }
51
71
 
52
72
  get captureInput() {
53
73
  return this.interactive;
54
74
  }
55
75
 
76
+ kill(signal = 'SIGINT') {
77
+ this._killed = true;
78
+ this.exitCode = 130;
79
+ this._exitAltScreen();
80
+ if (this._asyncifyReject) {
81
+ try { this._asyncifyReject(new Error('Interrupted by SIGINT')); } catch (_) {}
82
+ this._asyncifyReject = null;
83
+ }
84
+ if (this._pendingReadResolve) {
85
+ const r = this._pendingReadResolve;
86
+ this._pendingReadResolve = null;
87
+ try { r(); } catch (_) {}
88
+ }
89
+ super.kill(signal);
90
+ }
91
+
56
92
  _enterAltScreen() {
57
93
  if (this._inAltScreen) return;
58
94
  this._inAltScreen = true;
@@ -135,7 +171,15 @@ class WasmCommand extends ScriptCommand {
135
171
  const nodeFs = (() => { try { return require('fs'); } catch { return null; } })();
136
172
 
137
173
  return this._loadBytes(filepath, nodeFs)
138
- .then(({ bytes, isWat }) => isWat ? this._runWat(bytes) : this._runWasm(bytes))
174
+ .then(({ bytes, isWat }) => {
175
+ if (this.interactive) {
176
+ this.emit('interactive');
177
+ if (this.context && typeof this.context.emit === 'function') {
178
+ this.context.emit('interactive');
179
+ }
180
+ }
181
+ return isWat ? this._runWat(bytes) : this._runWasm(bytes);
182
+ })
139
183
  .catch(e => {
140
184
  this.stdErr = e.message || String(e);
141
185
  this.exitCode = 1;
@@ -145,19 +189,30 @@ class WasmCommand extends ScriptCommand {
145
189
  _loadBytes(filepath, nodeFs) {
146
190
  const fs = (this.context && this.context.fs) || this.fs;
147
191
  if (!fs) return Promise.reject(new Error(`${filepath}: Filesystem is not available`));
192
+ let p;
148
193
  if (fs.isRealFilesystem && nodeFs) {
149
194
  try {
150
195
  const buf = nodeFs.readFileSync(fs.absolutePath(filepath));
151
196
  const bytes = new Uint8Array(buf);
152
- return Promise.resolve({ bytes, isWat: this._isWat(filepath, bytes) });
197
+ p = Promise.resolve({ bytes, isWat: this._isWat(filepath, bytes) });
153
198
  } catch(e) {
154
199
  return Promise.reject(new Error(`${filepath}: ${e.message}`));
155
200
  }
201
+ } else {
202
+ const content = fs.getFileByPath(filepath);
203
+ if (content == null) return Promise.reject(new Error(`${filepath}: No such file or directory`));
204
+ const bytes = this._contentToBytes(content);
205
+ p = Promise.resolve({ bytes, isWat: this._isWat(filepath, bytes) });
156
206
  }
157
- const content = fs.getFileByPath(filepath);
158
- if (content == null) return Promise.reject(new Error(`${filepath}: No such file or directory`));
159
- const bytes = this._contentToBytes(content);
160
- return Promise.resolve({ bytes, isWat: this._isWat(filepath, bytes) });
207
+ return p.then(res => {
208
+ if (!res.isWat && res.bytes) {
209
+ this._inspectedWasm = inspectWasmBytes(res.bytes);
210
+ if (this._inspectedWasm.isInteractive) {
211
+ this._isInteractive = true;
212
+ }
213
+ }
214
+ return res;
215
+ });
161
216
  }
162
217
 
163
218
  _isWat(filepath, bytes) {
@@ -231,10 +286,23 @@ class WasmCommand extends ScriptCommand {
231
286
  this.interactive && isTtyEnvironment
232
287
  );
233
288
 
289
+ if (isInteractive) {
290
+ this.emit('interactive');
291
+ if (this.context && typeof this.context.emit === 'function') {
292
+ this.context.emit('interactive');
293
+ }
294
+ }
295
+
234
296
  const promoteToInteractive = () => {
235
297
  if (isInteractive || !isTtyEnvironment) return;
236
298
  isInteractive = true;
237
299
  this._isInteractive = true;
300
+ this.emit('interactive');
301
+ if (this.context && typeof this.context.emit === 'function') {
302
+ this.context.emit('interactive');
303
+ }
304
+
305
+ this._enterAltScreen();
238
306
 
239
307
  if (outBuf[1]) {
240
308
  if (this.stdout && typeof this.stdout.write === 'function') this.stdout.write(outBuf[1]);
@@ -545,8 +613,10 @@ class WasmCommand extends ScriptCommand {
545
613
  }
546
614
 
547
615
  instance.exports.asyncify_start_unwind(asyncifyDataAddr);
548
- asyncifyPromise = new Promise(resolve => {
616
+ asyncifyPromise = new Promise((resolve, reject) => {
549
617
  pendingReadResolve = resolve;
618
+ this._pendingReadResolve = resolve;
619
+ this._asyncifyReject = reject;
550
620
  });
551
621
  view.setUint32(nread_ptr, 0, true);
552
622
  return ERRNO_SUCCESS;
@@ -800,13 +870,21 @@ class WasmCommand extends ScriptCommand {
800
870
  new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
801
871
  return ERRNO_SUCCESS;
802
872
  }
803
- if (cleanPath === '/dev/tty') {
873
+ if (cleanPath === '/dev/tty' || cleanPath === '/dev/stdin') {
804
874
  promoteToInteractive();
805
875
  const newFd = nextFd++;
806
- fdTable.set(newFd, { type: 'dev_tty', path: '/dev/tty' });
876
+ fdTable.set(newFd, { type: 'dev_tty', path: cleanPath });
807
877
  new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
808
878
  return ERRNO_SUCCESS;
809
879
  }
880
+ if (cleanPath === '/dev/stdout') {
881
+ new DataView(memRef.buffer).setUint32(opened_fd_ptr, 1, true);
882
+ return ERRNO_SUCCESS;
883
+ }
884
+ if (cleanPath === '/dev/stderr') {
885
+ new DataView(memRef.buffer).setUint32(opened_fd_ptr, 2, true);
886
+ return ERRNO_SUCCESS;
887
+ }
810
888
 
811
889
  const st = fs.stat(absPath);
812
890
  const exists = st !== null;
@@ -861,14 +939,14 @@ class WasmCommand extends ScriptCommand {
861
939
  const absPath = resolveGuestPath(dirfd, relPath);
862
940
  if (!absPath) return ERRNO_BADF;
863
941
  const cleanPath = absPath.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
864
- if (cleanPath === '/dev/null' || cleanPath === '/dev/zero' || cleanPath === '/dev/urandom' || cleanPath === '/dev/random' || cleanPath === '/dev/tty') {
942
+ const st = fs.stat(absPath);
943
+ if (cleanPath === '/dev/null' || cleanPath === '/dev/zero' || cleanPath === '/dev/urandom' || cleanPath === '/dev/random' || cleanPath === '/dev/tty' || cleanPath === '/dev/stdin' || cleanPath === '/dev/stdout' || cleanPath === '/dev/stderr' || (st && (st.isDevice || st.isCharacterDevice))) {
865
944
  const view = new DataView(memRef.buffer);
866
945
  for (let i = 0; i < 64; i++) view.setUint8(buf_ptr + i, 0);
867
946
  view.setUint8(buf_ptr + 16, FILETYPE_CHARACTER_DEVICE);
868
947
  view.setBigUint64(buf_ptr + 24, 1n, true);
869
948
  return ERRNO_SUCCESS;
870
949
  }
871
- const st = fs.stat(absPath);
872
950
  if (!st) return ERRNO_NOENT;
873
951
  const view = new DataView(memRef.buffer);
874
952
  for (let i = 0; i < 64; i++) view.setUint8(buf_ptr + i, 0);
@@ -882,6 +960,7 @@ class WasmCommand extends ScriptCommand {
882
960
  const relPath = decoder.decode(new Uint8Array(memRef.buffer, path_ptr, path_len));
883
961
  const absPath = resolveGuestPath(dirfd, relPath);
884
962
  if (!absPath) return ERRNO_BADF;
963
+ if (fs.exists(absPath)) return ERRNO_EXIST;
885
964
  try {
886
965
  fs.setFileByPath(absPath, {}, true);
887
966
  return ERRNO_SUCCESS;
@@ -1123,17 +1202,23 @@ class WasmCommand extends ScriptCommand {
1123
1202
  }
1124
1203
 
1125
1204
  instance.exports.asyncify_start_unwind(asyncifyDataAddr);
1126
- asyncifyPromise = new Promise(resolve => {
1205
+ asyncifyPromise = new Promise((resolve, reject) => {
1127
1206
  let timer = null;
1207
+ this._asyncifyReject = reject;
1128
1208
  const onKey = () => {
1129
1209
  if (timer) clearTimeout(timer);
1130
1210
  pendingReadResolve = null;
1211
+ this._pendingReadResolve = null;
1212
+ this._asyncifyReject = null;
1131
1213
  resolve();
1132
1214
  };
1133
1215
  pendingReadResolve = onKey;
1216
+ this._pendingReadResolve = onKey;
1134
1217
  if (minTimeoutMs !== Infinity) {
1135
1218
  timer = setTimeout(() => {
1136
1219
  pendingReadResolve = null;
1220
+ this._pendingReadResolve = null;
1221
+ this._asyncifyReject = null;
1137
1222
  resolve();
1138
1223
  }, Math.max(1, minTimeoutMs));
1139
1224
  }
@@ -1268,24 +1353,43 @@ class WasmCommand extends ScriptCommand {
1268
1353
  if (res && typeof res.then === 'function') res = await res;
1269
1354
 
1270
1355
  while (hasAsyncify && typeof instance.exports.asyncify_get_state === 'function' && instance.exports.asyncify_get_state() === 1) {
1356
+ if (this._killed) {
1357
+ this.exitCode = 130;
1358
+ break;
1359
+ }
1271
1360
  instance.exports.asyncify_stop_unwind();
1272
1361
  if (asyncifyPromise) {
1273
- await asyncifyPromise;
1362
+ try {
1363
+ await asyncifyPromise;
1364
+ } catch (_) {
1365
+ if (this._killed) {
1366
+ this.exitCode = 130;
1367
+ break;
1368
+ }
1369
+ }
1274
1370
  asyncifyPromise = null;
1275
1371
  }
1372
+ if (this._killed) {
1373
+ this.exitCode = 130;
1374
+ break;
1375
+ }
1276
1376
  instance.exports.asyncify_start_rewind(asyncifyDataAddr);
1277
1377
  res = start();
1278
1378
  if (res && typeof res.then === 'function') res = await res;
1279
1379
  }
1280
1380
  } catch(e) {
1281
- if (!e || !e._wasmExit) {
1381
+ if (this._killed) {
1382
+ this.exitCode = 130;
1383
+ } else if (!e || !e._wasmExit) {
1282
1384
  this.stdErr = `${this.script}: runtime error: ${e?.message || String(e)}`;
1283
1385
  this.exitCode = 1;
1284
1386
  }
1285
1387
  }
1286
1388
  }
1287
1389
  } catch(e) {
1288
- if (!e || !e._wasmExit) {
1390
+ if (this._killed) {
1391
+ this.exitCode = 130;
1392
+ } else if (!e || !e._wasmExit) {
1289
1393
  this.stdErr = `${this.script}: ${e?.message || String(e)}`;
1290
1394
  this.exitCode = 1;
1291
1395
  }
@@ -1320,12 +1424,13 @@ class WasmCommand extends ScriptCommand {
1320
1424
  const args = this.arguments || [];
1321
1425
  const hasOutput = this.result && this.result.getStdOutput && this.result.getStdOutput().length > 0;
1322
1426
  if (!hasOutput && (this.exitCode === 0 || this.exitCode === undefined)) {
1323
- const binLabel = (this.script || 'wasm').split('/').pop();
1427
+ const pkgMeta = this._ensurePkgMeta();
1428
+ const binLabel = (pkgMeta && pkgMeta.bin) || (this.script || 'wasm').split('/').pop();
1324
1429
  const meta = Object.assign({
1325
- name: binLabel,
1326
- version: 'wasi',
1430
+ name: (pkgMeta && pkgMeta.name) || binLabel,
1431
+ version: (pkgMeta && pkgMeta.version) || 'wasi',
1327
1432
  description: `WebAssembly WASI binary (${this.script})`
1328
- }, this._pkgMeta || {});
1433
+ }, pkgMeta || {});
1329
1434
  if (args.includes('--help') || args.includes('-h')) {
1330
1435
  const inspected = inspectWasmBytes(bytes);
1331
1436
  for (const line of formatWasmHelp(binLabel, meta, inspected)) {
@@ -1393,24 +1498,13 @@ function readBytesFromFs(fs, filepath) {
1393
1498
  */
1394
1499
  function writeBytesToFs(fs, filepath, bytes, mimeType = 'application/octet-stream') {
1395
1500
  const uint8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
1501
+ if (fs && fs.isRealFilesystem) {
1502
+ fs.setFileByPath(filepath, uint8, true);
1503
+ return;
1504
+ }
1396
1505
  const copy = new Uint8Array(uint8.byteLength);
1397
1506
  copy.set(uint8);
1398
1507
  const bf = new BinaryFile(copy.buffer, mimeType);
1399
- if (fs.isRealFilesystem) {
1400
- try {
1401
- const nodeFs = require('fs');
1402
- const nodePath = require('path');
1403
- const abs = fs.absolutePath(filepath);
1404
- nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
1405
- nodeFs.writeFileSync(abs, Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
1406
- return;
1407
- } catch {
1408
- if (typeof fs._setFileRaw === 'function') {
1409
- fs._setFileRaw(filepath, bf, true);
1410
- return;
1411
- }
1412
- }
1413
- }
1414
1508
  if (typeof fs._setFileRaw === 'function' && filepath.startsWith('/var/lib/wbt/')) {
1415
1509
  fs._setFileRaw(filepath, bf, true);
1416
1510
  return;
@@ -1507,7 +1601,9 @@ function inspectWasmBytes(bytes) {
1507
1601
  usage: null,
1508
1602
  options: [],
1509
1603
  exports: [],
1510
- wasiImports: []
1604
+ wasiImports: [],
1605
+ hasAsyncify: false,
1606
+ isInteractive: false
1511
1607
  };
1512
1608
  if (!(bytes instanceof Uint8Array) || bytes.length < 8) return info;
1513
1609
 
@@ -1520,6 +1616,11 @@ function inspectWasmBytes(bytes) {
1520
1616
  info.wasiImports = WebAssembly.Module.imports(mod)
1521
1617
  .filter(i => i.module.startsWith('wasi_'))
1522
1618
  .map(i => i.name);
1619
+
1620
+ info.hasAsyncify = info.exports.includes('asyncify_start_unwind') && info.exports.includes('asyncify_stop_unwind');
1621
+ if (info.exports.includes('set_terminal_size')) {
1622
+ info.isInteractive = true;
1623
+ }
1523
1624
  }
1524
1625
  } catch {
1525
1626
  // Ignore if bytes are WAT or non-standard
@@ -1539,7 +1640,14 @@ function inspectWasmBytes(bytes) {
1539
1640
  }
1540
1641
  if (cur.length >= 4) chunks.push(cur);
1541
1642
 
1542
- const parsed = extractHelpFromText(chunks.join('\n'), true);
1643
+ const allText = chunks.join('\n');
1644
+ if (!info.isInteractive) {
1645
+ if (allText.includes('/dev/tty') || allText.includes('\x1b[?1049h') || allText.includes('smcup') || allText.includes('xterm')) {
1646
+ info.isInteractive = true;
1647
+ }
1648
+ }
1649
+
1650
+ const parsed = extractHelpFromText(allText, true);
1543
1651
  info.usage = parsed.usage;
1544
1652
  info.options = parsed.options;
1545
1653
  } catch {
@@ -1631,6 +1739,31 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1631
1739
  get name() { return binName; }
1632
1740
  get requiresFilesystem() { return true; }
1633
1741
 
1742
+ get interactive() {
1743
+ if (this._subCommand) return this._subCommand.interactive;
1744
+ if (this._isInteractive !== undefined) return Boolean(this._isInteractive);
1745
+ if (pkgMeta && (pkgMeta.interactive || pkgMeta.wasm?.interactive)) return true;
1746
+ if (this._inspectedWasm && this._inspectedWasm.isInteractive) return true;
1747
+ return false;
1748
+ }
1749
+
1750
+ get captureInput() {
1751
+ return this.interactive;
1752
+ }
1753
+
1754
+ kill(signal = 'SIGINT') {
1755
+ if (this._subCommand && typeof this._subCommand.kill === 'function') {
1756
+ this._subCommand.kill(signal);
1757
+ }
1758
+ super.kill(signal);
1759
+ }
1760
+
1761
+ onInput(char) {
1762
+ if (this._subCommand && typeof this._subCommand.onInput === 'function') {
1763
+ this._subCommand.onInput(char);
1764
+ }
1765
+ }
1766
+
1634
1767
  async run() {
1635
1768
  const args = [...(this.arguments || [])];
1636
1769
  const isHelp = args.includes('--help') || args.includes('-h');
@@ -1705,7 +1838,7 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1705
1838
  await this._runRawWasmBytes(bytes, args);
1706
1839
  } else if (typeof target === 'function') {
1707
1840
  // 3. Factory / constructor / CLI function (`export default function(opts)` or class)
1708
- await this._runFunctionOrEmscripten(target, args, isHelp);
1841
+ await this._runFunctionOrEmscripten(target, args, isHelp, isVersion);
1709
1842
  } else if (target && typeof target === 'object') {
1710
1843
  // 4. Standard CLI module object (`main`, `run`, `callMain`, `exec`)
1711
1844
  if (target.ready) await target.ready;
@@ -1818,7 +1951,12 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1818
1951
  if (this.stdin !== undefined) {
1819
1952
  wasmCmd.stdin = this.stdin;
1820
1953
  }
1821
- await wasmCmd._runWasm(bytes);
1954
+ this._subCommand = wasmCmd;
1955
+ try {
1956
+ await wasmCmd._runWasm(bytes);
1957
+ } finally {
1958
+ this._subCommand = null;
1959
+ }
1822
1960
  for (const line of wasmCmd.result.getStdOutput()) {
1823
1961
  if (line.type === 'out') this.stdOut = line.string;
1824
1962
  else if (line.type === 'err') this.stdErr = line.string;
@@ -1888,7 +2026,7 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
1888
2026
  };
1889
2027
  }
1890
2028
 
1891
- async _runFunctionOrEmscripten(fn, args, isHelp = false) {
2029
+ async _runFunctionOrEmscripten(fn, args, isHelp = false, isVersion = false) {
1892
2030
  const outLines = [];
1893
2031
  const errLines = [];
1894
2032
  const stdinBytes = new TextEncoder().encode(this.stdin || '');
@@ -2181,6 +2319,38 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
2181
2319
  return GenericWasmCommand;
2182
2320
  }
2183
2321
 
2322
+ function isWasmFile(filepath, content) {
2323
+ if (filepath && (filepath.endsWith('.wasm') || filepath.endsWith('.wat'))) return true;
2324
+ if (content instanceof Uint8Array) {
2325
+ return content.length >= 4 && content[0] === 0x00 && content[1] === 0x61 && content[2] === 0x73 && content[3] === 0x6d;
2326
+ }
2327
+ if (typeof content !== 'string') return false;
2328
+ // Binary WASM: magic bytes \0asm
2329
+ if (content.charCodeAt(0) === 0 && content.slice(1, 4) === 'asm') return true;
2330
+ // WAT text format
2331
+ return content.trimStart().startsWith('(module');
2332
+ }
2333
+
2334
+ function readSiblingPkgMeta(fs, filepath) {
2335
+ if (!fs || !filepath || typeof fs.exists !== 'function' || typeof fs.getFileByPath !== 'function') {
2336
+ return null;
2337
+ }
2338
+ try {
2339
+ const dirParts = filepath.split('/').filter(Boolean);
2340
+ dirParts.pop();
2341
+ const pkgJsonPath = (dirParts.length ? '/' + dirParts.join('/') : '') + '/package.json';
2342
+ if (fs.exists(pkgJsonPath)) {
2343
+ const rawJson = fs.getFileByPath(pkgJsonPath);
2344
+ if (typeof rawJson === 'string') {
2345
+ return JSON.parse(rawJson);
2346
+ }
2347
+ }
2348
+ } catch (_) {}
2349
+ return null;
2350
+ }
2351
+
2352
+ WasmCommand.isWasmFile = isWasmFile;
2353
+ WasmCommand.readSiblingPkgMeta = readSiblingPkgMeta;
2184
2354
  WasmCommand.readBytesFromFs = readBytesFromFs;
2185
2355
  WasmCommand.writeBytesToFs = writeBytesToFs;
2186
2356
  WasmCommand.loadModule = loadModule;
@@ -2191,4 +2361,3 @@ WasmCommand.createGenericWasmCommand = createGenericWasmCommand;
2191
2361
  WasmCommand.createCommand = createGenericWasmCommand;
2192
2362
 
2193
2363
  module.exports = WasmCommand;
2194
-
@@ -2,6 +2,8 @@
2
2
 
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
+ const { SymlinkRef } = require('./BaseFileSystem');
6
+ const isUtf8Text = require('./isUtf8Text');
5
7
 
6
8
  const IGNORE = ['.DS_Store'];
7
9
 
@@ -23,9 +25,13 @@ function _isWasmBuffer(buf) {
23
25
  /**
24
26
  * Recursively builds a filesystem structure object from a real directory.
25
27
  * Returns { filesystem, permissions } where:
26
- * - filesystem is the nested content tree (directories as objects, files as require() strings)
28
+ * - filesystem is the nested content tree (directories as objects, files as strings or BinaryFiles/SymlinkRefs)
27
29
  * - permissions maps virtual absolute paths to Unix mode bits (e.g. { '/bin/script.sh': 0o755 })
28
30
  *
31
+ * Real filenames and extensions (.js, .wasm, etc.) are preserved verbatim.
32
+ * OS symlinks are serialized as SymlinkRef instances.
33
+ * Files are checked for UTF-8/ASCII text content; anything that is not valid text defaults to binary.
34
+ *
29
35
  * Throws if `root` cannot be read.
30
36
  */
31
37
  function buildStructure(root) {
@@ -42,42 +48,50 @@ function _buildTree(root, virtualPrefix, permissions) {
42
48
  return structure;
43
49
  }
44
50
  try {
45
- const stat = fs.lstatSync(path.join(root, handle));
51
+ const filePath = path.join(root, handle);
52
+ const stat = fs.lstatSync(filePath);
53
+
54
+ if(stat.isSymbolicLink()) {
55
+ const target = fs.readlinkSync(filePath);
56
+ structure[handle] = new SymlinkRef(target);
57
+ permissions[virtualPrefix + '/' + handle] = stat.mode & 0o777;
58
+ return structure;
59
+ }
60
+
46
61
  if(stat.isDirectory()) {
47
62
  structure[handle] = _buildTree(
48
- path.join(root, handle),
63
+ filePath,
49
64
  virtualPrefix + '/' + handle,
50
65
  permissions
51
66
  );
52
67
  return structure;
53
68
  }
54
69
 
55
- const filePath = path.join(root, handle);
56
70
  const isJavaScript = handle.endsWith('.js');
57
71
  const ext = path.extname(handle).toLowerCase();
58
- const rawBuf = isJavaScript ? null : fs.readFileSync(filePath);
59
- const isWasmMagic = rawBuf !== null && _isWasmBuffer(rawBuf);
60
- const isBinary = (ext in BINARY_MIME) || isWasmMagic;
61
- const mime = BINARY_MIME[ext] || (isWasmMagic ? 'application/wasm' : 'application/octet-stream');
62
- const fileContents = isJavaScript
63
- ? null
64
- : isBinary
65
- ? `data:${mime};base64,${rawBuf.toString('base64')}`
66
- : rawBuf.toString('utf8');
72
+ const rawBuf = fs.readFileSync(filePath);
73
+ const isWasmMagic = _isWasmBuffer(rawBuf);
74
+ const isKnownBinary = (ext in BINARY_MIME) || isWasmMagic;
67
75
 
68
- const isWasmExt = ext === '.wasm';
69
- const key = isJavaScript
70
- ? handle.substring(0, handle.length - 3)
71
- : isWasmExt
72
- ? handle.substring(0, handle.length - 5)
73
- : handle;
76
+ let fileContents;
77
+ if (isJavaScript) {
78
+ // Preserved as UTF-8 text string (bundled with esbuild later during export)
79
+ fileContents = rawBuf.toString('utf8');
80
+ } else if (isKnownBinary) {
81
+ const mime = BINARY_MIME[ext] || (isWasmMagic ? 'application/wasm' : 'application/octet-stream');
82
+ fileContents = `data:${mime};base64,${rawBuf.toString('base64')}`;
83
+ } else if (isUtf8Text(rawBuf)) {
84
+ fileContents = rawBuf.toString('utf8');
85
+ } else {
86
+ // Content-based binary fallback for unknown binary formats (.wad, .gguf, ELF, images, etc.)
87
+ const mime = 'application/octet-stream';
88
+ fileContents = `data:${mime};base64,${rawBuf.toString('base64')}`;
89
+ }
74
90
 
75
- structure[key] = isJavaScript
76
- ? `require('${path.resolve(root, handle)}')`
77
- : fileContents;
91
+ structure[handle] = fileContents;
78
92
 
79
93
  // Record real Unix permission bits for this file
80
- permissions[virtualPrefix + '/' + key] = stat.mode & 0o777;
94
+ permissions[virtualPrefix + '/' + handle] = stat.mode & 0o777;
81
95
  } catch(fe) {
82
96
  // Silently skip files/dirs that are inaccessible
83
97
  }
@@ -85,4 +99,4 @@ function _buildTree(root, virtualPrefix, permissions) {
85
99
  }, {});
86
100
  }
87
101
 
88
- module.exports = { buildStructure, IGNORE };
102
+ module.exports = { buildStructure, IGNORE, BINARY_MIME, _isWasmBuffer };
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Checks whether a byte buffer contains valid UTF-8/ASCII text.
5
+ * Returns true if the buffer is text, false if it should be treated as binary.
6
+ *
7
+ * Rules:
8
+ * - Empty buffers are considered valid text.
9
+ * - Checks for NUL bytes (0x00) or non-printable ASCII control characters.
10
+ * Valid text allows tabs (\t, 0x09), line feeds (\n, 0x0A), carriage returns (\r, 0x0D),
11
+ * and ANSI escape sequences (ESC, 0x1B).
12
+ * Characters 0x00-0x08, 0x0B, 0x0C, 0x0E-0x1A, 0x1C-0x1F are treated as binary.
13
+ * - Uses TextDecoder('utf-8', { fatal: true }) to verify strict UTF-8 validity.
14
+ */
15
+ function isUtf8Text(buf) {
16
+ if (!buf || buf.length === 0) return true;
17
+
18
+ const u8 = buf instanceof Uint8Array
19
+ ? buf
20
+ : (typeof Buffer !== 'undefined' && Buffer.isBuffer(buf))
21
+ ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)
22
+ : (buf instanceof ArrayBuffer || ArrayBuffer.isView(buf))
23
+ ? new Uint8Array(buf.buffer || buf, buf.byteOffset || 0, buf.byteLength)
24
+ : null;
25
+
26
+ if (!u8) return false;
27
+
28
+ // Fast check first 8KB (or entire buffer if smaller) for binary control bytes
29
+ const checkLength = Math.min(u8.length, 8192);
30
+ for (let i = 0; i < checkLength; i++) {
31
+ const b = u8[i];
32
+ if (b === 0x00) return false;
33
+ if (b < 0x20 && b !== 0x09 && b !== 0x0A && b !== 0x0D && b !== 0x1B) {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ try {
39
+ new TextDecoder('utf-8', { fatal: true }).decode(u8);
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+
46
+ module.exports = isUtf8Text;
47
+ module.exports.isUtf8Text = isUtf8Text;
@@ -10,13 +10,18 @@ class Which extends LocalCommand {
10
10
  return Promise.reject('which requires a single argument');
11
11
  }
12
12
 
13
- const file = this.context.fs.getFileByPath(`${this.context.getVar('PATH')}/${this.arguments[0]}`);
13
+ const cmdPath = `${this.context.getVar('PATH')}/${this.arguments[0]}`;
14
+ const file = this.context.fs.getFileByPath(cmdPath);
14
15
 
15
- if(!file || file.constructor === Object || file.constructor === String) {
16
+ if(!file || file.constructor === Object) {
16
17
  return Promise.reject();
17
18
  }
18
19
 
19
- return Promise.resolve(`${this.context.getVar('PATH')}/${this.arguments[0]}`);
20
+ if(file.constructor === String && !file.startsWith('#!') && !this.context.fs.isExecutable(cmdPath)) {
21
+ return Promise.reject();
22
+ }
23
+
24
+ return Promise.resolve(cmdPath);
20
25
  }
21
26
  }
22
27