brsh 2.1.1 → 2.1.3

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 (56) hide show
  1. package/.github/workflows/pages.yml +12 -1
  2. package/.nvmrc +1 -0
  3. package/CHANGELOG.md +14 -0
  4. package/Readme.md +191 -3
  5. package/bin/brsh-shell.js +65 -0
  6. package/dist/brsh.css +1 -1
  7. package/dist/shell.es.js +854 -577
  8. package/dist/shell.es.js.map +1 -1
  9. package/dist/shell.min.js +13 -9
  10. package/dist/shell.min.js.map +1 -1
  11. package/dist/terminal.es.js +874 -588
  12. package/dist/terminal.es.js.map +1 -1
  13. package/dist/terminal.min.js +16 -12
  14. package/dist/terminal.min.js.map +1 -1
  15. package/index.js +65 -10
  16. package/lib/BaseFileSystem.js +82 -0
  17. package/lib/Command.js +3 -1
  18. package/lib/Context.js +3 -2
  19. package/lib/FileSystem.js +55 -26
  20. package/lib/NodeFileSystem.js +31 -17
  21. package/lib/Terminal.js +34 -5
  22. package/lib/WasmCommand.js +14 -7
  23. package/lib/buildFilesystemStructure.js +9 -4
  24. package/lib/builtins/cat.js +4 -1
  25. package/lib/builtins/echo.js +2 -0
  26. package/lib/builtins/false.js +1 -1
  27. package/lib/builtins/grep.js +10 -2
  28. package/lib/builtins/ls.js +6 -2
  29. package/lib/builtins/test.js +2 -4
  30. package/lib/builtins/true.js +1 -1
  31. package/lib/local/alias.js +2 -0
  32. package/lib/local/cd.js +5 -3
  33. package/lib/local/chmod.js +2 -3
  34. package/lib/local/clear.js +2 -0
  35. package/lib/local/cp.js +13 -8
  36. package/lib/local/curl.js +138 -0
  37. package/lib/local/exit.js +2 -0
  38. package/lib/local/export.js +2 -0
  39. package/lib/local/index.js +2 -1
  40. package/lib/local/jsfunction.js +1 -1
  41. package/lib/local/mkdir.js +3 -3
  42. package/lib/local/mv.js +12 -6
  43. package/lib/local/pwd.js +2 -0
  44. package/lib/local/read.js +2 -0
  45. package/lib/local/rm.js +1 -1
  46. package/lib/local/source.js +5 -4
  47. package/lib/local/which.js +2 -0
  48. package/package.json +9 -4
  49. package/styles/terminal.css +8 -1
  50. package/test/builtins.test.js +11 -0
  51. package/test/exportFileSystem.test.js +28 -8
  52. package/test/local-commands.test.js +11 -0
  53. package/test/scripts.test.js +57 -0
  54. package/test/shell.test.js +42 -0
  55. package/vite.config.demo.js +35 -0
  56. package/vite.config.js +34 -0
package/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- const EventEmitter = require('events');
4
-
5
3
  const Context = require('./lib/Context');
6
4
  const LocalCommand = require('./lib/local/LocalCommand');
7
5
  const ScriptCommand = require('./lib/ScriptCommand');
@@ -10,9 +8,13 @@ const Command = require('./lib/Command');
10
8
 
11
9
  const builtins = require('./lib/builtins');
12
10
  const localCommands = require('./lib/local');
11
+ const events = require('events');
12
+ const BaseFileSystem = require('./lib/BaseFileSystem');
13
13
 
14
14
  const variableRegex = /\${?([\w\d]+)}?/g;
15
15
 
16
+
17
+ const EventEmitter = events.EventEmitter || events.default || events;
16
18
  //shims etc
