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,779 @@
1
+ 'use strict';
2
+
3
+ const LocalCommand = require('../local/LocalCommand');
4
+ const WasmCommand = require('../WasmCommand');
5
+ const ReplCommand = require('../ReplCommand');
6
+ const { DEFAULT_REGISTRY, resolvePackageName } = require('./registry');
7
+ const { writeBytesToFs, createGenericWasmCommand } = WasmCommand;
8
+ const { createReplWasmCommand } = ReplCommand;
9
+ const { daemonManager } = require('./daemon');
10
+
11
+ const { createPgliteCommand, createPgCtlCommand } = require('./packages/pglite');
12
+
13
+ const STATE_FILE = '/var/lib/wbt/installed.json';
14
+ 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
+ /**
25
+ * Creates a Command class that executes a custom installed WASM or WAT file at `wasmPath`.
26
+ */
27
+ function createCustomWasmBinCommand(binName, wasmPath, pkgMeta = {}) {
28
+ class CustomWasmBin extends WasmCommand {
29
+ static get name() { return binName; }
30
+ get name() { return binName; }
31
+
32
+ constructor(args, context) {
33
+ super(wasmPath, args, context);
34
+ this.script = wasmPath;
35
+ this.arguments = args || [];
36
+ this.context = context || null;
37
+ this._pkgMeta = pkgMeta;
38
+ }
39
+ }
40
+ return CustomWasmBin;
41
+ }
42
+
43
+ /**
44
+ * Web Binary Tool (wbt) — optional APT-style WASM binary manager for brsh.
45
+ *
46
+ * Register in a shell via:
47
+ * import Wbt from 'brsh/wbt';
48
+ * shell.context.setCommand(Wbt);
49
+ *
50
+ * Or configure with custom registry/options:
51
+ * const CustomWbt = Wbt.configure({ registry: { ... } });
52
+ * shell.context.setCommand(CustomWbt);
53
+ */
54
+ class Wbt extends LocalCommand {
55
+ static get name() { return 'wbt'; }
56
+ get name() { return 'wbt'; }
57
+ get requiresFilesystem() { return true; }
58
+
59
+ static get _config() {
60
+ return this.__wbtConfig || {};
61
+ }
62
+
63
+ /**
64
+ * Returns a configured subclass of Wbt with custom options:
65
+ * - `registry`: custom package metadata entries merged with DEFAULT_REGISTRY
66
+ * - `moduleLoader`: async (pkgName, cdnUrl) => module (for custom CDN/offline/test injection)
67
+ * - `fetch`: custom fetch function for downloading custom `.wasm` URLs or remote registries
68
+ * - `sources`: array of remote registry JSON URLs to fetch on `wbt update`
69
+ */
70
+ static configure(config = {}) {
71
+ class ConfiguredWbt extends Wbt {
72
+ static get name() { return 'wbt'; }
73
+ }
74
+ ConfiguredWbt.__wbtConfig = Object.assign({}, this._config, config);
75
+ return ConfiguredWbt;
76
+ }
77
+
78
+ /**
79
+ * Restores any packages previously recorded in `/var/lib/wbt/installed.json`
80
+ * into the given Shell or Context (useful when loading a persisted virtual filesystem).
81
+ */
82
+ static restoreInstalled(shellOrContext, config = {}) {
83
+ const ctx = shellOrContext.context || shellOrContext;
84
+ if (!ctx || !ctx.fs) return;
85
+ const instance = new (this.configure(config))([], ctx);
86
+ instance.fs = ctx.fs.sandbox();
87
+ instance._restoreCommands();
88
+ }
89
+
90
+ _getRegistry() {
91
+ const cfg = this.constructor._config || {};
92
+ const base = Object.assign({}, DEFAULT_REGISTRY, cfg.registry || {});
93
+ try {
94
+ const cachedRemote = this.context.fs._getFileRaw(`${CACHE_DIR}/remote-registry.json`);
95
+ if (typeof cachedRemote === 'string' && cachedRemote.trim()) {
96
+ const parsed = JSON.parse(cachedRemote);
97
+ Object.assign(base, parsed);
98
+ }
99
+ } catch {
100
+ // ignore
101
+ }
102
+ return base;
103
+ }
104
+
105
+ _readState() {
106
+ try {
107
+ const raw = this.context.fs._getFileRaw(STATE_FILE);
108
+ if (typeof raw === 'string' && raw.trim()) {
109
+ const parsed = JSON.parse(raw);
110
+ if (parsed && typeof parsed === 'object' && parsed.packages) {
111
+ return parsed;
112
+ }
113
+ }
114
+ } catch {
115
+ // ignore
116
+ }
117
+ return { packages: {} };
118
+ }
119
+
120
+ _writeState(state) {
121
+ this.context.fs._setFileRaw(STATE_FILE, JSON.stringify(state, null, 2), true);
122
+ }
123
+
124
+ _buildCommandsForPackage(pkgMeta) {
125
+ const cfg = this.constructor._config || {};
126
+
127
+ if (pkgMeta.type === 'custom-wasm' && pkgMeta.wasmPath) {
128
+ const binName = (pkgMeta.bin || pkgMeta.name).toLowerCase();
129
+ return [{ bin: binName, Cmd: createCustomWasmBinCommand(binName, pkgMeta.wasmPath, pkgMeta) }];
130
+ }
131
+
132
+ const factory = ADAPTER_FACTORIES[pkgMeta.adapter || pkgMeta.name];
133
+ if (factory) {
134
+ return factory(pkgMeta, cfg);
135
+ }
136
+
137
+ // Use `createReplWasmCommand` for packages with REPL enabled (`repl: true`),
138
+ // and standard `createGenericWasmCommand` for non-interactive WASM CLI binaries.
139
+ const cmdBuilder = pkgMeta.repl ? createReplWasmCommand : createGenericWasmCommand;
140
+ const binName = (pkgMeta.bin || pkgMeta.name.split('/').pop()).toLowerCase();
141
+ const entries = [{ bin: binName, Cmd: cmdBuilder(pkgMeta, cfg, binName) }];
142
+ for (const alias of (pkgMeta.aliases || [])) {
143
+ const aliasLower = alias.toLowerCase();
144
+ if (aliasLower !== binName) {
145
+ entries.push({ bin: aliasLower, Cmd: cmdBuilder(pkgMeta, cfg, aliasLower) });
146
+ }
147
+ }
148
+ return entries;
149
+ }
150
+
151
+ _registerPackageIntoContext(pkgMeta) {
152
+ const pathDir = this.context.getVar('PATH') || '/bin';
153
+ const entries = this._buildCommandsForPackage(pkgMeta);
154
+ const installedBins = [];
155
+
156
+ for (const { bin, Cmd } of entries) {
157
+ const binName = bin.toLowerCase();
158
+ this._installBin(pathDir, binName, Cmd);
159
+ installedBins.push(binName);
160
+ }
161
+
162
+ // Also register any aliases not already created by the factory
163
+ for (const alias of (pkgMeta.aliases || [])) {
164
+ const aliasLower = alias.toLowerCase();
165
+ if (!installedBins.includes(aliasLower) && entries.length > 0) {
166
+ const PrimaryCmd = entries[0].Cmd;
167
+ class AliasCommand extends PrimaryCmd {
168
+ static get name() { return aliasLower; }
169
+ get name() { return aliasLower; }
170
+ }
171
+ this._installBin(pathDir, aliasLower, AliasCommand);
172
+ installedBins.push(aliasLower);
173
+ }
174
+ }
175
+
176
+ return installedBins;
177
+ }
178
+
179
+ _installBin(pathDir, binName, Cmd) {
180
+ const location = `${pathDir}/${binName}`;
181
+ this.context.fs.addFiles({ [location]: Cmd });
182
+ this.context.fs.setMode(location, 0o555);
183
+ }
184
+
185
+ _removeBin(pathDir, binName) {
186
+ const location = `${pathDir}/${binName.toLowerCase()}`;
187
+ if (this.context.fs._deleteByAbsolutePath) {
188
+ this.context.fs._deleteByAbsolutePath(location);
189
+ this.context.fs._triggerChange();
190
+ } else {
191
+ try { this.context.fs.deleteFileByPath(location); } catch { /* ignore */ }
192
+ }
193
+ }
194
+
195
+ _restoreCommands() {
196
+ const state = this._readState();
197
+ const registry = this._getRegistry();
198
+ for (const [pkgName, record] of Object.entries(state.packages)) {
199
+ const meta = registry[pkgName] || record;
200
+ if (meta) {
201
+ try {
202
+ this._registerPackageIntoContext(meta);
203
+ } catch {
204
+ // ignore
205
+ }
206
+ }
207
+ }
208
+ }
209
+
210
+ async run() {
211
+ const args = [...(this.arguments || [])];
212
+ if (args.length === 0 || args.includes('--help') || args.includes('-h') || args[0] === 'help') {
213
+ this._printHelp();
214
+ return;
215
+ }
216
+
217
+ if (args.includes('--version') || args.includes('-v')) {
218
+ this.stdOut = 'wbt 1.1.0 (Web Binary Tool for brsh)';
219
+ return;
220
+ }
221
+
222
+ const subcmd = args.shift().toLowerCase();
223
+
224
+ switch (subcmd) {
225
+ case 'install':
226
+ case 'add':
227
+ await this._handleInstall(args);
228
+ break;
229
+ case 'remove':
230
+ case 'uninstall':
231
+ case 'purge':
232
+ await this._handleRemove(args);
233
+ break;
234
+ case 'list':
235
+ this._handleList(args);
236
+ break;
237
+ case 'search':
238
+ this._handleSearch(args);
239
+ break;
240
+ case 'show':
241
+ case 'info':
242
+ this._handleShow(args);
243
+ break;
244
+ case 'update':
245
+ await this._handleUpdate(args);
246
+ break;
247
+ case 'run':
248
+ await this._handleRun(args);
249
+ break;
250
+ case 'services':
251
+ case 'daemons':
252
+ case 'ps':
253
+ await this._handleServices(args);
254
+ break;
255
+ default:
256
+ this.stdErr = `E: Invalid operation ${subcmd}`;
257
+ this.stdErr = `Run 'wbt --help' for usage information.`;
258
+ this.exitCode = 100;
259
+ }
260
+ }
261
+
262
+ async _handleInstall(args) {
263
+ const flags = [];
264
+ const positional = [];
265
+ let asName = null;
266
+ for (let i = 0; i < args.length; i++) {
267
+ const a = args[i];
268
+ if (a === '--as' && i + 1 < args.length) {
269
+ asName = args[++i];
270
+ } else if (a.startsWith('--as=')) {
271
+ asName = a.slice(5);
272
+ } else if (a.startsWith('-')) {
273
+ flags.push(a);
274
+ } else {
275
+ positional.push(a);
276
+ }
277
+ }
278
+ const quiet = flags.includes('-q') || flags.includes('--quiet');
279
+ const forceGeneric = flags.includes('--generic') || flags.includes('--npm');
280
+
281
+ if (positional.length === 0) {
282
+ this.stdErr = 'E: Specify at least one package to install';
283
+ this.exitCode = 1;
284
+ return;
285
+ }
286
+
287
+ const isUrl = (s) => /^(https?:\/\/|data:)/i.test(s);
288
+ const deriveUrlBinName = (url) => (
289
+ url.startsWith('data:')
290
+ ? 'custom-wasm'
291
+ : (url.split('/').pop().split('?')[0].replace(/\.(wasm|wat|mjs|js)$/i, '') || 'custom-wasm')
292
+ );
293
+
294
+ const registry = this._getRegistry();
295
+ const state = this._readState();
296
+ let printedHeader = false;
297
+
298
+ for (let i = 0; i < positional.length; i++) {
299
+ const rawName = positional[i];
300
+
301
+ // Case A: `<name> <url>` pair (current token is not a URL, next token is a URL)
302
+ if (!isUrl(rawName) && i + 1 < positional.length && isUrl(positional[i + 1])) {
303
+ const url = positional[++i];
304
+ const pkgName = (asName || rawName).toLowerCase();
305
+ await this._installCustomUrl(pkgName, url, quiet, state);
306
+ if (this.exitCode) return;
307
+ continue;
308
+ }
309
+
310
+ // Case B: standalone `<url>` (with optional `--as <name>`)
311
+ if (isUrl(rawName)) {
312
+ const url = rawName;
313
+ const pkgName = (asName || deriveUrlBinName(url)).toLowerCase();
314
+ await this._installCustomUrl(pkgName, url, quiet, state);
315
+ if (this.exitCode) return;
316
+ continue;
317
+ }
318
+
319
+ // Case C: registry package or `npm:<pkg>` / `esm:<pkg>`
320
+ if (!quiet && !printedHeader) {
321
+ this.stdOut = 'Reading package lists... Done';
322
+ this.stdOut = 'Building dependency tree... Done';
323
+ this.flush();
324
+ printedHeader = true;
325
+ }
326
+
327
+ const pkgName = resolvePackageName(rawName);
328
+ let pkgMeta = registry[pkgName];
329
+
330
+ // Generic npm/esm.sh resolution when `--npm` / `--generic` or `npm:<pkg>` is used
331
+ if (!pkgMeta && (forceGeneric || rawName.startsWith('npm:') || rawName.startsWith('esm:'))) {
332
+ const cleanSpec = rawName.replace(/^(npm|esm):/i, '');
333
+ const shortBin = (asName || cleanSpec.replace(/^@[^/]+\//, '').split('@')[0]).toLowerCase();
334
+ pkgMeta = {
335
+ name: shortBin,
336
+ bin: shortBin,
337
+ version: 'latest',
338
+ description: `Dynamic WASM/ESM package from https://esm.sh/${cleanSpec}`,
339
+ cdnUrl: `https://esm.sh/${cleanSpec}`,
340
+ type: 'generic-runtime'
341
+ };
342
+ }
343
+
344
+ if (!pkgMeta) {
345
+ this.stdErr = `E: Unable to locate package ${rawName}`;
346
+ this.exitCode = 100;
347
+ return;
348
+ }
349
+
350
+ if (state.packages[pkgMeta.name] && !flags.includes('--reinstall') && !flags.includes('-f')) {
351
+ if (!quiet) {
352
+ this.stdOut = `${pkgMeta.name} is already the newest version (${pkgMeta.version}).`;
353
+ }
354
+ continue;
355
+ }
356
+
357
+ if (!quiet) {
358
+ this.stdOut = `Get:1 ${pkgMeta.cdnUrl} ${pkgMeta.name} ${pkgMeta.version} [${pkgMeta.size || 'WASM'}]`;
359
+ this.stdOut = `Unpacking ${pkgMeta.name} (${pkgMeta.version}) ...`;
360
+ this.flush();
361
+ }
362
+
363
+ // Optional eager preload when `--preload` is passed
364
+ if (flags.includes('--preload')) {
365
+ const cfg = this.constructor._config || {};
366
+ const { loadModule } = require('./utils');
367
+ try {
368
+ await loadModule(pkgMeta.name, pkgMeta.cdnUrl, cfg.moduleLoader);
369
+ } catch (err) {
370
+ this.stdErr = `E: Failed to fetch ${pkgMeta.name}: ${err.message || err}`;
371
+ this.exitCode = 1;
372
+ return;
373
+ }
374
+ }
375
+
376
+ const bins = this._registerPackageIntoContext(pkgMeta);
377
+ state.packages[pkgMeta.name] = {
378
+ name: pkgMeta.name,
379
+ bin: pkgMeta.bin,
380
+ bins,
381
+ aliases: pkgMeta.aliases || [],
382
+ version: pkgMeta.version,
383
+ description: pkgMeta.description,
384
+ cdnUrl: pkgMeta.cdnUrl,
385
+ type: pkgMeta.type,
386
+ adapter: pkgMeta.adapter,
387
+ repl: pkgMeta.repl,
388
+ installedAt: new Date().toISOString()
389
+ };
390
+
391
+ if (!quiet) {
392
+ this.stdOut = `Setting up ${pkgMeta.name} (${pkgMeta.version}) -> /bin/${bins.join(', /bin/')} ...`;
393
+ }
394
+ }
395
+
396
+ this._writeState(state);
397
+ }
398
+
399
+ async _installCustomUrl(pkgName, url, quiet = false, existingState = null) {
400
+ // If URL is an ESM JS module (.mjs / .js or esm.sh URL without .wasm/.wat), wrap with GenericWasmCommand
401
+ const isBinaryWasmOrWat = /\.(wasm|wat)(\?.*)?$/i.test(url);
402
+ if (!isBinaryWasmOrWat && (/^https?:\/\/esm\.sh\//i.test(url) || /\.(mjs|js)(\?.*)?$/i.test(url))) {
403
+ const pkgMeta = {
404
+ name: pkgName,
405
+ bin: pkgName,
406
+ bins: [pkgName],
407
+ version: 'custom-esm',
408
+ description: `Custom ESM/WASM module from ${url}`,
409
+ cdnUrl: url,
410
+ type: 'generic-runtime',
411
+ installedAt: new Date().toISOString()
412
+ };
413
+ this._registerPackageIntoContext(pkgMeta);
414
+ const state = existingState || this._readState();
415
+ state.packages[pkgName] = pkgMeta;
416
+ this._writeState(state);
417
+ if (!quiet) {
418
+ this.stdOut = `Setting up ${pkgName} (generic runtime) -> /bin/${pkgName} ...`;
419
+ }
420
+ return;
421
+ }
422
+
423
+ const cfg = this.constructor._config || {};
424
+ const fetchFn = cfg.fetch || (typeof fetch === 'function' ? fetch : null);
425
+ if (!fetchFn) {
426
+ this.stdErr = `E: fetch is not available in this environment`;
427
+ this.exitCode = 1;
428
+ return;
429
+ }
430
+
431
+ if (!quiet) {
432
+ this.stdOut = `Get:1 ${url} ${pkgName}`;
433
+ this.flush();
434
+ }
435
+
436
+ // Rewrite github.com blob/raw URLs to raw.githubusercontent.com (which serves CORS headers)
437
+ const normalizedUrl = url.replace(
438
+ /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/(?:blob|raw)\/([^/]+)\/(.+)$/i,
439
+ 'https://raw.githubusercontent.com/$1/$2/$3/$4'
440
+ );
441
+
442
+ let res;
443
+ try {
444
+ res = await fetchFn(normalizedUrl);
445
+ } catch (err) {
446
+ // GitHub `/releases/download/...` redirects to objects.githubusercontent.com without CORS headers in browsers;
447
+ // fall back to a CORS proxy if direct browser fetch throws a network/CORS TypeError
448
+ if (/^https?:\/\/github\.com\/[^/]+\/[^/]+\/releases\/download\//i.test(normalizedUrl)) {
449
+ try {
450
+ res = await fetchFn(`https://corsproxy.io/?${encodeURIComponent(normalizedUrl)}`);
451
+ } catch (_proxyErr) {
452
+ this.stdErr = `E: Failed to fetch ${url} (GitHub Releases blocks browser CORS requests; host the .wasm on jsDelivr/unpkg/raw.githubusercontent.com): ${err.message || err}`;
453
+ this.exitCode = 1;
454
+ return;
455
+ }
456
+ } else {
457
+ this.stdErr = `E: Failed to fetch ${url}: ${err.message || err}`;
458
+ this.exitCode = 1;
459
+ return;
460
+ }
461
+ }
462
+
463
+ if (!res || !res.ok) {
464
+ this.stdErr = `E: HTTP ${res ? res.status : 'error'} fetching ${url}`;
465
+ this.exitCode = 1;
466
+ return;
467
+ }
468
+
469
+ const isWat = url.endsWith('.wat');
470
+ const ext = isWat ? '.wat' : '.wasm';
471
+ const wasmPath = `/var/lib/wbt/wasm/${pkgName}${ext}`;
472
+
473
+ if (isWat) {
474
+ const text = await res.text();
475
+ this.context.fs._setFileRaw(wasmPath, text, true);
476
+ } else {
477
+ const ab = await res.arrayBuffer();
478
+ writeBytesToFs(this.fs, wasmPath, new Uint8Array(ab), 'application/wasm');
479
+ }
480
+ this.context.fs.setMode(wasmPath, 0o755);
481
+
482
+ const pkgMeta = {
483
+ name: pkgName,
484
+ bin: pkgName,
485
+ bins: [pkgName],
486
+ version: 'custom',
487
+ description: `Custom WebAssembly binary from ${url}`,
488
+ cdnUrl: url,
489
+ type: 'custom-wasm',
490
+ wasmPath,
491
+ installedAt: new Date().toISOString()
492
+ };
493
+
494
+ this._registerPackageIntoContext(pkgMeta);
495
+ const state = existingState || this._readState();
496
+ state.packages[pkgName] = pkgMeta;
497
+ this._writeState(state);
498
+
499
+ if (!quiet) {
500
+ this.stdOut = `Setting up ${pkgName} (custom) -> /bin/${pkgName} ...`;
501
+ }
502
+ }
503
+
504
+ async _handleRemove(args) {
505
+ const positional = args.filter(a => !a.startsWith('-'));
506
+ if (positional.length === 0) {
507
+ this.stdErr = 'E: Specify at least one package to remove';
508
+ this.exitCode = 1;
509
+ return;
510
+ }
511
+
512
+ const state = this._readState();
513
+ const pathDir = this.context.getVar('PATH') || '/bin';
514
+
515
+ for (const rawName of positional) {
516
+ const pkgName = resolvePackageName(rawName);
517
+ const record = state.packages[pkgName] || state.packages[rawName.toLowerCase()];
518
+
519
+ if (!record) {
520
+ this.stdErr = `E: Package '${rawName}' is not installed, so not removed`;
521
+ this.exitCode = 1;
522
+ return;
523
+ }
524
+
525
+ const binsToRemove = record.bins || [record.bin || record.name, ...(record.aliases || [])];
526
+ for (const b of binsToRemove) {
527
+ this._removeBin(pathDir, b);
528
+ }
529
+
530
+ if (record.wasmPath) {
531
+ try { this.context.fs.deleteFileByPath(record.wasmPath); } catch { /* ignore */ }
532
+ }
533
+
534
+ delete state.packages[record.name];
535
+ this.stdOut = `Removing ${record.name} (${record.version}) ...`;
536
+ }
537
+
538
+ this._writeState(state);
539
+ }
540
+
541
+ _handleList(args) {
542
+ const installedOnly = args.includes('--installed') || args.includes('-i');
543
+ const registry = this._getRegistry();
544
+ const state = this._readState();
545
+
546
+ this.stdOut = 'Listing...';
547
+
548
+ const names = installedOnly
549
+ ? Object.keys(state.packages).sort()
550
+ : Array.from(new Set([...Object.keys(registry), ...Object.keys(state.packages)])).sort();
551
+
552
+ for (const name of names) {
553
+ const reg = registry[name];
554
+ const inst = state.packages[name];
555
+ const meta = inst || reg;
556
+ if (!meta) continue;
557
+
558
+ const statusTag = inst ? '[installed]' : '[available]';
559
+ const binLabel = meta.bin && meta.bin !== meta.name ? ` (bin: ${meta.bin})` : '';
560
+ this.stdOut = `${meta.name}/wasm ${meta.version} wasm ${statusTag}${binLabel} - ${meta.description || ''}`;
561
+ }
562
+ }
563
+
564
+ _handleSearch(args) {
565
+ const query = args.filter(a => !a.startsWith('-')).join(' ').toLowerCase();
566
+ const registry = this._getRegistry();
567
+ const state = this._readState();
568
+
569
+ this.stdOut = 'Sorting... Done';
570
+ this.stdOut = 'Full Text Search... Done';
571
+
572
+ const entries = Object.values(registry).filter(pkg => {
573
+ if (!query) return true;
574
+ return (
575
+ pkg.name.toLowerCase().includes(query) ||
576
+ (pkg.bin && pkg.bin.toLowerCase().includes(query)) ||
577
+ (pkg.aliases && pkg.aliases.some(a => a.toLowerCase().includes(query))) ||
578
+ (pkg.description && pkg.description.toLowerCase().includes(query)) ||
579
+ (pkg.details && pkg.details.toLowerCase().includes(query))
580
+ );
581
+ });
582
+
583
+ for (const pkg of entries) {
584
+ const inst = state.packages[pkg.name] ? ' [installed]' : '';
585
+ this.stdOut = `${pkg.name}/wasm ${pkg.version} wasm${inst}`;
586
+ this.stdOut = ` ${pkg.description}`;
587
+ }
588
+ }
589
+
590
+ _handleShow(args) {
591
+ const rawName = args.find(a => !a.startsWith('-'));
592
+ if (!rawName) {
593
+ this.stdErr = 'E: No packages found — specify a package name';
594
+ this.exitCode = 1;
595
+ return;
596
+ }
597
+
598
+ const pkgName = resolvePackageName(rawName);
599
+ const registry = this._getRegistry();
600
+ const state = this._readState();
601
+ const meta = state.packages[pkgName] || registry[pkgName];
602
+
603
+ if (!meta) {
604
+ this.stdErr = `E: No packages found matching ${rawName}`;
605
+ this.exitCode = 100;
606
+ return;
607
+ }
608
+
609
+ const full = Object.assign({}, registry[pkgName] || {}, meta);
610
+ const isInstalled = Boolean(state.packages[full.name]);
611
+
612
+ this.stdOut = `Package: ${full.name}`;
613
+ this.stdOut = `Version: ${full.version}`;
614
+ this.stdOut = `State: ${isInstalled ? 'installed' : 'not installed'}`;
615
+ this.stdOut = `Binary: ${full.bin || full.name}`;
616
+ if (full.aliases && full.aliases.length > 0) {
617
+ this.stdOut = `Aliases: ${full.aliases.join(', ')}`;
618
+ }
619
+ if (full.size) {
620
+ this.stdOut = `Download-Size: ${full.size}`;
621
+ }
622
+ if (full.cdnUrl) {
623
+ this.stdOut = `APT-Sources: ${full.cdnUrl}`;
624
+ }
625
+ if (full.homepage) {
626
+ this.stdOut = `Homepage: ${full.homepage}`;
627
+ }
628
+ this.stdOut = `Description: ${full.description || ''}`;
629
+ if (full.details) {
630
+ this.stdOut = ` ${full.details}`;
631
+ }
632
+ }
633
+
634
+ async _handleUpdate() {
635
+ const cfg = this.constructor._config || {};
636
+ const sources = cfg.sources || [];
637
+ const fetchFn = cfg.fetch || (typeof fetch === 'function' ? fetch : null);
638
+
639
+ const mergedRemote = {};
640
+ let idx = 1;
641
+ this.stdOut = 'Hit:1 https://registry.brsh.dev/wbt wasm InRelease';
642
+
643
+ for (const srcUrl of sources) {
644
+ idx++;
645
+ if (!fetchFn) continue;
646
+ try {
647
+ const res = await fetchFn(srcUrl);
648
+ if (res && res.ok) {
649
+ const data = await res.json();
650
+ Object.assign(mergedRemote, data);
651
+ this.stdOut = `Get:${idx} ${srcUrl} Packages`;
652
+ }
653
+ } catch (err) {
654
+ this.stdErr = `W: Failed to fetch ${srcUrl}: ${err.message || err}`;
655
+ }
656
+ }
657
+
658
+ if (Object.keys(mergedRemote).length > 0) {
659
+ this.context.fs._setFileRaw(`${CACHE_DIR}/remote-registry.json`, JSON.stringify(mergedRemote, null, 2), true);
660
+ }
661
+
662
+ // Also ensure any installed packages in state are registered in PATH
663
+ this._restoreCommands();
664
+
665
+ const registry = this._getRegistry();
666
+ this.stdOut = `Reading package lists... Done (${Object.keys(registry).length} packages available)`;
667
+ }
668
+
669
+ async _handleRun(args) {
670
+ if (args.length === 0) {
671
+ this.stdErr = 'E: Specify a package to run (e.g. wbt run sqlite3 --version)';
672
+ this.exitCode = 1;
673
+ return;
674
+ }
675
+ const rawName = args.shift();
676
+ const pkgName = resolvePackageName(rawName);
677
+ const registry = this._getRegistry();
678
+ const state = this._readState();
679
+ let pkgMeta = state.packages[pkgName] || registry[pkgName];
680
+
681
+ if (!pkgMeta && (rawName.startsWith('npm:') || rawName.startsWith('esm:'))) {
682
+ const cleanSpec = rawName.replace(/^(npm|esm):/i, '');
683
+ const shortBin = cleanSpec.replace(/^@[^/]+\//, '').split('@')[0].toLowerCase();
684
+ pkgMeta = {
685
+ name: shortBin,
686
+ bin: shortBin,
687
+ version: 'latest',
688
+ cdnUrl: `https://esm.sh/${cleanSpec}`,
689
+ type: 'generic-runtime'
690
+ };
691
+ }
692
+
693
+ if (!pkgMeta) {
694
+ this.stdErr = `E: Unable to locate package ${rawName}`;
695
+ this.exitCode = 100;
696
+ return;
697
+ }
698
+
699
+ const entries = this._buildCommandsForPackage(pkgMeta);
700
+ // Find matching entry if user specified e.g. `wbt run asrun` or `wbt run wasm2wat`
701
+ const matched = entries.find(e => e.bin === rawName.toLowerCase()) || entries[0];
702
+ const Cmd = matched.Cmd;
703
+
704
+ const instance = new Cmd(args, this.context);
705
+ if (instance.requiresFilesystem) {
706
+ instance.fs = this.context.fs.sandbox();
707
+ }
708
+ if (this.stdin !== undefined) {
709
+ instance.stdin = this.stdin;
710
+ }
711
+ const res = await instance.runCommand();
712
+ for (const line of res.getStdOutput()) {
713
+ if (line.type === 'out') this.stdOut = line.string;
714
+ else if (line.type === 'err') this.stdErr = line.string;
715
+ }
716
+ this.exitCode = res.getExitCode();
717
+ }
718
+
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
+ _printHelp() {
744
+ [
745
+ 'wbt 1.1.0 — Web Binary Tool (WASM binary manager & runtime for brsh)',
746
+ 'Usage: wbt [options] command [package ...]',
747
+ '',
748
+ 'Commands:',
749
+ ' install <pkg> [url] Install a WASM binary from registry, npm:<pkg>, or a custom URL',
750
+ ' remove <pkg> Remove an installed WASM binary',
751
+ ' update Update package index and restore installed binaries',
752
+ ' list [--installed] List available or installed WASM binaries',
753
+ ' search <query> Search available WASM binaries by name or description',
754
+ ' show <pkg> Show detailed information about a package',
755
+ ' run <pkg> [args...] Run a WASM binary without permanently installing it',
756
+ ' services [stop <id>] List or stop running WASM background server daemons',
757
+ '',
758
+ 'Curated WASM Packages:',
759
+ ' pglite WASM PostgreSQL database, REPL & daemon (pglite, psql, pg_ctl)',
760
+ ' sqlite3 SQLite3 compiled to WebAssembly (sqlite3, sqlite)',
761
+ ' assemblyscript AssemblyScript compiler & ts-node style runtime (asc, asrun, asnode)',
762
+ ' jq Command-line JSON processor (jq)',
763
+ ' python3 CPython 3.12 via Pyodide (python3, python, py)',
764
+ ' duckdb DuckDB analytical SQL OLAP engine (duckdb)',
765
+ ' graphviz Graphviz DOT diagram compiler (dot)',
766
+ ' ffmpeg FFmpeg multimedia transcoder (ffmpeg)',
767
+ ' wabt WebAssembly Binary Toolkit (wat2wasm, wasm2wat)',
768
+ ' quickjs Sandboxed QuickJS JavaScript engine (qjs)',
769
+ ' lua Lua 5.4 WebAssembly interpreter (lua)'
770
+ ].forEach(l => { this.stdOut = l; });
771
+ }
772
+ }
773
+
774
+ module.exports = Wbt;
775
+ module.exports.Wbt = Wbt;
776
+ module.exports.DEFAULT_REGISTRY = DEFAULT_REGISTRY;
777
+ module.exports.daemonManager = daemonManager;
778
+ module.exports.createGenericWasmCommand = createGenericWasmCommand;
779
+ module.exports.createReplWasmCommand = createReplWasmCommand;