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/test/wbt.test.js CHANGED
@@ -4,8 +4,7 @@ import { createShell, run } from './helpers.js';
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
6
  const Wbt = require('../lib/wbt/index.js');
7
- const { daemonManager } = require('../lib/wbt/index.js');
8
- const { pgliteInstances } = require('../lib/wbt/packages/pglite.js');
7
+ const { wllamaInstances } = require('../lib/wbt/packages/wllama.js');
9
8
 
10
9
  // Minimal valid WASM binary that exits cleanly with 0 via _start:
11
10
  // (module (func (export "_start")))
@@ -123,115 +122,6 @@ function createMockSqlJs() {
123
122
  };
124
123
  }
125
124
 
126
- /**
127
- * In-memory mock implementation of @electric-sql/pglite for deterministic tests.
128
- */
129
- function createMockPglite() {
130
- class MockPGlite {
131
- constructor(dataDir) {
132
- this.dataDir = dataDir || 'memory://';
133
- this._tables = {};
134
- this.waitReady = Promise.resolve();
135
- }
136
-
137
- static async create(dataDir) {
138
- return new MockPGlite(dataDir);
139
- }
140
-
141
- async exec(sql) {
142
- const results = [];
143
- const statements = sql
144
- .split(';')
145
- .map(s => s.trim())
146
- .filter(Boolean);
147
-
148
- for (const stmt of statements) {
149
- if (/FROM\s+pg_catalog\.pg_tables/i.test(stmt)) {
150
- const rows = Object.keys(this._tables).map(t => ({
151
- schema: 'public',
152
- name: t,
153
- owner: 'postgres'
154
- }));
155
- results.push({
156
- fields: [{ name: 'schema' }, { name: 'name' }, { name: 'owner' }],
157
- rows
158
- });
159
- continue;
160
- }
161
-
162
- const createMatch = stmt.match(/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)\s*\((.+)\)/i);
163
- if (createMatch) {
164
- const tbl = createMatch[1];
165
- const cols = createMatch[2].split(',').map(c => c.trim().split(/\s+/)[0]);
166
- this._tables[tbl] = { columns: cols, rows: [] };
167
- results.push({ fields: [], rows: [], affectedRows: 0 });
168
- continue;
169
- }
170
-
171
- const insertMatch = stmt.match(/^INSERT\s+INTO\s+(\w+)(?:\s*\(([^)]+)\))?\s+VALUES\s*\((.+)\)/i);
172
- if (insertMatch) {
173
- const tbl = insertMatch[1];
174
- if (!this._tables[tbl]) throw new Error(`relation "${tbl}" does not exist`);
175
- const vals = insertMatch[3].split(',').map(v => {
176
- const s = v.trim();
177
- if ((s.startsWith("'") && s.endsWith("'")) || (s.startsWith('"') && s.endsWith('"'))) {
178
- return s.slice(1, -1);
179
- }
180
- const n = Number(s);
181
- return Number.isNaN(n) ? s : n;
182
- });
183
- const rowObj = {};
184
- this._tables[tbl].columns.forEach((c, idx) => { rowObj[c] = vals[idx]; });
185
- this._tables[tbl].rows.push(rowObj);
186
- results.push({ fields: [], rows: [], affectedRows: 1 });
187
- continue;
188
- }
189
-
190
- const selectTableMatch = stmt.match(/^SELECT\s+(.+)\s+FROM\s+(\w+)/i);
191
- if (selectTableMatch) {
192
- const tbl = selectTableMatch[2];
193
- if (!this._tables[tbl]) throw new Error(`relation "${tbl}" does not exist`);
194
- const tableObj = this._tables[tbl];
195
- results.push({
196
- fields: tableObj.columns.map(c => ({ name: c })),
197
- rows: tableObj.rows
198
- });
199
- continue;
200
- }
201
-
202
- const selectExprMatch = stmt.match(/^SELECT\s+(.+)/i);
203
- if (selectExprMatch) {
204
- const exprs = selectExprMatch[1].split(',').map(e => e.trim());
205
- const fields = [];
206
- const rowObj = {};
207
- for (const expr of exprs) {
208
- const asMatch = expr.match(/^(.+?)\s+AS\s+(\w+)$/i);
209
- const rawExpr = asMatch ? asMatch[1].trim() : expr;
210
- const colName = asMatch ? asMatch[2] : '?column?';
211
- fields.push({ name: colName });
212
- if ((rawExpr.startsWith("'") && rawExpr.endsWith("'")) || (rawExpr.startsWith('"') && rawExpr.endsWith('"'))) {
213
- rowObj[colName] = rawExpr.slice(1, -1);
214
- } else if (/^[\d\s+\-*/%()]+$/.test(rawExpr)) {
215
- rowObj[colName] = Function(`return (${rawExpr})`)();
216
- } else {
217
- rowObj[colName] = rawExpr;
218
- }
219
- }
220
- results.push({ fields, rows: [rowObj] });
221
- continue;
222
- }
223
-
224
- throw new Error(`syntax error at or near "${stmt}"`);
225
- }
226
- return results;
227
- }
228
-
229
- async close() {}
230
- }
231
-
232
- return { PGlite: MockPGlite };
233
- }
234
-
235
125
  /**
236
126
  * Mock AssemblyScript CLI (`assemblyscript/asc`).
237
127
  */
