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.
package/lib/FileSystem.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const BaseFileSystem = require('./BaseFileSystem');
4
- const { BinaryFile, SymlinkRef } = BaseFileSystem;
4
+ const { BinaryFile, SymlinkRef, DeviceFile } = BaseFileSystem;
5
5
 
6
6
  /**
7
7
  * Recursively converts `data:<mime>;base64,<...>` strings in a filesystem
@@ -12,7 +12,9 @@ const { BinaryFile, SymlinkRef } = BaseFileSystem;
12
12
  function decodeBinaryFiles(node) {
13
13
  for (const key of Object.keys(node)) {
14
14
  const value = node[key];
15
- if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof SymlinkRef)) {
15
+ if (value && typeof value === 'object' && ('$l' in value)) {
16
+ node[key] = new SymlinkRef(value.$l);
17
+ } else if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof SymlinkRef) && !(value instanceof DeviceFile)) {
16
18
  decodeBinaryFiles(value);
17
19
  } else if (typeof value === 'string' && value.startsWith('data:')) {
18
20
  const semicolon = value.indexOf(';');
@@ -58,6 +60,63 @@ class FileSystem extends BaseFileSystem {
58
60
  this.cwd = cwd.endsWith('/') ? cwd : (cwd + '/');
59
61
  this._onChange = onChange;
60
62
  this._changeScheduled = false;
63
+ this._initDevices();
64
+ }
65
+
66
+ _initDevices() {
67
+ this._devices = {};
68
+ const dev = this._devices;
69
+ dev.null = new DeviceFile('null', { read: () => '', write: () => {} });
70
+ dev.zero = new DeviceFile('zero', {
71
+ read: () => new Uint8Array(4096),
72
+ write: () => {}
73
+ });
74
+ dev.urandom = new DeviceFile('urandom', {
75
+ read: () => {
76
+ const buf = new Uint8Array(256);
77
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
78
+ crypto.getRandomValues(buf);
79
+ } else {
80
+ for (let i = 0; i < buf.length; i++) buf[i] = Math.floor(Math.random() * 256);
81
+ }
82
+ return buf;
83
+ },
84
+ write: () => {}
85
+ });
86
+ dev.random = dev.urandom;
87
+ dev.tty = new DeviceFile('tty', {
88
+ read: () => '',
89
+ write: () => {}
90
+ });
91
+ dev.stdin = new SymlinkRef('/dev/tty');
92
+ dev.stdout = new SymlinkRef('/dev/tty');
93
+ dev.stderr = new SymlinkRef('/dev/tty');
94
+ }
95
+
96
+ _getDevDir() {
97
+ if (!this._devices) this._initDevices();
98
+ if (this.fileSystem && this.fileSystem.dev && typeof this.fileSystem.dev === 'object' && !(this.fileSystem.dev instanceof SymlinkRef) && !(this.fileSystem.dev instanceof Uint8Array)) {
99
+ return Object.assign({}, this.fileSystem.dev, this._devices);
100
+ }
101
+ return this._devices;
102
+ }
103
+
104
+ _getRootOverlay() {
105
+ const root = Object.assign({}, this.fileSystem);
106
+ root.dev = this._getDevDir();
107
+ return root;
108
+ }
109
+
110
+ setTtyDevice(options = {}) {
111
+ if (!this._devices) this._initDevices();
112
+ this._devices.tty = new DeviceFile('tty', {
113
+ read: options.read || (() => ''),
114
+ write: options.write || (() => {}),
115
+ mode: 0o666
116
+ });
117
+ this._devices.stdin = new SymlinkRef('/dev/tty');
118
+ this._devices.stdout = new SymlinkRef('/dev/tty');
119
+ this._devices.stderr = new SymlinkRef('/dev/tty');
61
120
  }
62
121
 
63
122
  /**
@@ -82,12 +141,15 @@ class FileSystem extends BaseFileSystem {
82
141
  const file = this._resolveByAbsolutePath(this._pathToAbsolute(path), true);
83
142
  if (file === null || file === undefined) return null;
84
143
  if (!this.isReadable(path)) return null;
144
+ if (file instanceof DeviceFile) return file.read();
85
145
  return file;
86
146
  }
87
147
 
88
148
  // Raw read bypassing permission checks — for internal/system use only.
89
149
  _getFileRaw(path) {
90
- return this._getFileByAbsolutePath(this._pathToAbsolute(path));
150
+ const file = this._getFileByAbsolutePath(this._pathToAbsolute(path));
151
+ if (file instanceof DeviceFile) return file.read();
152
+ return file;
91
153
  }
92
154
 
93
155
  // Returns true if the path exists (and for symlinks, the target resolves too).
@@ -105,7 +167,7 @@ class FileSystem extends BaseFileSystem {
105
167
  return file instanceof SymlinkRef ? file.target : null;
106
168
  }
107
169
  createSymlink(target, linkPath) {
108
- this._setFileRaw(linkPath, new SymlinkRef(target));
170
+ this._setFileRaw(linkPath, new SymlinkRef(target), true);
109
171
  }
110
172
 
111
173
  // Returns type metadata without following the final symlink (like lstat).
@@ -114,7 +176,18 @@ class FileSystem extends BaseFileSystem {
114
176
  const file = this._resolveByAbsolutePath(this._pathToAbsolute(path), false);
115
177
  if (file === null || file === undefined) return null;
116
178
  if (file instanceof SymlinkRef) {
117
- return { isDirectory: false, isFile: false, isCommand: false, isBinary: false, isSymlink: true };
179
+ return { isDirectory: false, isFile: false, isCommand: false, isBinary: false, isSymlink: true, isDevice: false, isCharacterDevice: false };
180
+ }
181
+ if (file instanceof DeviceFile) {
182
+ return {
183
+ isDirectory: false,
184
+ isFile: true,
185
+ isCommand: false,
186
+ isBinary: file.read() instanceof Uint8Array,
187
+ isSymlink: false,
188
+ isDevice: true,
189
+ isCharacterDevice: true,
190
+ };
118
191
  }
119
192
  return {
120
193
  isDirectory: file.constructor === Object,
@@ -122,6 +195,8 @@ class FileSystem extends BaseFileSystem {
122
195
  isCommand: typeof file === 'function',
123
196
  isBinary: file instanceof Uint8Array,
124
197
  isSymlink: false,
198
+ isDevice: false,
199
+ isCharacterDevice: false,
125
200
  };
126
201
  }
127
202
 
@@ -158,6 +233,11 @@ class FileSystem extends BaseFileSystem {
158
233
  const existing = this._getFileByAbsolutePath(absolute);
159
234
  if (existing !== null && existing !== undefined) {
160
235
  if (!this.isWritable(path)) throw new Error('Permission denied');
236
+ if (existing instanceof DeviceFile) {
237
+ existing.write(content);
238
+ this._triggerChange();
239
+ return;
240
+ }
161
241
  } else {
162
242
  const parentParts = absolute.split('/');
163
243
  parentParts.pop();
@@ -181,6 +261,28 @@ class FileSystem extends BaseFileSystem {
181
261
  parts.shift();
182
262
  const filename = parts.pop();
183
263
 
264
+ if (parts.length > 0 && parts[0] === 'dev') {
265
+ let dir = this._getDevDir();
266
+ const devParts = parts.slice(1);
267
+ for (const handle of devParts) {
268
+ if (!Object.prototype.hasOwnProperty.call(dir, handle)) {
269
+ if (!createDir) throw new Error(`${handle}: No such file or directory`);
270
+ dir[handle] = {};
271
+ }
272
+ dir = dir[handle];
273
+ }
274
+ if (dir[filename] instanceof DeviceFile) {
275
+ dir[filename].write(content);
276
+ return;
277
+ }
278
+ dir[filename] = content;
279
+ return;
280
+ }
281
+
282
+ if (parts.length === 0 && filename === 'dev') {
283
+ throw new Error('dev: File exists');
284
+ }
285
+
184
286
  let dir = this.fileSystem;
185
287
  const pathSoFar = [];
186
288
  for (const handle of parts) {
@@ -203,6 +305,10 @@ class FileSystem extends BaseFileSystem {
203
305
  }
204
306
  dir = next;
205
307
  }
308
+ if (dir[filename] instanceof DeviceFile) {
309
+ dir[filename].write(content);
310
+ return;
311
+ }
206
312
  dir[filename] = content;
207
313
  }
208
314
 
@@ -217,11 +323,22 @@ class FileSystem extends BaseFileSystem {
217
323
  parts.shift();
218
324
  if (parts.length > 0 && parts[parts.length - 1].length < 1) parts.pop();
219
325
 
326
+ if (parts.length === 0) {
327
+ return this._getRootOverlay();
328
+ }
329
+
220
330
  let pointer = this.fileSystem;
221
331
  const pathSoFar = [];
222
332
  for (let i = 0; i < parts.length; i++) {
223
333
  const handle = parts[i];
224
334
  const isLast = i === parts.length - 1;
335
+
336
+ if (i === 0 && handle === 'dev') {
337
+ pointer = this._getDevDir();
338
+ pathSoFar.push(handle);
339
+ continue;
340
+ }
341
+
225
342
  if (pointer == null || typeof pointer !== 'object' || pointer instanceof SymlinkRef) return null;
226
343
  if (!Object.prototype.hasOwnProperty.call(pointer, handle)) return null;
227
344
  pointer = pointer[handle];
@@ -242,10 +359,24 @@ class FileSystem extends BaseFileSystem {
242
359
  const parts = absolute.split('/');
243
360
  parts.shift();
244
361
 
245
- if(parts[parts.length - 1].length < 1) {
362
+ if (parts.length > 0 && parts[parts.length - 1].length < 1) {
246
363
  parts.pop();
247
364
  }
248
365
 
366
+ if (parts.length === 0) {
367
+ return this._getRootOverlay();
368
+ }
369
+
370
+ if (parts[0] === 'dev') {
371
+ let pointer = this._getDevDir();
372
+ for (let i = 1; i < parts.length; i++) {
373
+ if (pointer == null || typeof pointer !== 'object') return null;
374
+ if (!Object.prototype.hasOwnProperty.call(pointer, parts[i])) return null;
375
+ pointer = pointer[parts[i]];
376
+ }
377
+ return pointer;
378
+ }
379
+
249
380
  return parts.reduce((pointer, handle) => {
250
381
  if (pointer == null || typeof pointer !== 'object') return null;
251
382
  if (!Object.prototype.hasOwnProperty.call(pointer, handle)) return null;
@@ -282,6 +413,22 @@ class FileSystem extends BaseFileSystem {
282
413
  const filename = parts.pop();
283
414
  if (!filename) return;
284
415
 
416
+ if (parts.length > 0 && parts[0] === 'dev') {
417
+ let parent = this._getDevDir();
418
+ for (let i = 1; i < parts.length; i++) {
419
+ if (!parent || typeof parent !== 'object') return;
420
+ parent = parent[parts[i]];
421
+ }
422
+ if (parent && filename in parent) {
423
+ delete parent[filename];
424
+ }
425
+ return;
426
+ }
427
+
428
+ if (parts.length === 0 && filename === 'dev') {
429
+ return;
430
+ }
431
+
285
432
  let parent = this.fileSystem;
286
433
  const pathSoFar = [];
287
434
  for (const handle of parts) {
@@ -311,6 +458,7 @@ class FileSystem extends BaseFileSystem {
311
458
  }
312
459
  const file = this._resolveByAbsolutePath(absolute, true);
313
460
  if (file === null || file === undefined) return null;
461
+ if (file instanceof DeviceFile) return file.mode || 0o666;
314
462
  if (file.constructor === Object) return 0o755;
315
463
  if (typeof file === 'function') return 0o555;
316
464
  return 0o644;
@@ -326,6 +474,11 @@ class FileSystem extends BaseFileSystem {
326
474
  const absolute = this._pathToAbsolute(path);
327
475
  const file = this._resolveByAbsolutePath(absolute, true);
328
476
  if (file === null || file === undefined) return 0;
477
+ if (file instanceof DeviceFile) {
478
+ const val = file.read();
479
+ if (val instanceof Uint8Array) return val.length;
480
+ return typeof val === 'string' ? val.length : 0;
481
+ }
329
482
  if (file.constructor === Object) return JSON.stringify(file).length;
330
483
  if (file instanceof Uint8Array) return file.length;
331
484
  return file.toString().length;
@@ -65,6 +65,11 @@ class InteractiveCommand extends Command {
65
65
  if (this.stdout) this.stdout.write('\x1b[?1049l\x1b[?25h');
66
66
  }
67
67
 
68
+ kill(signal = 'SIGINT') {
69
+ this._exitAltScreen();
70
+ super.kill(signal);
71
+ }
72
+
68
73
  runCommand() {
69
74
  if (this.interactive) {
70
75
  this._enterAltScreen();
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+
3
+ const WasmCommand = require('./WasmCommand');
4
+
5
+ /**
6
+ * Handles loading, evaluating, and wrapping JavaScript commands and modules
7
+ * stored on the brsh virtual or real filesystem.
8
+ */
9
+ class JsCommand {
10
+ static isCommandClass(fn) {
11
+ return typeof fn === 'function'
12
+ && Boolean(fn.prototype)
13
+ && typeof fn.prototype.run === 'function'
14
+ && typeof fn.prototype.runCommand === 'function';
15
+ }
16
+
17
+ static isJsFile(scriptPath, content) {
18
+ if (typeof content === 'function') return true;
19
+ if (scriptPath && scriptPath.endsWith('.js')) return true;
20
+ return typeof content === 'string' && (content.includes('export') || content.includes('module.exports'));
21
+ }
22
+
23
+ /**
24
+ * Loads a JavaScript module from the filesystem, evaluates it,
25
+ * and returns an executable Command class.
26
+ *
27
+ * @param {Object} fs - The filesystem instance (BaseFileSystem / NodeFileSystem)
28
+ * @param {string} scriptPath - Absolute path to the .js script
29
+ * @param {string|Function|null} content - Optional pre-read content or function
30
+ * @param {Map} [cache] - Optional cache Map to store evaluated classes by scriptPath
31
+ * @returns {Function} Executable Command constructor
32
+ */
33
+ static load(fs, scriptPath, content = null, cache = null) {
34
+ const fileContent = content !== null && content !== undefined
35
+ ? content
36
+ : (fs && typeof fs.getFileByPath === 'function' ? fs.getFileByPath(scriptPath) : null);
37
+
38
+ if (cache && cache.has(scriptPath)) {
39
+ const cached = cache.get(scriptPath);
40
+ if (cached && cached.content === fileContent) {
41
+ return cached.Cmd;
42
+ }
43
+ }
44
+
45
+ if (typeof fileContent === 'function') {
46
+ const Cmd = JsCommand.isCommandClass(fileContent)
47
+ ? fileContent
48
+ : JsCommand.wrapModule(fs, scriptPath, fileContent);
49
+ if (cache) {
50
+ cache.set(scriptPath, { content: fileContent, Cmd });
51
+ }
52
+ return Cmd;
53
+ }
54
+
55
+ let exported = null;
56
+ try {
57
+ if (fs && typeof fs.loadModule === 'function') {
58
+ exported = fs.loadModule(scriptPath);
59
+ } else {
60
+ const nodeReq = typeof require !== 'undefined' ? require : null;
61
+ if (nodeReq) {
62
+ exported = nodeReq(scriptPath);
63
+ } else {
64
+ throw new Error('loadModule is not available on filesystem');
65
+ }
66
+ }
67
+ } catch (e) {
68
+ throw new Error(`${scriptPath}: Failed to evaluate script: ${e.message}`);
69
+ }
70
+
71
+ const Cmd = JsCommand.isCommandClass(exported)
72
+ ? exported
73
+ : JsCommand.wrapModule(fs, scriptPath, exported);
74
+
75
+ if (cache) {
76
+ cache.set(scriptPath, { content: fileContent, Cmd });
77
+ }
78
+ return Cmd;
79
+ }
80
+
81
+ /**
82
+ * Wraps a non-Command export (e.g. exported function or module object)
83
+ * as an executable GenericWasmCommand, automatically detecting any sibling .wasm binary.
84
+ *
85
+ * @param {Object} fs - The filesystem instance
86
+ * @param {string} scriptPath - Absolute path to the .js file
87
+ * @param {*} exported - The module's exported value
88
+ * @returns {Function} Executable Command constructor
89
+ */
90
+ static wrapModule(fs, scriptPath, exported) {
91
+ const binName = scriptPath.split('/').pop().replace(/\.js$/i, '').toLowerCase();
92
+ const siblingWasmPath = scriptPath.replace(/\.js$/i, '.wasm');
93
+ const hasSiblingWasm = fs && typeof fs.exists === 'function' && fs.exists(siblingWasmPath);
94
+ const wasmBytes = (hasSiblingWasm && typeof fs.getFileByPath === 'function')
95
+ ? fs.getFileByPath(siblingWasmPath)
96
+ : null;
97
+
98
+ const pkgMeta = {
99
+ name: binName,
100
+ bin: binName,
101
+ wasmPath: hasSiblingWasm ? siblingWasmPath : null,
102
+ wasmBytes: wasmBytes || null
103
+ };
104
+
105
+ const config = {
106
+ moduleLoader: async () => exported
107
+ };
108
+
109
+ return WasmCommand.createGenericWasmCommand(pkgMeta, config, binName);
110
+ }
111
+ }
112
+
113
+ module.exports = JsCommand;