brsh 2.7.0 → 2.8.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
@@ -646,6 +646,9 @@ class Shell extends EventEmitter {
646
646
 
647
647
  const binLocation = `${this.path}/${cmdName}`;
648
648
  if (this._isWasmFile(binLocation, cmd)) {
649
+ if (!this.context.fs.isExecutable(binLocation)) {
650
+ throw new Error(`${command}: permission denied`);
651
+ }
649
652
  return WasmCommand.bind(null, binLocation);
650
653
  }
651
654
 
@@ -872,6 +875,30 @@ class Shell extends EventEmitter {
872
875
  static _escapeRegExp(string) {
873
876
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
874
877
  }
878
+
879
+ /**
880
+ * Asynchronously creates and boots a Shell instance.
881
+ * Pre-resolves any async filesystem sources (URLs, Promises, .brfs containers, or IndexedDB)
882
+ * before returning the fully initialized shell.
883
+ */
884
+ static async create(options = {}) {
885
+ let { filesystem, permissions, ...rest } = options;
886
+ if (isAsyncFilesystemSource(filesystem) || (filesystem && typeof filesystem === 'object' && isAsyncFilesystemSource(filesystem.filesystem))) {
887
+ const resolved = await resolveFilesystemSource(filesystem, permissions);
888
+ filesystem = resolved.filesystem;
889
+ permissions = resolved.permissions;
890
+ }
891
+ const shell = new Shell(Object.assign({}, rest, { filesystem, permissions }));
892
+ await shell.ready;
893
+ return shell;
894
+ }
895
+
896
+ /**
897
+ * Helper to create a Shell directly from a .brfs container (URL, Uint8Array, or Promise).
898
+ */
899
+ static async fromContainer(source, options = {}) {
900
+ return Shell.create(Object.assign({}, options, { filesystem: source }));
901
+ }
875
902
  }
876
903
 
877
904
  Shell.STATUS_READY = 'READY';
@@ -881,10 +908,12 @@ Shell.STATUS_DESTROYED = 'DESTROYED';
881
908
  Shell.Command = Command;
882
909
  Shell.InteractiveCommand = InteractiveCommand;
883
910
  Shell.WasmCommand = WasmCommand;
911
+ Shell.createWasmCommand = WasmCommand.createGenericWasmCommand || WasmCommand.createCommand;
884
912
  Shell.ReplCommand = require('./lib/ReplCommand');
885
913
  Shell.FS = BaseFileSystem;
886
914
  Shell.BinaryContainer = require('./lib/BinaryContainer');
887
915
  Shell.Storage = Shell.BinaryContainer.FilesystemStorage;
888
916
 
889
917
  globalThis.shell = Shell;
918
+ globalThis.Shell = Shell;
890
919
  module.exports = Shell;
package/lib/Terminal.js CHANGED
@@ -1,8 +1,10 @@
1
1
  'use strict';
2
2
 
3
- const Shell = require('Shell');
4
- const _AnsiUp = require('ansi_up');
5
- // ansi_up is a pre-compiled ESM→CJS shim: module.exports = { default: AnsiUp }
3
+ import _Shell from 'brsh';
4
+ import _AnsiUp from 'ansi_up';
5
+ import '../styles/terminal.css';
6
+
7
+ const ImportedShell = _Shell?.default ?? _Shell;
6
8
  const AnsiUp = _AnsiUp?.default ?? _AnsiUp;
7
9
 
8
10
  const HISTORY_FILE = '/.brsh_history';
@@ -44,7 +46,19 @@ class Terminal {
44
46
  this._lineWrap = lineWrap;
45
47
  this._working = true;
46
48
  this._pendingCommands = [];
47
- this.cli = new Shell(Object.assign({}, options, { command: undefined }));
49
+
50
+ let ShellClass = null;
51
+ if (options.Shell !== false && options.Shell !== null) {
52
+ ShellClass = options.Shell || (typeof globalThis !== 'undefined' && (globalThis.Shell || globalThis.shell)) || (typeof ImportedShell === 'function' ? ImportedShell : null);
53
+ }
54
+ this.cli = options.cli || options.shell;
55
+ if (!this.cli) {
56
+ if (!ShellClass) {
57
+ throw new Error('Shell is required by Terminal. Please import Shell from "brsh" or include shell.min.js before terminal.min.js.');
58
+ }
59
+ this.cli = new ShellClass(Object.assign({}, options, { command: undefined }));
60
+ }
61
+
48
62
  this._buffer = [];
49
63
  this._cursorPos = 0;
50
64
  this._history = [];
@@ -182,6 +196,8 @@ class Terminal {
182
196
  }
183
197
 
184
198
  _newPrompt(callback) {
199
+ if (typeof document === 'undefined' || !this._cmdList) return;
200
+ this._progressLine = null;
185
201
  this._clearCursor();
186
202
  this._currentLine = document.createElement('li');
187
203
  this._cmdList.appendChild(this._currentLine);
@@ -192,6 +208,24 @@ class Terminal {
192
208
  }
193
209
 
194
210
  _print(data, type = 'out') {
211
+ if (typeof data === 'string' && data.startsWith('\r')) {
212
+ const clean = data.slice(1);
213
+ if (this._progressLine && this._progressLine.parentNode === this._cmdList) {
214
+ this._progressLine.innerHTML = this._ansi.ansi_to_html(clean);
215
+ this._autoScroll();
216
+ return;
217
+ }
218
+ const line = document.createElement('li');
219
+ line.classList.add('terminal__line');
220
+ line.classList.add(type);
221
+ line.innerHTML = this._ansi.ansi_to_html(clean);
222
+ this._cmdList.appendChild(line);
223
+ this._progressLine = line;
224
+ this._autoScroll();
225
+ return;
226
+ }
227
+
228
+ this._progressLine = null;
195
229
  if(this._outputAnimation === 'none') {
196
230
  const line = document.createElement('li');
197
231
  line.classList.add('terminal__line');
@@ -308,7 +342,8 @@ class Terminal {
308
342
  }
309
343
 
310
344
  _statusCheck(status) {
311
- if(status === Shell.STATUS_READY) {
345
+ const readyStatus = this.cli?.constructor?.STATUS_READY || ImportedShell?.STATUS_READY || globalThis.Shell?.STATUS_READY || globalThis.shell?.STATUS_READY || 'READY';
346
+ if(status === readyStatus) {
312
347
  if (this._interactive) {
313
348
  this._exitInteractiveMode();
314
349
  }
@@ -644,8 +679,8 @@ class Terminal {
644
679
  }
645
680
  }
646
681
  }
647
-
648
- module.exports = Terminal;
649
-
650
- //import css
651
- require('../styles/terminal.css');
682
+ Terminal.Terminal = Terminal;
683
+ if (typeof globalThis !== 'undefined') {
684
+ globalThis.Terminal = Terminal;
685
+ }
686
+ export default Terminal;
package/lib/local/curl.js CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  const LocalCommand = require('./LocalCommand');
4
4
 
5
+ function formatBytes(bytes) {
6
+ if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
7
+ if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
8
+ return bytes + ' B';
9
+ }
10
+
5
11
  class Curl extends LocalCommand {
6
12
  static get name() { return 'curl'; }
7
13
  get requiresFilesystem() { return true; }
@@ -49,6 +55,9 @@ class Curl extends LocalCommand {
49
55
  case '-s': case '--silent':
50
56
  silent = true;
51
57
  break;
58
+ case '-#': case '--progress-bar':
59
+ // Accepted — progress bar is displayed when downloading to output file
60
+ break;
52
61
  case '-L': case '--location':
53
62
  // fetch follows redirects by default — accepted and ignored
54
63
  break;
@@ -91,16 +100,65 @@ class Curl extends LocalCommand {
91
100
  this.stdOut = '';
92
101
  }
93
102
 
94
- const text = await res.text();
103
+ let bytes = null;
104
+ const total = Number(res.headers.get('content-length') || 0);
105
+
106
+ if (res.body && typeof res.body.getReader === 'function') {
107
+ const reader = res.body.getReader();
108
+ const chunks = [];
109
+ let loaded = 0;
110
+ while (true) {
111
+ const { done, value } = await reader.read();
112
+ if (done) break;
113
+ chunks.push(value);
114
+ loaded += value.length;
115
+ if (outputFile && !silent) {
116
+ if (total > 0) {
117
+ const pct = Math.min(100, Math.floor((loaded / total) * 100));
118
+ const width = 20;
119
+ const filled = Math.min(width, Math.round((loaded / total) * width));
120
+ const bar = '='.repeat(Math.max(0, filled - 1)) + (filled > 0 ? '>' : '') + ' '.repeat(Math.max(0, width - filled));
121
+ this.stdOut = `\r[${bar}] ${pct}% (${formatBytes(loaded)} / ${formatBytes(total)})`;
122
+ } else {
123
+ this.stdOut = `\rDownloading: ${formatBytes(loaded)}`;
124
+ }
125
+ this.flush();
126
+ }
127
+ }
128
+ bytes = new Uint8Array(loaded);
129
+ let offset = 0;
130
+ for (const chunk of chunks) {
131
+ bytes.set(chunk, offset);
132
+ offset += chunk.length;
133
+ }
134
+ if (outputFile && !silent && loaded > 0) {
135
+ const finalTotal = total || loaded;
136
+ this.stdOut = `\r[${'='.repeat(20)}] 100% (${formatBytes(loaded)} / ${formatBytes(finalTotal)})`;
137
+ this.flush();
138
+ }
139
+ } else {
140
+ const buf = await res.arrayBuffer();
141
+ bytes = new Uint8Array(buf);
142
+ }
95
143
 
96
144
  if (outputFile) {
97
145
  try {
98
- this.fs.setFileByPath(outputFile, text, false);
146
+ const contentType = res.headers.get('content-type') || '';
147
+ const isText = /^text\/|application\/(json|javascript|xml|x-sh)/i.test(contentType);
148
+ if (isText) {
149
+ const text = new TextDecoder().decode(bytes);
150
+ this.fs.setFileByPath(outputFile, text, true);
151
+ } else {
152
+ const { BinaryFile } = require('../FileSystem');
153
+ const fileObj = BinaryFile ? new BinaryFile(bytes.buffer, contentType || 'application/octet-stream') : bytes;
154
+ this.fs.setFileByPath(outputFile, fileObj, true);
155
+ }
99
156
  } catch(e) {
100
157
  this.stdErr = `curl: cannot write to '${outputFile}': ${e.message}`;
101
158
  this.exitCode = 1;
102
159
  }
103
160
  } else {
161
+ const text = new TextDecoder().decode(bytes);
104
162
  text.split(/\r?\n/).forEach(line => { this.stdOut = line; });
105
163
  }
106
164
 
package/lib/wbt/index.js CHANGED
@@ -6,21 +6,9 @@ const ReplCommand = require('../ReplCommand');
6
6
  const { DEFAULT_REGISTRY, resolvePackageName } = require('./registry');
7
7
  const { writeBytesToFs, createGenericWasmCommand } = WasmCommand;
8
8
  const { createReplWasmCommand } = ReplCommand;
9
- const { daemonManager } = require('./daemon');
10
-
11
- const { createPgliteCommand, createPgCtlCommand } = require('./packages/pglite');
12
9
 
13
10
  const STATE_FILE = '/var/lib/wbt/installed.json';
14
11
  const CACHE_DIR = '/var/cache/wbt';
15
-
16
- const ADAPTER_FACTORIES = {
17
- pglite: (meta, cfg) => [
18
- { bin: meta.bin || 'pglite', Cmd: createPgliteCommand(meta, cfg, 'pglite') },
19
- { bin: 'psql', Cmd: createPgliteCommand(meta, cfg, 'psql') },
20
- { bin: 'pg_ctl', Cmd: createPgCtlCommand(meta, cfg) }
21
- ]
22
- };
23
-
24
12
  /**
25
13
  * Creates a Command class that executes a custom installed WASM or WAT file at `wasmPath`.
26
14
  */
@@ -60,6 +48,15 @@ class Wbt extends LocalCommand {
60
48
  return this.__wbtConfig || {};
61
49
  }
62
50
 
51
+ static get _adapters() {
52
+ if (!this.__adapters) this.__adapters = new Map();
53
+ return this.__adapters;
54
+ }
55
+
56
+ static registerAdapter(name, factory) {
57
+ this._adapters.set(name, factory);
58
+ }
59
+
63
60
  /**
64
61
  * Returns a configured subclass of Wbt with custom options:
65
62
  * - `registry`: custom package metadata entries merged with DEFAULT_REGISTRY
@@ -129,9 +126,18 @@ class Wbt extends LocalCommand {
129
126
  return [{ bin: binName, Cmd: createCustomWasmBinCommand(binName, pkgMeta.wasmPath, pkgMeta) }];
130
127
  }
131
128
 
132
- const factory = ADAPTER_FACTORIES[pkgMeta.adapter || pkgMeta.name];
133
- if (factory) {
134
- return factory(pkgMeta, cfg);
129
+ const adapterKey = pkgMeta.adapter || pkgMeta.name;
130
+ let factory = this.constructor._adapters && this.constructor._adapters.get(adapterKey);
131
+ if (!factory && pkgMeta.adapter) {
132
+ try {
133
+ const adapterMod = require(`./packages/${pkgMeta.adapter}`);
134
+ factory = adapterMod.buildEntries || adapterMod.createAdapter || adapterMod;
135
+ } catch {}
136
+ }
137
+ if (typeof factory === 'function') {
138
+ const result = factory(pkgMeta, cfg);
139
+ if (Array.isArray(result)) return result;
140
+ if (result) return [{ bin: (pkgMeta.bin || pkgMeta.name).toLowerCase(), Cmd: result }];
135
141
  }
136
142
 
137
143
  // Use `createReplWasmCommand` for packages with REPL enabled (`repl: true`),
@@ -209,12 +215,13 @@ class Wbt extends LocalCommand {
209
215
 
210
216
  async run() {
211
217
  const args = [...(this.arguments || [])];
212
- if (args.length === 0 || args.includes('--help') || args.includes('-h') || args[0] === 'help') {
218
+ const isRunSubcmd = args.length >= 2 && args[0].toLowerCase() === 'run';
219
+ if (args.length === 0 || (!isRunSubcmd && (args.includes('--help') || args.includes('-h') || args[0] === 'help'))) {
213
220
  this._printHelp();
214
221
  return;
215
222
  }
216
223
 
217
- if (args.includes('--version') || args.includes('-v')) {
224
+ if (!isRunSubcmd && (args.includes('--version') || args.includes('-v'))) {
218
225
  this.stdOut = 'wbt 1.1.0 (Web Binary Tool for brsh)';
219
226
  return;
220
227
  }
@@ -247,11 +254,6 @@ class Wbt extends LocalCommand {
247
254
  case 'run':
248
255
  await this._handleRun(args);
249
256
  break;
250
- case 'services':
251
- case 'daemons':
252
- case 'ps':
253
- await this._handleServices(args);
254
- break;
255
257
  default:
256
258
  this.stdErr = `E: Invalid operation ${subcmd}`;
257
259
  this.stdErr = `Run 'wbt --help' for usage information.`;
@@ -382,6 +384,7 @@ class Wbt extends LocalCommand {
382
384
  version: pkgMeta.version,
383
385
  description: pkgMeta.description,
384
386
  cdnUrl: pkgMeta.cdnUrl,
387
+ wasmUrl: pkgMeta.wasmUrl,
385
388
  type: pkgMeta.type,
386
389
  adapter: pkgMeta.adapter,
387
390
  repl: pkgMeta.repl,
@@ -716,30 +719,6 @@ class Wbt extends LocalCommand {
716
719
  this.exitCode = res.getExitCode();
717
720
  }
718
721
 
719
- async _handleServices(args) {
720
- const sub = (args[0] || 'list').toLowerCase();
721
- if (sub === 'stop' && args[1]) {
722
- const stopped = await daemonManager.stopDaemon(args[1]);
723
- if (!stopped) {
724
- this.stdErr = `E: No running service matching '${args[1]}'`;
725
- this.exitCode = 1;
726
- return;
727
- }
728
- this.stdOut = `Stopped service ${stopped.name} (PID ${stopped.pid}, port ${stopped.port})`;
729
- return;
730
- }
731
-
732
- const list = daemonManager.listDaemons();
733
- if (list.length === 0) {
734
- this.stdOut = 'No WASM background services currently running.';
735
- return;
736
- }
737
- this.stdOut = 'PID SERVICE PORT HOST DATADIR';
738
- for (const d of list) {
739
- this.stdOut = `${String(d.pid).padEnd(5)} ${d.name.padEnd(10)} ${String(d.port).padEnd(6)} ${d.host.padEnd(11)} ${d.dataDir}`;
740
- }
741
- }
742
-
743
722
  _printHelp() {
744
723
  [
745
724
  'wbt 1.1.0 — Web Binary Tool (WASM binary manager & runtime for brsh)',
@@ -753,10 +732,8 @@ class Wbt extends LocalCommand {
753
732
  ' search <query> Search available WASM binaries by name or description',
754
733
  ' show <pkg> Show detailed information about a package',
755
734
  ' run <pkg> [args...] Run a WASM binary without permanently installing it',
756
- ' services [stop <id>] List or stop running WASM background server daemons',
757
735
  '',
758
736
  'Curated WASM Packages:',
759
- ' pglite WASM PostgreSQL database, REPL & daemon (pglite, psql, pg_ctl)',
760
737
  ' sqlite3 SQLite3 compiled to WebAssembly (sqlite3, sqlite)',
761
738
  ' assemblyscript AssemblyScript compiler & ts-node style runtime (asc, asrun, asnode)',
762
739
  ' jq Command-line JSON processor (jq)',
@@ -766,7 +743,8 @@ class Wbt extends LocalCommand {
766
743
  ' ffmpeg FFmpeg multimedia transcoder (ffmpeg)',
767
744
  ' wabt WebAssembly Binary Toolkit (wat2wasm, wasm2wat)',
768
745
  ' quickjs Sandboxed QuickJS JavaScript engine (qjs)',
769
- ' lua Lua 5.4 WebAssembly interpreter (lua)'
746
+ ' lua Lua 5.4 WebAssembly interpreter (lua)',
747
+ ' wllama WASM & WebGPU LLM inference engine (wllama, llama, llama-cli)'
770
748
  ].forEach(l => { this.stdOut = l; });
771
749
  }
772
750
  }
@@ -774,6 +752,5 @@ class Wbt extends LocalCommand {
774
752
  module.exports = Wbt;
775
753
  module.exports.Wbt = Wbt;
776
754
  module.exports.DEFAULT_REGISTRY = DEFAULT_REGISTRY;
777
- module.exports.daemonManager = daemonManager;
778
755
  module.exports.createGenericWasmCommand = createGenericWasmCommand;
779
756
  module.exports.createReplWasmCommand = createReplWasmCommand;