@@ -465,11 +355,147 @@ function createMockEmscriptenCowsay() {
465
355
  };
466
356
  }
467
357
 
358
+ /**
359
+ * In-memory mock implementation of @wllama/wllama v3 for deterministic tests.
360
+ */
361
+ function createMockWllama() {
362
+ class MockWllama {
363
+ constructor(pathConfig, config = {}) {
364
+ this.pathConfig = pathConfig;
365
+ this.config = config;
366
+ this._loaded = false;
367
+ this._loadParams = {};
368
+ this._modelSource = null;
369
+ this.modelManager = {
370
+ getModels: async () => []
371
+ };
372
+ }
373
+
374
+ static getLibllamaVersion() {
375
+ return 'b6327-4d74393';
376
+ }
377
+
378
+ isSupportWebGPU() {
379
+ return true;
380
+ }
381
+
382
+ isMultithread() {
383
+ return true;
384
+ }
385
+
386
+ getNumThreads() {
387
+ return 4;
388
+ }
389
+
390
+ isModelLoaded() {
391
+ return this._loaded;
392
+ }
393
+
394
+ getModelMetadata() {
395
+ return {
396
+ hparams: { nVocab: 32000, nCtxTrain: 4096, nEmbd: 2048, nLayer: 22 },
397
+ meta: { 'general.name': 'TinyLlama-1.1B' }
398
+ };
399
+ }
400
+
401
+ async loadModel(blobs, params = {}) {
402
+ this._loaded = true;
403
+ this._loadParams = params;
404
+ this._modelSource = blobs.map(b => b.name || 'blob.gguf').join('+');
405
+ }
406
+
407
+ async loadModelFromUrl(urlOrObj, params = {}) {
408
+ if (typeof params.progressCallback === 'function') {
409
+ params.progressCallback({ loaded: 524288, total: 1048576 });
410
+ params.progressCallback({ loaded: 1048576, total: 1048576 });
411
+ }
412
+ this._loaded = true;
413
+ this._loadParams = params;
414
+ this._modelSource = typeof urlOrObj === 'string' ? urlOrObj : urlOrObj.url;
415
+ }
416
+
417
+ async loadModelFromHF(hfOpts, params = {}) {
418
+ if (typeof params.progressCallback === 'function') {
419
+ params.progressCallback({ loaded: 524288, total: 1048576 });
420
+ params.progressCallback({ loaded: 1048576, total: 1048576 });
421
+ }
422
+ this._loaded = true;
423
+ this._loadParams = params;
424
+ this._modelSource = `hf:${hfOpts.repo}:${hfOpts.quant || 'Q4_K_M'}`;
425
+ }
426
+
427
+ async getLoadedBlob() {
428
+ return new Uint8Array([0x47, 0x47, 0x55, 0x46, 0x03, 0x00, 0x00, 0x00]);
429
+ }
430
+
431
+ async createChatCompletion(opts) {
432
+ const messages = opts.messages || [];
433
+ const sysMsg = messages.find(m => m.role === 'system');
434
+ const userMsgs = messages.filter(m => m.role === 'user').map(m => m.content);
435
+ const prefix = sysMsg ? `[sys:${sysMsg.content}] ` : '';
436
+ const gpuTag = this._loadParams.n_gpu_layers === 0 ? 'CPU' : 'WebGPU';
437
+ const reply = `${prefix}Reply(${gpuTag},turns=${userMsgs.length}): ${userMsgs[userMsgs.length - 1] || ''}`;
438
+ return {
439
+ id: 'chatcmpl-wllama',
440
+ object: 'chat.completion',
441
+ choices: [
442
+ {
443
+ index: 0,
444
+ message: { role: 'assistant', content: reply },
445
+ finish_reason: 'stop'
446
+ }
447
+ ]
448
+ };
449
+ }
450
+
451
+ async createCompletion(opts) {
452
+ return {
453
+ id: 'cmpl-wllama',
454
+ object: 'text_completion',
455
+ choices: [
456
+ {
457
+ index: 0,
458
+ text: `${opts.prompt} [completed]`,
459
+ finish_reason: 'stop'
460
+ }
461
+ ]
462
+ };
463
+ }
464
+
465
+ async createEmbedding(opts) {
466
+ const text = String(opts.input || '');
467
+ return {
468
+ object: 'list',
469
+ data: [
470
+ {
471
+ object: 'embedding',
472
+ index: 0,
473
+ embedding: [text.length, 0.25, 0.5, 0.75]
474
+ }
475
+ ]
476
+ };
477
+ }
478
+
479
+ async testBackendOps() {
480
+ return { retcode: 0, success: true };
481
+ }
482
+
483
+ async exit() {
484
+ this._loaded = false;
485
+ }
486
+ }
487
+
488
+ return {
489
+ Wllama: MockWllama,
490
+ LoggerWithoutDebug: console
491
+ };
492
+ }
493
+
468
494
  function createTestWbt() {
469
495
  return Wbt.configure({
470
496
  moduleLoader: async (pkgName) => {
471
497
  if (pkgName === 'sql.js' || pkgName === 'sqlite3') return createMockSqlJs();
472
- if (pkgName === '@electric-sql/pglite' || pkgName === 'pglite') return createMockPglite();
498
+ if (pkgName === '@wllama/wllama' || pkgName === 'wllama') return createMockWllama();
473
499
  if (pkgName === 'assemblyscript/asc' || pkgName === 'assemblyscript') return createMockAsc();
474
500
  if (pkgName === 'quickjs-emscripten' || pkgName === 'quickjs') return createMockQuickJs();
475
501
  if (pkgName === 'wasmoon' || pkgName === 'lua') return createMockLua();
@@ -537,8 +563,6 @@ describe('WBT CLI subcommands (list, search, show, install, remove, update)', ()
537
563
  let shell;
538
564
 
539
565
  beforeEach(async () => {
540
- await daemonManager.stopAll();
541
- pgliteInstances.clear();
542
566
  shell = await createShell({ filesystem: { home: {} } });
543
567
  shell.context.setCommand(createTestWbt());
544
568
  });
@@ -548,7 +572,6 @@ describe('WBT CLI subcommands (list, search, show, install, remove, update)', ()
548
572
  expect(exitCode).toBe(0);
549
573
  const text = output.join('\n');
550
574
  expect(text).toContain('Web Binary Tool');
551
- expect(text).toContain('pglite');
552
575
  expect(text).toContain('sqlite3');
553
576
  expect(text).toContain('assemblyscript');
554
577
  expect(text).toContain('jq');
@@ -561,9 +584,9 @@ describe('WBT CLI subcommands (list, search, show, install, remove, update)', ()
561
584
  it('lists available packages with `wbt list` and installed packages with `wbt list --installed`', async () => {
562
585
  const allRes = await run(shell, 'wbt list');
563
586
  expect(allRes.exitCode).toBe(0);
564
- expect(allRes.output.join('\n')).toContain('pglite/wasm');
565
587
  expect(allRes.output.join('\n')).toContain('sqlite3/wasm');
566
588
  expect(allRes.output.join('\n')).toContain('assemblyscript/wasm');
589
+ expect(allRes.output.join('\n')).toContain('duckdb/wasm');
567
590
 
568
591
  const emptyInstalled = await run(shell, 'wbt list --installed');
569
592
  expect(emptyInstalled.exitCode).toBe(0);
@@ -576,22 +599,22 @@ describe('WBT CLI subcommands (list, search, show, install, remove, update)', ()
576
599
  });
577
600
 
578
601
  it('searches packages by keyword with `wbt search`', async () => {
579
- const { output, exitCode } = await run(shell, 'wbt search postgres');
602
+ const { output, exitCode } = await run(shell, 'wbt search json');
580
603
  expect(exitCode).toBe(0);
581
- expect(output.join('\n')).toContain('pglite/wasm');
604
+ expect(output.join('\n')).toContain('jq/wasm');
582
605
  expect(output.join('\n')).not.toContain('lua/wasm');
583
606
  });
584
607
 
585
608
  it('shows detailed package metadata with `wbt show`', async () => {
586
- const { output, exitCode } = await run(shell, 'wbt show pglite');
609
+ const { output, exitCode } = await run(shell, 'wbt show sqlite3');
587
610
  expect(exitCode).toBe(0);
588
611
  const text = output.join('\n');
589
- expect(text).toContain('Package: pglite');
612
+ expect(text).toContain('Package: sqlite3');
590
613
  expect(text).toContain('State: not installed');
591
- expect(text).toContain('Binary: pglite');
614
+ expect(text).toContain('Binary: sqlite3');
592
615
 
593
- await run(shell, 'wbt install pglite');
594
- const afterShow = await run(shell, 'wbt show pglite');
616
+ await run(shell, 'wbt install sqlite3');
617
+ const afterShow = await run(shell, 'wbt show sqlite3');
595
618
  expect(afterShow.output.join('\n')).toContain('State: installed');
596
619
  });
597
620
 
@@ -692,83 +715,6 @@ describe('WBT SQLite3 WASM package (`sqlite3` / `sqlite`)', () => {
692
715
  });
693
716
  });
694
717
 
695
- describe('WBT PGlite WASM package (`pglite`, `psql`, `pg_ctl` & background server daemon)', () => {
696
- let shell;
697
-
698
- beforeEach(async () => {
699
- await daemonManager.stopAll();
700
- pgliteInstances.clear();
701
- shell = await createShell({ filesystem: { home: {} } });
702
- shell.context.setCommand(createTestWbt());
703
- await run(shell, 'wbt install pglite');
704
- });
705
-
706
- it('runs one-shot SQL queries with `pglite -c` or positional SQL', async () => {
707
- const { output, exitCode } = await run(shell, 'pglite -c "SELECT 7 * 6 AS product"');
708
- expect(exitCode).toBe(0);
709
- const text = output.join('\n');
710
- expect(text).toContain('product');
711
- expect(text).toContain('42');
712
- expect(text).toContain('(1 row)');
713
- });
714
-
715
- it('persists database state across commands when a data directory is given and supports `psql` alias', async () => {
716
- const initRes = await run(
717
- shell,
718
- 'pglite -d /home/pgdata -c "CREATE TABLE projects (id INT, title TEXT); INSERT INTO projects VALUES (1, \'Brsh\');"'
719
- );
720
- expect(initRes.exitCode).toBe(0);
721
-
722
- const queryRes = await run(
723
- shell,
724
- 'psql -d /home/pgdata -c "SELECT * FROM projects"'
725
- );
726
- expect(queryRes.exitCode).toBe(0);
727
- expect(queryRes.output.join('\n')).toContain('Brsh');
728
-
729
- const dtRes = await run(shell, 'psql -d /home/pgdata -c "\\dt"');
730
- expect(dtRes.exitCode).toBe(0);
731
- expect(dtRes.output.join('\n')).toContain('projects');
732
- });
733
-
734
- it('starts a background PGlite server daemon (`pglite serve` / `pg_ctl start`), serves HTTP SQL via `curl`, and stops cleanly', async () => {
735
- const startRes = await run(shell, 'pg_ctl start -D /home/pgdaemon -p 5432');
736
- expect(startRes.exitCode).toBe(0);
737
- expect(startRes.output.join('\n')).toContain('server started');
738
-
739
- // Verify `wbt services` lists the running daemon
740
- const svcRes = await run(shell, 'wbt services');
741
- expect(svcRes.exitCode).toBe(0);
742
- expect(svcRes.output.join('\n')).toContain('pglite');
743
- expect(svcRes.output.join('\n')).toContain('5432');
744
-
745
- // Query the live daemon over HTTP via `curl`!
746
- const curlStatus = await run(shell, 'curl -s http://localhost:5432/status');
747
- expect(curlStatus.exitCode).toBe(0);
748
- expect(curlStatus.output.join('\n')).toContain('"status":"ready"');
749
-
750
- // Create table & insert via HTTP POST to the daemon
751
- const curlCreate = await run(
752
- shell,
753
- 'curl -s -X POST -d "CREATE TABLE tasks (id INT, name TEXT); INSERT INTO tasks VALUES (1, \'DaemonTask\');" http://localhost:5432/query'
754
- );
755
- expect(curlCreate.exitCode).toBe(0);
756
-
757
- // Query via `psql` client (auto-connects to the running daemon on port 5432!)
758
- const psqlRes = await run(shell, 'psql -p 5432 -c "SELECT * FROM tasks"');
759
- expect(psqlRes.exitCode).toBe(0);
760
- expect(psqlRes.output.join('\n')).toContain('DaemonTask');
761
-
762
- // Stop the daemon with `pg_ctl stop`
763
- const stopRes = await run(shell, 'pg_ctl stop -p 5432');
764
- expect(stopRes.exitCode).toBe(0);
765
- expect(stopRes.output.join('\n')).toContain('server stopped');
766
-
767
- const statusAfter = await run(shell, 'pg_ctl status -p 5432');
768
- expect(statusAfter.exitCode).toBe(3);
769
- });
770
- });
771
-
772
718
  describe('WBT AssemblyScript compiler (`asc`) and JIT/AOT runtime (`asrun` / `asnode`)', () => {
773
719
  let shell;
774
720
 
@@ -914,11 +860,9 @@ describe('WBT interactive REPL mode', () => {
914
860
  let shell;
915
861
 
916
862
  beforeEach(async () => {
917
- await daemonManager.stopAll();
918
- pgliteInstances.clear();
919
863
  shell = await createShell({ filesystem: { home: {} } });
920
864
  shell.context.setCommand(createTestWbt());
921
- await run(shell, 'wbt install sqlite3 pglite');
865
+ await run(shell, 'wbt install sqlite3');
922
866
  });
923
867
 
924
868
  it('enters interactive REPL mode when `sqlite3` is invoked with no query and evaluates keystrokes until .exit', async () => {
@@ -953,32 +897,6 @@ describe('WBT interactive REPL mode', () => {
953
897
 
954
898
  expect(shell.context.fs.exists('/home/interactive.db')).toBe(true);
955
899
  });
956
-
957
- it('enters interactive REPL mode when `pglite` is invoked with no query and exits on Ctrl+D (^D)', async () => {
958
- let interactiveFired = false;
959
- shell.once('interactive', () => { interactiveFired = true; });
960
-
961
- const screens = [];
962
- const onOut = (line) => screens.push(line);
963
- shell.on('stdOut', onOut);
964
-
965
- const cmdPromise = shell.onCommand('pglite');
966
-
967
- await new Promise(r => setTimeout(r, 20));
968
- expect(interactiveFired).toBe(true);
969
-
970
- for (const ch of 'SELECT 123 AS val;') {
971
- shell.onInput(ch);
972
- }
973
- shell.onInput('Enter');
974
-
975
- await new Promise(r => setTimeout(r, 20));
976
- expect(screens[screens.length - 1]).toContain('123');
977
-
978
- shell.onInput('^D');
979
- await cmdPromise;
980
- shell.removeListener('stdOut', onOut);
981
- });
982
900
  });
983
901
 
984
902
  describe('Direct .wasm binary in /bin (without wbt) and standardized --help across all WASM bins', () => {
@@ -1010,11 +928,11 @@ describe('Direct .wasm binary in /bin (without wbt) and standardized --help acro
1010
928
  it('passes through native --help when a WASM binary implements it and falls back to standardized --help otherwise', async () => {
1011
929
  const shell = await createShell({ filesystem: { home: {} } });
1012
930
  shell.context.setCommand(createTestWbt());
1013
- await run(shell, 'wbt install jq python3 pglite npm:cowsay-wasm');
931
+ await run(shell, 'wbt install jq python3 npm:cowsay-wasm');
1014
932
  await run(shell, 'wbt install mywasm https://example.com/hello.wasm');
1015
933
 
1016
934
  // 1. Binaries without their own `--help` get the standardized fallback `--help` screen
1017
- for (const bin of ['python3', 'pglite', 'pg_ctl', 'cowsay-wasm', 'mywasm']) {
935
+ for (const bin of ['python3', 'cowsay-wasm', 'mywasm']) {
1018
936
  const { output, exitCode } = await run(shell, `${bin} --help`);
1019
937
  expect(exitCode).toBe(0);
1020
938
  const text = output.join('\n');
@@ -1081,4 +999,177 @@ describe('Direct .wasm binary in /bin (without wbt) and standardized --help acro
1081
999
  });
1082
1000
  });
1083
1001
 
1002
+ describe('WBT Wllama v3 WASM & WebGPU package (`wllama`, `llama`, `llama-cli`)', () => {
1003
+ let shell;
1004
+
1005
+ beforeEach(async () => {
1006
+ wllamaInstances.clear();
1007
+ shell = await createShell({
1008
+ filesystem: {
1009
+ home: {
1010
+ 'tinyllama.gguf': 'GGUF_MODEL_BINARY_BYTES',
1011
+ 'prompt.txt': 'Explain WebGPU in one sentence.'
1012
+ }
1013
+ }
1014
+ });
1015
+ shell.context.setCommand(createTestWbt());
1016
+ await run(shell, 'wbt install wllama');
1017
+ });
1018
+
1019
+ it('registers wllama, llama, and llama-cli binaries and supports --help / --version', async () => {
1020
+ for (const bin of ['wllama', 'llama', 'llama-cli']) {
1021
+ const whichRes = await run(shell, `which ${bin}`);
1022
+ expect(whichRes.exitCode).toBe(0);
1023
+ expect(whichRes.output.join('')).toContain(`/bin/${bin}`);
1024
+ }
1025
+
1026
+ const helpRes = await run(shell, 'wllama --help');
1027
+ expect(helpRes.exitCode).toBe(0);
1028
+ expect(helpRes.output.join('\n')).toContain('WebGPU');
1029
+ expect(helpRes.output.join('\n')).toContain('--n-gpu-layers');
1030
+
1031
+ const runHelpRes = await run(shell, 'wbt run wllama --help');
1032
+ expect(runHelpRes.exitCode).toBe(0);
1033
+ expect(runHelpRes.output.join('\n')).toContain('Usage: wllama');
1034
+ });
1035
+
1036
+ it('runs one-shot chat completions from a local filesystem .gguf model, piped stdin, or -f file with WebGPU or --no-gpu', async () => {
1037
+ const res1 = await run(
1038
+ shell,
1039
+ 'wllama -m /home/tinyllama.gguf -s "Be concise" -p "Hello Wllama 3!"'
1040
+ );
1041
+ expect(res1.exitCode).toBe(0);
1042
+ expect(res1.output.join('\n')).toContain('[sys:Be concise] Reply(WebGPU,turns=1): Hello Wllama 3!');
1043
+
1044
+ // CPU fallback (--no-gpu / -ngl 0)
1045
+ const resCpu = await run(
1046
+ shell,
1047
+ 'llama -m /home/tinyllama.gguf --no-gpu -p "CPU test"'
1048
+ );
1049
+ expect(resCpu.exitCode).toBe(0);
1050
+ expect(resCpu.output.join('\n')).toContain('Reply(CPU,turns=1): CPU test');
1051
+
1052
+ // Piped stdin
1053
+ const piped = await run(
1054
+ shell,
1055
+ 'echo "Piped prompt" | llama-cli -m /home/tinyllama.gguf'
1056
+ );
1057
+ expect(piped.exitCode).toBe(0);
1058
+ expect(piped.output.join('\n')).toContain('Reply(WebGPU,turns=1): Piped prompt');
1059
+
1060
+ // File prompt (-f) and raw completion (--raw)
1061
+ const rawRes = await run(
1062
+ shell,
1063
+ 'wllama -m /home/tinyllama.gguf --raw -f /home/prompt.txt'
1064
+ );
1065
+ expect(rawRes.exitCode).toBe(0);
1066
+ expect(rawRes.output.join('\n')).toContain('Explain WebGPU in one sentence. [completed]');
1067
+ });
1068
+
1069
+ it('supports Hugging Face model loading (--hf / hf:), embeddings (wllama embed), info, and bench', async () => {
1070
+ const hfRes = await run(
1071
+ shell,
1072
+ 'wllama --hf Qwen/Qwen2.5-0.5B-Instruct-GGUF --quant Q4_K_M -p "From HF"'
1073
+ );
1074
+ expect(hfRes.exitCode).toBe(0);
1075
+ expect(hfRes.output.join('\n')).toContain('Reply(WebGPU,turns=1): From HF');
1076
+
1077
+ const embRes = await run(
1078
+ shell,
1079
+ 'wllama embed -m /home/tinyllama.gguf -p "hello"'
1080
+ );
1081
+ expect(embRes.exitCode).toBe(0);
1082
+ expect(JSON.parse(embRes.output.join(''))).toEqual([5, 0.25, 0.5, 0.75]);
1083
+
1084
+ const infoRes = await run(shell, 'wllama info -m /home/tinyllama.gguf');
1085
+ expect(infoRes.exitCode).toBe(0);
1086
+ expect(infoRes.output.join('\n')).toContain('WebGPU: enabled');
1087
+ expect(infoRes.output.join('\n')).toContain('layers=22');
1088
+
1089
+ const benchRes = await run(shell, 'wllama bench');
1090
+ expect(benchRes.exitCode).toBe(0);
1091
+ expect(benchRes.output.join('\n')).toContain('PASSED');
1092
+ });
1093
+
1094
+ it('enters interactive multi-turn chat REPL mode when `wllama` is invoked with no prompt', async () => {
1095
+ let interactiveFired = false;
1096
+ shell.once('interactive', () => { interactiveFired = true; });
1097
+
1098
+ const screens = [];
1099
+ const onOut = (line) => screens.push(line);
1100
+ shell.on('stdOut', onOut);
1101
+
1102
+ const cmdPromise = shell.onCommand('wllama -m /home/tinyllama.gguf');
1103
+
1104
+ await new Promise(r => setTimeout(r, 20));
1105
+ expect(interactiveFired).toBe(true);
1106
+
1107
+ for (const ch of 'First question') {
1108
+ shell.onInput(ch);
1109
+ }
1110
+ shell.onInput('Enter');
1111
+ await new Promise(r => setTimeout(r, 20));
1112
+ expect(screens[screens.length - 1]).toContain('Reply(WebGPU,turns=1): First question');
1113
+
1114
+ for (const ch of 'Second question') {
1115
+ shell.onInput(ch);
1116
+ }
1117
+ shell.onInput('Enter');
1118
+ await new Promise(r => setTimeout(r, 20));
1119
+ expect(screens[screens.length - 1]).toContain('Reply(WebGPU,turns=2): Second question');
1120
+
1121
+ shell.onInput('^D');
1122
+ await cmdPromise;
1123
+ shell.removeListener('stdOut', onOut);
1124
+ });
1125
+
1126
+ it('persists pulled remote models to the brsh filesystem via `--persist`, `-o`, and `wllama pull`', async () => {
1127
+ // 1. Run with `--persist` (saves to default /var/cache/wllama/<filename>.gguf)
1128
+ const persistRes = await run(
1129
+ shell,
1130
+ 'wllama --hf Qwen/Qwen2.5-0.5B-Instruct-GGUF --quant Q4_K_M --persist -p "Persist test"'
1131
+ );
1132
+ expect(persistRes.exitCode).toBe(0);
1133
+ expect(persistRes.output.join('\n')).toContain('Reply(WebGPU,turns=1): Persist test');
1134
+ expect(shell.context.fs.exists('/var/cache/wllama/Qwen2.5-0.5B-Instruct-GGUF-Q4_K_M.gguf')).toBe(true);
1135
+
1136
+ // 2. Run with `-o` / `--output` to persist to a custom path
1137
+ const outRes = await run(
1138
+ shell,
1139
+ 'wllama -m https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K.gguf -o /home/saved-stories.gguf -p "Saved custom"'
1140
+ );
1141
+ expect(outRes.exitCode).toBe(0);
1142
+ expect(shell.context.fs.exists('/home/saved-stories.gguf')).toBe(true);
1143
+
1144
+ // 3. Dedicated `wllama pull` subcommand streams download progress bars
1145
+ const pullRes = await run(
1146
+ shell,
1147
+ 'wllama pull hf:bartowski/SmolLM2-135M-Instruct-GGUF:Q4_K_M -o /home/smol.gguf'
1148
+ );
1149
+ expect(pullRes.exitCode).toBe(0);
1150
+ expect(pullRes.output.some(l => l.startsWith('\rPulling') && l.includes('50%'))).toBe(true);
1151
+ expect(pullRes.output.some(l => l.startsWith('\rPulling') && l.includes('100%'))).toBe(true);
1152
+ expect(pullRes.output.join('\n')).toContain('Persisted model');
1153
+ expect(pullRes.output.join('\n')).toContain('/home/smol.gguf');
1154
+ expect(shell.context.fs.exists('/home/smol.gguf')).toBe(true);
1155
+
1156
+ // 4. `-q` / `--no-progress` suppresses the progress bar
1157
+ const quietRes = await run(
1158
+ shell,
1159
+ 'wllama pull hf:ggml-org/models/tinyllamas/stories15M-q4_0.gguf -q -o /home/quiet.gguf'
1160
+ );
1161
+ expect(quietRes.exitCode).toBe(0);
1162
+ expect(quietRes.output.some(l => l.startsWith('\rPulling'))).toBe(false);
1163
+ expect(shell.context.fs.exists('/home/quiet.gguf')).toBe(true);
1164
+
1165
+ // 5. Verify `wllama models` lists persisted models in `/var/cache/wllama`
1166
+ const modelsRes = await run(shell, 'wllama models');
1167
+ expect(modelsRes.exitCode).toBe(0);
1168
+ expect(modelsRes.output.join('\n')).toContain('/var/cache/wllama/Qwen2.5-0.5B-Instruct-GGUF-Q4_K_M.gguf');
1169
+ expect(modelsRes.output.join('\n')).toContain('persisted (fs)');
1170
+ });
1171
+ });
1172
+
1173
+
1174
+
1084
1175
 
@@ -1,23 +1,27 @@
1
1
  import { defineConfig } from 'vite';
2
- import { nodePolyfills } from 'vite-plugin-node-polyfills';
3
2
  import path from 'path';
4
3
 
5
4
  export default defineConfig({
6
- plugins: [
7
- nodePolyfills()
8
- ],
9
- resolve: {
10
- // Terminal.js does require('Shell') — point that at the real entry
11
- alias: {
12
- Shell: path.resolve(import.meta.dirname, 'index.js')
13
- }
14
- },
15
5
  build: {
16
6
  lib: {
17
7
  entry: path.resolve(import.meta.dirname, 'lib/Terminal.js'),
18
8
  name: 'Terminal',
19
- formats: ['es', 'iife'],
20
- fileName: (format) => format === 'iife' ? 'terminal.min.js' : 'terminal.es.js'
9
+ formats: ['es', 'cjs', 'iife'],
10
+ fileName: (format) => {
11
+ if (format === 'iife') return 'terminal.min.js';
12
+ if (format === 'cjs') return 'terminal.cjs.js';
13
+ return 'terminal.es.js';
14
+ }
15
+ },
16
+ rollupOptions: {
17
+ external: ['brsh', 'Shell'],
18
+ output: {
19
+ exports: 'auto',
20
+ globals: {
21
+ brsh: 'globalThis.Shell',
22
+ Shell: 'globalThis.Shell'
23
+ }
24
+ }
21
25
  },
22
26
  minify: true,
23
27
  sourcemap: true,