17
19
  String.prototype.regexIndexOf = function(regex, startpos) {
18
20
  const indexOf = this.substring(startpos || 0).search(regex);
@@ -146,7 +148,29 @@ class Shell extends EventEmitter {
146
148
  }
147
149
 
148
150
  if (!args.length) return;
149
- let bin = args.shift();
151
+ let bin = args.shift().value;
152
+
153
+ // Parse output redirection (> and >>)
154
+ // Quoted tokens (hasQuote: true) are never treated as redirects.
155
+ let redirectPath = null;
156
+ let appendMode = false;
157
+ const filteredArgs = [];
158
+ for (let i = 0; i < args.length; i++) {
159
+ const { value: arg, hasQuote } = args[i];
160
+ if (!hasQuote && (arg === '>>' || arg === '>') && i + 1 < args.length) {
161
+ appendMode = arg === '>>';
162
+ redirectPath = args[++i].value;
163
+ } else if (!hasQuote && arg.startsWith('>>') && arg.length > 2) {
164
+ appendMode = true;
165
+ redirectPath = arg.slice(2);
166
+ } else if (!hasQuote && arg.startsWith('>') && arg.length > 1) {
167
+ appendMode = false;
168
+ redirectPath = arg.slice(1);
169
+ } else {
170
+ filteredArgs.push(arg);
171
+ }
172
+ }
173
+ args = filteredArgs;
150
174
 
151
175
  //short circuit for aliases
152
176
  const alias = this.context.getAlias(bin);
@@ -166,10 +190,11 @@ class Shell extends EventEmitter {
166
190
  return;
167
191
  }
168
192
 
193
+ const isCommandClass = (C) => typeof C === 'function' && typeof C.prototype.run === 'function' && typeof C.prototype.runCommand === 'function';
169
194
  let instance;
170
195
  if(Cmd.prototype instanceof LocalCommand || new Cmd() instanceof ScriptCommand) {
171
196
  instance = new Cmd(args, this.context);
172
- } else if(Cmd.prototype instanceof Command) {
197
+ } else if(isCommandClass(Cmd)) {
173
198
  instance = new Cmd(args);
174
199
  } else {
175
200
  this.emit('stdErr', `${bin}: Command not found`);
@@ -179,7 +204,7 @@ class Shell extends EventEmitter {
179
204
  }
180
205
 
181
206
  if(instance.requiresFilesystem) {
182
- instance.fs = this.context.fs;
207
+ instance.fs = this.context.fs.sandbox();
183
208
  }
184
209
 
185
210
  if (this._stdin !== undefined) {
@@ -194,7 +219,33 @@ class Shell extends EventEmitter {
194
219
  }
195
220
 
196
221
  return instance.runCommand().then(result => {
197
- this._emitOutput(result.getStdOutput());
222
+ const stdOutput = result.getStdOutput();
223
+
224
+ if (redirectPath) {
225
+ const absTarget = this.context.fs.absolutePath(redirectPath);
226
+ const outLines = stdOutput.filter(l => l.type === 'out').map(l => l.string);
227
+ const content = appendMode
228
+ ? (() => {
229
+ const existing = this.context.fs._getFileRaw(absTarget);
230
+ return typeof existing === 'string'
231
+ ? existing + '\n' + outLines.join('\n')
232
+ : outLines.join('\n');
233
+ })()
234
+ : outLines.join('\n');
235
+ try {
236
+ this.context.fs.setFileByPath(absTarget, content, true);
237
+ } catch (e) {
238
+ this.emit('stdErr', `${redirectPath}: Permission denied`);
239
+ this.lastCode = 1;
240
+ this.emit('exitCode', this.lastCode);
241
+ delete this.runningCommand;
242
+ return;
243
+ }
244
+ this._emitOutput(stdOutput.filter(l => l.type === 'err'));
245
+ } else {
246
+ this._emitOutput(stdOutput);
247
+ }
248
+
198
249
  this.lastCode = result.getExitCode();
199
250
  this.emit('exitCode', this.lastCode);
200
251
  delete this.runningCommand;
@@ -265,7 +316,7 @@ class Shell extends EventEmitter {
265
316
 
266
317
  _parseCommand(command) {
267
318
  if(command.startsWith('./') || command.startsWith('/')) {
268
- const handle = this.context.fs.getFileByPath(command);
319
+ const handle = this.context.fs._getFileRaw(command);
269
320
  if(!handle) {
270
321
  throw new Error(`${command}: No such file or directory`);
271
322
  }
@@ -274,7 +325,10 @@ class Shell extends EventEmitter {
274
325
  throw new Error(`${command}: is a directory`);
275
326
  }
276
327
 
277
- if(handle.prototype && handle.prototype instanceof Command) {
328
+ if(handle.prototype && typeof handle.prototype.run === 'function' && typeof handle.prototype.runCommand === 'function') {
329
+ if (!this.context.fs.isExecutable(command)) {
330
+ throw new Error(`${command}: permission denied`);
331
+ }
278
332
  return handle;
279
333
  }
280
334
 
@@ -311,9 +365,9 @@ class Shell extends EventEmitter {
311
365
  )
312
366
  );
313
367
  // Keep tokens that are non-empty OR were explicitly quoted (preserves "" → '')
368
+ // Preserve hasQuote so redirect detection can skip quoted tokens.
314
369
  return replaced
315
- .filter(({ value, hasQuote }) => value.length > 0 || hasQuote)
316
- .map(({ value }) => value);
370
+ .filter(({ value, hasQuote }) => value.length > 0 || hasQuote);
317
371
  }
318
372
 
319
373
  static _sanitiseCommandPart(string) {
@@ -466,6 +520,7 @@ Shell.STATUS_WORKING = 'WORKING';
466
520
  Shell.STATUS_DESTROYED = 'DESTROYED';
467
521
 
468
522
  Shell.Command = Command;
523
+ Shell.FS = BaseFileSystem;
469
524
 
470
525
  global.shell = Shell;
471
526
  module.exports = Shell;
@@ -0,0 +1,82 @@
1
+ 'use strict';
2
+
3
+ // The set of methods exposed to command instances via sandbox().
4
+ // Anything not in this list is inaccessible to user-supplied commands.
5
+ const SANDBOX_ALLOWED = new Set([
6
+ 'getFileByPath', 'setFileByPath', 'deleteFileByPath',
7
+ 'exists', 'stat', 'absolutePath',
8
+ 'getMode', 'setMode',
9
+ 'isReadable', 'isWritable', 'isExecutable',
10
+ 'getSize', 'autoComplete',
11
+ 'isRealFilesystem', 'isSymlink',
12
+ ]);
13
+
14
+ /**
15
+ * Abstract base class for filesystem implementations.
16
+ *
17
+ * Subclasses must implement:
18
+ * getFileByPath(path)
19
+ * _getFileRaw(path)
20
+ * setFileByPath(path, content, createDir)
21
+ * deleteFileByPath(path)
22
+ * exists(path)
23
+ * stat(path)
24
+ * absolutePath(path)
25
+ * getMode(path)
26
+ * setMode(path, mode)
27
+ * getSize(path)
28
+ * autoComplete(initial, commandPath)
29
+ * setCwd(cwd)
30
+ * getRaw()
31
+ * getRawPermissions()
32
+ * addFiles(commands)
33
+ */
34
+ class BaseFileSystem {
35
+ isReadable(path) {
36
+ const mode = this.getMode(path);
37
+ if (mode === null) return false;
38
+ return (mode & 0o400) !== 0;
39
+ }
40
+
41
+ isWritable(path) {
42
+ const mode = this.getMode(path);
43
+ if (mode === null) return false;
44
+ return (mode & 0o200) !== 0;
45
+ }
46
+
47
+ isExecutable(path) {
48
+ const mode = this.getMode(path);
49
+ if (mode === null) return false;
50
+ return (mode & 0o100) !== 0;
51
+ }
52
+
53
+ // Returns a sandboxed proxy of this filesystem for use by commands.
54
+ // Only the public API is accessible; raw/internal methods are blocked.
55
+ sandbox() {
56
+ const target = this;
57
+ return new Proxy(Object.create(null), {
58
+ get(_, prop) {
59
+ if (!SANDBOX_ALLOWED.has(prop)) return undefined;
60
+ const val = target[prop];
61
+ return typeof val === 'function' ? val.bind(target) : val;
62
+ },
63
+ set() { return false; },
64
+ has(_, prop) { return SANDBOX_ALLOWED.has(prop); },
65
+ });
66
+ }
67
+
68
+ // Schedules a single onChange notification per microtask tick,
69
+ // so multiple mutations in one command emit only one callback.
70
+ _triggerChange() {
71
+ if (!this._onChange || this._changeScheduled) return;
72
+ this._changeScheduled = true;
73
+ Promise.resolve().then(() => {
74
+ this._changeScheduled = false;
75
+ if (typeof this._onChange === 'function') {
76
+ this._onChange(this.getRaw(), this.getRawPermissions());
77
+ }
78
+ });
79
+ }
80
+ }
81
+
82
+ module.exports = BaseFileSystem;
package/lib/Command.js CHANGED
@@ -1,8 +1,10 @@
1
1
  'use strict';
2
2
 
3
- const EventEmitter = require('events');
3
+ const events = require('events');
4
4
  const Result = require('./Result');
5
5
 
6
+ const EventEmitter = events.EventEmitter || events.default || events;
7
+
6
8
  class Command extends EventEmitter {
7
9
  constructor(args) {
8
10
  super();
package/lib/Context.js CHANGED
@@ -50,12 +50,13 @@ class Context {
50
50
  const path = this.getVar('PATH');
51
51
  const location = `${path}/${command.name.toLowerCase()}`;
52
52
  this.fs.addFiles({[location]: command});
53
+ this.fs.setMode(location, 0o555);
53
54
  }
54
55
 
55
56
  getCommand(command) {
56
57
  const path = this.getVar('PATH');
57
58
  const location = `${path}/${command}`;
58
- return this.fs.getFileByPath(location) || null;
59
+ return this.fs._getFileRaw(location) || null;
59
60
  }
60
61
 
61
62
  setNodeFilesystem(cwd) {
@@ -65,7 +66,7 @@ class Context {
65
66
  }
66
67
 
67
68
  setFilesystem(filesystem, permissions = {}) {
68
- const commands = this.fs.getFileByPath(this.getVar('PATH')) || {};
69
+ const commands = this.fs._getFileRaw(this.getVar('PATH')) || {};
69
70
  const oldPermissions = this.fs.getRawPermissions();
70
71
  const onChange = this.fs._onChange;
71
72
  this.fs = new FileSystem(this.fs.cwd, filesystem, Object.assign({}, oldPermissions, permissions), onChange);
package/lib/FileSystem.js CHANGED
@@ -1,7 +1,10 @@
1
1
  'use strict';
2
2
 
3
- class FileSystem {
3
+ const BaseFileSystem = require('./BaseFileSystem');
4
+
5
+ class FileSystem extends BaseFileSystem {
4
6
  constructor(cwd = '/', filesystem = {}, permissions = {}, onChange = null) {
7
+ super();
5
8
  this.fileSystem = filesystem;
6
9
  this.permissions = Object.assign({}, permissions);
7
10
  this.cwd = cwd;
@@ -9,10 +12,38 @@ class FileSystem {
9
12
  this._changeScheduled = false;
10
13
  }
11
14
 
15
+ // Returns file content if the path exists AND is readable; null otherwise.
16
+ // Use exists() or stat() for permission-free existence/type checks.
12
17
  getFileByPath(path) {
18
+ const file = this._getFileByAbsolutePath(this._pathToAbsolute(path));
19
+ if (file === null || file === undefined) return null;
20
+ if (!this.isReadable(path)) return null;
21
+ return file;
22
+ }
23
+
24
+ // Raw read bypassing permission checks — for internal/system use only.
25
+ _getFileRaw(path) {
13
26
  return this._getFileByAbsolutePath(this._pathToAbsolute(path));
14
27
  }
15
28
 
29
+ // Returns true if the path exists regardless of permissions.
30
+ exists(path) {
31
+ const file = this._getFileByAbsolutePath(this._pathToAbsolute(path));
32
+ return file !== null && file !== undefined;
33
+ }
34
+
35
+ // Returns type metadata without content access or permission checks.
36
+ // Returns null if the path does not exist.
37
+ stat(path) {
38
+ const file = this._getFileByAbsolutePath(this._pathToAbsolute(path));
39
+ if (file === null || file === undefined) return null;
40
+ return {
41
+ isDirectory: file.constructor === Object,
42
+ isFile: typeof file === 'string',
43
+ isCommand: typeof file === 'function'
44
+ };
45
+ }
46
+
16
47
  _pathToAbsolute(path) {
17
48
  if(path.startsWith('./')) {
18
49
  path = path.substring(2);
@@ -38,7 +69,26 @@ class FileSystem {
38
69
  return this._pathToAbsolute(path);
39
70
  }
40
71
 
72
+ // Writes with permission enforcement — throws Error('Permission denied') if not writable.
73
+ // Use _setFileRaw() for internal/system writes that must bypass permission checks.
41
74
  setFileByPath(path, content, createDir = false) {
75
+ const absolute = this._pathToAbsolute(path);
76
+ const existing = this._getFileByAbsolutePath(absolute);
77
+ if (existing !== null && existing !== undefined) {
78
+ if (!this.isWritable(path)) throw new Error('Permission denied');
79
+ } else {
80
+ const parentParts = absolute.split('/');
81
+ parentParts.pop();
82
+ const parentAbs = parentParts.join('/') || '/';
83
+ const parentMode = this.getMode(parentAbs);
84
+ if (parentMode !== null && !(parentMode & 0o200)) throw new Error('Permission denied');
85
+ }
86
+ this._setFileByAbsolutePath(absolute, content, createDir);
87
+ this._triggerChange();
88
+ }
89
+
90
+ // Raw write bypassing permission checks — for internal/system use only.
91
+ _setFileRaw(path, content, createDir = false) {
42
92
  const absolute = this._pathToAbsolute(path);
43
93
  this._setFileByAbsolutePath(absolute, content, createDir);
44
94
  this._triggerChange();
@@ -128,12 +178,6 @@ class FileSystem {
128
178
  this._triggerChange();
129
179
  }
130
180
 
131
- isExecutable(path) {
132
- const mode = this.getMode(path);
133
- if (mode === null) return false;
134
- return (mode & 0o100) !== 0;
135
- }
136
-
137
181
  getSize(path) {
138
182
  const absolute = this._pathToAbsolute(path);
139
183
  const file = this._getFileByAbsolutePath(absolute);
@@ -154,13 +198,9 @@ class FileSystem {
154
198
  return this.fileSystem;
155
199
  }
156
200
 
157
- getRawPermissions() {
158
- return Object.assign({}, this.permissions);
159
- }
160
-
161
201
  addFiles(commands) {
162
202
  Object.entries(commands).forEach(([path, command]) => {
163
- this.setFileByPath(path, command, true);
203
+ this._setFileRaw(path, command, true);
164
204
  });
165
205
  }
166
206
 
@@ -170,8 +210,8 @@ class FileSystem {
170
210
  const parts = absolute.split('/');
171
211
  const end = parts.pop();
172
212
 
173
- const dir = this.getFileByPath(parts.length > 1 ? parts.join('/') : '/');
174
- const pathDir = this.getFileByPath(path);
213
+ const dir = this._getFileRaw(parts.length > 1 ? parts.join('/') : '/');
214
+ const pathDir = this._getFileRaw(path);
175
215
 
176
216
  if(dir && dir.constructor === Object) {
177
217
  let options = Object.keys(dir).filter(item => item.startsWith(end));
@@ -198,18 +238,7 @@ class FileSystem {
198
238
  return null;
199
239
  }
200
240
 
201
- // Schedules a single onChange notification per microtask tick,
202
- // so multiple mutations in one command emit only one callback.
203
- _triggerChange() {
204
- if (!this._onChange || this._changeScheduled) return;
205
- this._changeScheduled = true;
206
- Promise.resolve().then(() => {
207
- this._changeScheduled = false;
208
- if (typeof this._onChange === 'function') {
209
- this._onChange(this.getRaw(), this.getRawPermissions());
210
- }
211
- });
212
- }
213
241
  }
214
242
 
243
+
215
244
  module.exports = FileSystem;
@@ -2,9 +2,11 @@
2
2
 
3
3
  const nodeFs = require('fs');
4
4
  const nodePath = require('path');
5
+ const BaseFileSystem = require('./BaseFileSystem');
5
6
 
6
- class NodeFileSystem {
7
+ class NodeFileSystem extends BaseFileSystem {
7
8
  constructor(cwd, onChange = null) {
9
+ super();
8
10
  this._onChange = onChange;
9
11
  this._changeScheduled = false;
10
12
  this._virtualFiles = {};
@@ -126,16 +128,14 @@ class NodeFileSystem {
126
128
  }
127
129
 
128
130
  setMode(path, mode) {
129
- nodeFs.chmodSync(this.absolutePath(path), mode);
131
+ const abs = this.absolutePath(path);
132
+ if (this._virtualFiles[abs] !== undefined) {
133
+ return;
134
+ }
135
+ nodeFs.chmodSync(abs, mode);
130
136
  this._triggerChange();
131
137
  }
132
138
 
133
- isExecutable(path) {
134
- const mode = this.getMode(path);
135
- if (mode === null) return false;
136
- return (mode & 0o100) !== 0;
137
- }
138
-
139
139
  getSize(path) {
140
140
  const abs = this.absolutePath(path);
141
141
  if (this._virtualFiles[abs] !== undefined) return 0;
@@ -223,16 +223,30 @@ class NodeFileSystem {
223
223
  };
224
224
  }
225
225
 
226
- _triggerChange() {
227
- if (!this._onChange || this._changeScheduled) return;
228
- this._changeScheduled = true;
229
- Promise.resolve().then(() => {
230
- this._changeScheduled = false;
231
- if (typeof this._onChange === 'function') {
232
- this._onChange(null, null);
233
- }
234
- });
226
+ // System-internal bypass (NodeFileSystem has no permission layer over real FS)
227
+ _getFileRaw(path) {
228
+ return this.getFileByPath(path);
229
+ }
230
+
231
+ exists(path) {
232
+ const abs = this.absolutePath(path);
233
+ if (this._virtualFiles[abs] !== undefined) return true;
234
+ try { nodeFs.statSync(abs); return true; } catch(e) { return false; }
235
+ }
236
+
237
+ stat(path) {
238
+ const abs = this.absolutePath(path);
239
+ if (this._virtualFiles[abs] !== undefined) {
240
+ const v = this._virtualFiles[abs];
241
+ return { isDirectory: v !== null && v !== undefined && v.constructor === Object, isFile: typeof v === 'string', isCommand: typeof v === 'function' };
242
+ }
243
+ try {
244
+ const s = nodeFs.statSync(abs);
245
+ return { isDirectory: s.isDirectory(), isFile: s.isFile(), isCommand: false };
246
+ } catch(e) { return null; }
235
247
  }
236
248
  }
237
249
 
238
250
  module.exports = NodeFileSystem;
251
+
252
+ module.exports = NodeFileSystem;
package/lib/Terminal.js CHANGED
@@ -1,7 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  const Shell = require('Shell');
4
- const AnsiUp = require('ansi_up');
4
+ const _AnsiUp = require('ansi_up');
5
+ // ansi_up is a pre-compiled ESM→CJS shim: module.exports = { default: AnsiUp }
6
+ const AnsiUp = _AnsiUp?.default ?? _AnsiUp;
5
7
 
6
8
  const HISTORY_FILE = '/.brsh_history';
7
9
 
@@ -14,7 +16,8 @@ class Terminal {
14
16
  outputAnimation = 'none',
15
17
  animateSpeed = 1,
16
18
  onExit = null,
17
- mobileInput = 'click'
19
+ mobileInput = 'click',
20
+ lineWrap = false
18
21
  } = options;
19
22
 
20
23
  if(!el) {
@@ -37,6 +40,7 @@ class Terminal {
37
40
  this._cursor = cursor;
38
41
  this._outputAnimation = outputAnimation;
39
42
  this._animateSpeed = animateSpeed;
43
+ this._lineWrap = lineWrap;
40
44
  this._working = false;
41
45
  this.cli = new Shell(options);
42
46
  this._buffer = [];
@@ -46,7 +50,7 @@ class Terminal {
46
50
  this._savedInput = null;
47
51
  this._historyLoaded = false;
48
52
  this._el = el;
49
- this._ansi = new AnsiUp.default();
53
+ this._ansi = new AnsiUp();
50
54
 
51
55
  this._ansi.use_classes = true;
52
56
  this._ansi.url_whitelist = {
@@ -134,6 +138,9 @@ class Terminal {
134
138
  this._cmdList.style.fontFamily = `'${font}', monospace`;
135
139
  this._cmdList.style.listStyle = 'none';
136
140
  this._cmdList.style.padding = '0';
141
+ if (this._lineWrap) {
142
+ this._cmdList.classList.add('terminal--wrap');
143
+ }
137
144
  parent.appendChild(this._cmdList);
138
145
  }
139
146
 
@@ -282,7 +289,7 @@ class Terminal {
282
289
 
283
290
  _loadHistory() {
284
291
  try {
285
- const file = this.cli.context.fs.getFileByPath(HISTORY_FILE);
292
+ const file = this.cli.context.fs._getFileRaw(HISTORY_FILE);
286
293
  if (file && typeof file === 'string' && file.length > 0) {
287
294
  this._history = file.split('\n').filter(l => l.length > 0);
288
295
  }
@@ -293,7 +300,7 @@ class Terminal {
293
300
 
294
301
  _saveHistory() {
295
302
  try {
296
- this.cli.context.fs.setFileByPath(HISTORY_FILE, this._history.join('\n'), true);
303
+ this.cli.context.fs._setFileRaw(HISTORY_FILE, this._history.join('\n'), true);
297
304
  } catch(e) {
298
305
  // Ignore persistence errors
299
306
  }
@@ -373,6 +380,28 @@ class Terminal {
373
380
  });
374
381
 
375
382
  el.addEventListener('keyup', (e) => this._keyEvent(onUpdate, e.key));
383
+
384
+ window.addEventListener('paste', (e) => {
385
+ e.preventDefault();
386
+ const text = (e.clipboardData || window.clipboardData).getData('text');
387
+ if (!text) return;
388
+
389
+ // Split on newlines; each newline acts as Enter (submits a command)
390
+ const segments = text.split(/\r?\n/);
391
+ segments.forEach((segment, idx) => {
392
+ // Bulk-insert characters for this segment
393
+ const chars = segment.split('');
394
+ this._buffer.splice(this._cursorPos, 0, ...chars);
395
+ this._cursorPos += chars.length;
396
+
397
+ // Newline between segments → submit as Enter
398
+ if (idx < segments.length - 1) {
399
+ this._keyEvent(onUpdate, 'Enter');
400
+ }
401
+ });
402
+
403
+ onUpdate(this._buffer);
404
+ });
376
405
  }
377
406
 
378
407
  _wordLeft() {
@@ -56,22 +56,29 @@ class WasmCommand extends ScriptCommand {
56
56
  async _runWat(bytes) {
57
57
  const text = new TextDecoder().decode(bytes);
58
58
  let wasmBytes;
59
+
60
+ let wabtModule;
61
+ try {
62
+ const wabtPkg = 'wabt'; // variable prevents Vite static import analysis
63
+ wabtModule = await import(/* @vite-ignore */wabtPkg);
64
+ } catch(e) {
65
+ this.stdErr = `${this.script}: WAT execution requires the 'wabt' package\nInstall it with: npm install wabt`;
66
+ this.exitCode = 1;
67
+ return;
68
+ }
69
+
59
70
  try {
60
- const wabtInit = require('wabt');
71
+ const wabtInit = wabtModule.default ?? wabtModule;
61
72
  const wabt = typeof wabtInit === 'function' ? await wabtInit() : wabtInit;
62
73
  const parsed = wabt.parseWat(this.script, text, { mutable_globals: true });
63
74
  const { buffer } = parsed.toBinary({});
64
75
  wasmBytes = new Uint8Array(buffer);
65
76
  } catch(e) {
66
- if (e.code === 'MODULE_NOT_FOUND') {
67
- this.stdErr = `${this.script}: WAT execution requires the 'wabt' package`;
68
- this.stdErr = `Install it with: npm install wabt`;
69
- } else {
70
- this.stdErr = `${this.script}: WAT compilation error: ${e.message}`;
71
- }
77
+ this.stdErr = `${this.script}: WAT compilation error: ${e.message}`;
72
78
  this.exitCode = 1;
73
79
  return;
74
80
  }
81
+
75
82
  return this._runWasm(wasmBytes);
76
83
  }
77
84
 
@@ -37,14 +37,19 @@ function _buildTree(root, virtualPrefix, permissions) {
37
37
  return structure;
38
38
  }
39
39
 
40
- // Confirm file is readable before including it
41
- fs.readFileSync(path.join(root, handle), 'utf8');
40
+ const filePath = path.join(root, handle);
41
+ const isJavaScript = handle.endsWith('.js');
42
+ const fileContents = isJavaScript
43
+ ? null
44
+ : fs.readFileSync(filePath, 'utf8');
42
45
 
43
- const key = handle.endsWith('.js')
46
+ const key = isJavaScript
44
47
  ? handle.substring(0, handle.length - 3)
45
48
  : handle;
46
49
 
47
- structure[key] = `require('${path.resolve(root, handle)}')`;
50
+ structure[key] = isJavaScript
51
+ ? `require('${path.resolve(root, handle)}')`
52
+ : fileContents;
48
53
 
49
54
  // Record real Unix permission bits for this file
50
55
  permissions[virtualPrefix + '/' + key] = stat.mode & 0o777;
@@ -3,6 +3,8 @@
3
3
  const Command = require('../Command');
4
4
 
5
5
  class Cat extends Command {
6
+ static get name() { return 'cat'; }
7
+
6
8
  get requiresFilesystem() {
7
9
  return true;
8
10
  }
@@ -43,7 +45,8 @@ class Cat extends Command {
43
45
  }
44
46
  const file = this.fs.getFileByPath(path);
45
47
  if (file === null || file === undefined) {
46
- this.stdErr = `${path}: No such file or directory`;
48
+ const msg = this.fs.exists(path) ? 'Permission denied' : 'No such file or directory';
49
+ this.stdErr = `${path}: ${msg}`;
47
50
  this.exitCode = 1;
48
51
  return Promise.resolve();
49
52
  }
@@ -3,6 +3,8 @@
3
3
  const Command = require('../Command');
4
4
 
5
5
  class Echo extends Command {
6
+ static get name() { return 'echo'; }
7
+
6
8
  run() {
7
9
  const args = [...this.arguments];
8
10
  let noNewline = false;
@@ -3,7 +3,7 @@
3
3
  const Command = require('../Command');
4
4
 
5
5
  class False extends Command {
6
- get name() { return 'false'; }
6
+ static get name() { return 'false'; }
7
7
  run() {
8
8
  this.exitCode = 1;
9
9
  return Promise.resolve();