brsh 3.6.2 → 3.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/lib/Readme.md CHANGED
@@ -113,8 +113,30 @@ Wrap any WASI `.wasm` binary or ESM/Emscripten module into a `brsh` command:
113
113
  ```js
114
114
  const MyWasmTool = Shell.createWasmCommand({
115
115
  name: 'mytool',
116
- wasmUrl: 'https://example.com/mytool.wasm'
116
+ wasmUrl: 'https://example.com/mytool.wasm',
117
+ interactive: true // Set to true for full-screen TUIs / games (enables alternate screen buffer & raw TTY input)
117
118
  });
118
119
 
119
120
  shell.context.setCommand(MyWasmTool);
120
121
  ```
122
+
123
+ ### Options for `Shell.createWasmCommand`
124
+
125
+ | Option | Type | Description |
126
+ | --- | --- | --- |
127
+ | `name` | `String` | Command name invoked in the shell |
128
+ | `wasmUrl` | `String` | URL to fetch the `.wasm` binary from |
129
+ | `wasmPath` | `String` | Optional path to `.wasm` binary stored in the virtual filesystem (`this.fs`) |
130
+ | `interactive` | `Boolean` | When `true`, automatically enters the alternate screen buffer (`\x1b[?1049h`) and routes live raw keyboard events to `stdin` (`fd 0`) and `stderr` (`fd 2`) |
131
+ | `bin` | `String` | Optional binary name override |
132
+ | `type` | `String` | `'wasm'` / `'custom-wasm'` for raw WASI, or omit for generic ESM/Emscripten |
133
+
134
+ ### Compiling C / C++ Applications for `brsh`
135
+
136
+ `brsh` supports WASI Preview 1 binaries with non-blocking I/O (`FDFLAGS_NONBLOCK`), cooperative sleep/timers via Asyncify (`poll_oneoff`, `clock_nanosleep`), and terminal dimension queries.
137
+
138
+ * For POSIX terminal raw mode, baud rates, and `TIOCGWINSZ`, use [**`wasi-termios-brsh`**](https://github.com/eliotstocker/wasi-termios-brsh).
139
+ * For a complete real-world reference implementation of an interactive C TUI editor with ncurses targeting `brsh`, inspect [**`nano-wasm`**](https://github.com/eliotstocker/nano-wasm).
140
+ * For complete step-by-step instructions on compiling with `wasi-sdk`, configuring `termios`, and instrumenting with `wasm-opt --asyncify`, see [Compiling C / C++ Applications in the main Readme](../Readme.md#compiling-c--c-applications-for-brsh).
141
+
142
+
@@ -5,12 +5,14 @@ const { BinaryFile } = require('./FileSystem');
5
5
 
6
6
  // WASI errno constants
7
7
  const ERRNO_SUCCESS = 0;
8
+ const ERRNO_AGAIN = 6;
8
9
  const ERRNO_BADF = 8;
9
10
  const ERRNO_EXIST = 20;
10
11
  const ERRNO_INVAL = 28;
11
12
  const ERRNO_ISDIR = 31;
12
13
  const ERRNO_NOENT = 44;
13
14
  const ERRNO_NOTDIR = 54;
15
+ const ERRNO_NOSYS = 52;
14
16
  const ERRNO_SPIPE = 70;
15
17
 
16
18
  // WASI filetype constants
@@ -27,6 +29,10 @@ const OFLAGS_TRUNC = 1 << 3;
27
29
 
28
30
  // WASI fdflags
29
31
  const FDFLAGS_APPEND = 1 << 0;
32
+ const FDFLAGS_DSYNC = 1 << 1;
33
+ const FDFLAGS_NONBLOCK = 1 << 2;
34
+ const FDFLAGS_RSYNC = 1 << 3;
35
+ const FDFLAGS_SYNC = 1 << 4;
30
36
 
31
37
  class WasmCommand extends ScriptCommand {
32
38
  // this.script = filepath (set by ScriptCommand parent constructor)
@@ -216,11 +222,31 @@ class WasmCommand extends ScriptCommand {
216
222
  let onResize = null;
217
223
  let onStreamData = null;
218
224
 
219
- const isInteractive = Boolean(
220
- this.interactive &&
221
- (this.stdin === undefined || this.stdin === null || this.stdin === this.stdinStream || (this.stdin && this.stdin.isTTY))
225
+ const isTtyEnvironment = (this.stdin === undefined || this.stdin === null || this.stdin === this.stdinStream || (this.stdin && this.stdin.isTTY));
226
+
227
+ let isInteractive = Boolean(
228
+ this.interactive && isTtyEnvironment
222
229
  );
223
230
 
231
+ const promoteToInteractive = () => {
232
+ if (isInteractive || !isTtyEnvironment) return;
233
+ isInteractive = true;
234
+ this._isInteractive = true;
235
+
236
+ if (outBuf[1]) {
237
+ if (this.stdout && typeof this.stdout.write === 'function') this.stdout.write(outBuf[1]);
238
+ outBuf[1] = '';
239
+ }
240
+ if (outBuf[2]) {
241
+ if (this.stderr && typeof this.stderr.write === 'function') this.stderr.write(outBuf[2]);
242
+ outBuf[2] = '';
243
+ }
244
+
245
+ if (this.stdinStream && typeof this.stdinStream.setRawMode === 'function') {
246
+ this.stdinStream.setRawMode(true);
247
+ }
248
+ };
249
+
224
250
  const writeFd = (fd, text) => {
225
251
  if (isInteractive && (fd === 1 || fd === 2)) {
226
252
  if (fd === 1 && this.stdout) {
@@ -290,18 +316,18 @@ class WasmCommand extends ScriptCommand {
290
316
  if (b) enqueueBytes(b);
291
317
  };
292
318
 
293
- if (isInteractive && this.stdinStream && typeof this.stdinStream.on === 'function') {
319
+ if (isTtyEnvironment && this.stdinStream && typeof this.stdinStream.on === 'function') {
294
320
  this.stdinStream.on('data', onStreamData);
295
321
  }
296
- if (isInteractive && this.stdin && this.stdin !== this.stdinStream && typeof this.stdin.on === 'function') {
322
+ if (isTtyEnvironment && this.stdin && this.stdin !== this.stdinStream && typeof this.stdin.on === 'function') {
297
323
  this.stdin.on('data', onStreamData);
298
324
  }
299
325
 
300
- const stdinBytes = (!isInteractive && typeof this.stdin === 'string')
326
+ const stdinBytes = (!isTtyEnvironment && typeof this.stdin === 'string')
301
327
  ? encoder.encode(this.stdin)
302
- : (!isInteractive && this.stdin instanceof Uint8Array
328
+ : (!isTtyEnvironment && this.stdin instanceof Uint8Array
303
329
  ? this.stdin
304
- : (!isInteractive && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.stdin) ? new Uint8Array(this.stdin) : new Uint8Array(0)));
330
+ : (!isTtyEnvironment && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.stdin) ? new Uint8Array(this.stdin) : new Uint8Array(0)));
305
331
  let stdinPos = 0;
306
332
 
307
333
  // ── Virtual WASI file descriptor table backed by this.context.fs ──
@@ -320,6 +346,7 @@ class WasmCommand extends ScriptCommand {
320
346
  [3, { type: 'preopen', path: '/', guestName: '/' }],
321
347
  [4, { type: 'preopen', path: cwd, guestName: '.' }]
322
348
  ]);
349
+ const fdFlagsMap = new Map([[0, 0], [1, 0], [2, 0]]);
323
350
 
324
351
  const getParentPath = (p) => {
325
352
  const parts = p.split('/').filter(Boolean);
@@ -410,7 +437,30 @@ class WasmCommand extends ScriptCommand {
410
437
  }
411
438
 
412
439
  const entry = fdTable.get(fd);
413
- if (!entry || entry.type !== 'file') return ERRNO_BADF;
440
+ if (!entry) return ERRNO_BADF;
441
+
442
+ if (entry.type === 'dev_null' || entry.type === 'dev_zero') {
443
+ let total = 0;
444
+ for (let i = 0; i < iovs_len; i++) {
445
+ total += view.getUint32(iovs + i * 8 + 4, true);
446
+ }
447
+ view.setUint32(nwritten_ptr, total, true);
448
+ return ERRNO_SUCCESS;
449
+ }
450
+
451
+ if (entry.type === 'dev_tty') {
452
+ let total = 0;
453
+ for (let i = 0; i < iovs_len; i++) {
454
+ const ptr = view.getUint32(iovs + i * 8, true);
455
+ const len = view.getUint32(iovs + i * 8 + 4, true);
456
+ if (len > 0) writeFd(1, decoder.decode(new Uint8Array(memRef.buffer, ptr, len)));
457
+ total += len;
458
+ }
459
+ view.setUint32(nwritten_ptr, total, true);
460
+ return ERRNO_SUCCESS;
461
+ }
462
+
463
+ if (entry.type !== 'file') return ERRNO_BADF;
414
464
 
415
465
  let total = 0;
416
466
  for (let i = 0; i < iovs_len; i++) {
@@ -438,8 +488,18 @@ class WasmCommand extends ScriptCommand {
438
488
  if (!memRef) return ERRNO_BADF;
439
489
  const view = new DataView(memRef.buffer);
440
490
 
441
- if (fd === 0) {
442
- if (isInteractive && hasAsyncify) {
491
+ const entry = fdTable.get(fd);
492
+ const isDevTty = Boolean(entry && entry.type === 'dev_tty');
493
+ const isTtyInput = (fd === 0) || (isInteractive && fd === 2) || isDevTty;
494
+
495
+ if (isTtyInput) {
496
+ if (isDevTty || fd === 2) {
497
+ promoteToInteractive();
498
+ }
499
+ const flags = fdFlagsMap.get(fd) || 0;
500
+ const isNonBlocking = Boolean(flags & FDFLAGS_NONBLOCK);
501
+
502
+ if (hasAsyncify) {
443
503
  const state = (typeof instance?.exports?.asyncify_get_state === 'function')
444
504
  ? instance.exports.asyncify_get_state()
445
505
  : 0;
@@ -473,6 +533,11 @@ class WasmCommand extends ScriptCommand {
473
533
  return ERRNO_SUCCESS;
474
534
  }
475
535
 
536
+ if (isNonBlocking) {
537
+ view.setUint32(nread_ptr, 0, true);
538
+ return ERRNO_AGAIN;
539
+ }
540
+
476
541
  instance.exports.asyncify_start_unwind(asyncifyDataAddr);
477
542
  asyncifyPromise = new Promise(resolve => {
478
543
  pendingReadResolve = resolve;
@@ -481,6 +546,20 @@ class WasmCommand extends ScriptCommand {
481
546
  return ERRNO_SUCCESS;
482
547
  }
483
548
 
549
+ if (inputQueue.length > 0) {
550
+ let total = 0;
551
+ for (let i = 0; i < iovs_len && inputQueue.length > 0; i++) {
552
+ const ptr = view.getUint32(iovs + i * 8, true);
553
+ const len = view.getUint32(iovs + i * 8 + 4, true);
554
+ const chunk = Math.min(len, inputQueue.length);
555
+ const slice = inputQueue.splice(0, chunk);
556
+ new Uint8Array(memRef.buffer).set(slice, ptr);
557
+ total += chunk;
558
+ }
559
+ view.setUint32(nread_ptr, total, true);
560
+ return ERRNO_SUCCESS;
561
+ }
562
+
484
563
  let total = 0;
485
564
  for (let i = 0; i < iovs_len && stdinPos < stdinBytes.length; i++) {
486
565
  const ptr = view.getUint32(iovs + i * 8, true);
@@ -490,12 +569,51 @@ class WasmCommand extends ScriptCommand {
490
569
  stdinPos += chunk;
491
570
  total += chunk;
492
571
  }
572
+ if (total === 0 && isNonBlocking && stdinPos >= stdinBytes.length) {
573
+ view.setUint32(nread_ptr, 0, true);
574
+ return ERRNO_AGAIN;
575
+ }
493
576
  view.setUint32(nread_ptr, total, true);
494
577
  return ERRNO_SUCCESS;
495
578
  }
496
579
 
497
- const entry = fdTable.get(fd);
498
- if (!entry || entry.type !== 'file') return ERRNO_BADF;
580
+ if (!entry) return ERRNO_BADF;
581
+
582
+ if (entry.type === 'dev_null') {
583
+ view.setUint32(nread_ptr, 0, true);
584
+ return ERRNO_SUCCESS;
585
+ }
586
+
587
+ if (entry.type === 'dev_zero') {
588
+ let total = 0;
589
+ for (let i = 0; i < iovs_len; i++) {
590
+ const ptr = view.getUint32(iovs + i * 8, true);
591
+ const len = view.getUint32(iovs + i * 8 + 4, true);
592
+ new Uint8Array(memRef.buffer, ptr, len).fill(0);
593
+ total += len;
594
+ }
595
+ view.setUint32(nread_ptr, total, true);
596
+ return ERRNO_SUCCESS;
597
+ }
598
+
599
+ if (entry.type === 'dev_urandom') {
600
+ let total = 0;
601
+ for (let i = 0; i < iovs_len; i++) {
602
+ const ptr = view.getUint32(iovs + i * 8, true);
603
+ const len = view.getUint32(iovs + i * 8 + 4, true);
604
+ const targetBuf = new Uint8Array(memRef.buffer, ptr, len);
605
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
606
+ crypto.getRandomValues(targetBuf);
607
+ } else {
608
+ for (let j = 0; j < len; j++) targetBuf[j] = Math.floor(Math.random() * 256);
609
+ }
610
+ total += len;
611
+ }
612
+ view.setUint32(nread_ptr, total, true);
613
+ return ERRNO_SUCCESS;
614
+ }
615
+
616
+ if (entry.type !== 'file') return ERRNO_BADF;
499
617
 
500
618
  let total = 0;
501
619
  for (let i = 0; i < iovs_len && entry.pos < entry.bytes.length; i++) {
@@ -513,7 +631,11 @@ class WasmCommand extends ScriptCommand {
513
631
  if (!memRef) return ERRNO_BADF;
514
632
  if (fd <= 2) return ERRNO_SPIPE;
515
633
  const entry = fdTable.get(fd);
516
- if (!entry || entry.type !== 'file') return ERRNO_BADF;
634
+ if (!entry) return ERRNO_BADF;
635
+ if (entry.type === 'dev_tty' || entry.type === 'dev_null' || entry.type === 'dev_zero' || entry.type === 'dev_urandom') {
636
+ return ERRNO_SPIPE;
637
+ }
638
+ if (entry.type !== 'file') return ERRNO_BADF;
517
639
 
518
640
  // Support both BigInt (i64) and split 32-bit calls
519
641
  let off;
@@ -553,8 +675,9 @@ class WasmCommand extends ScriptCommand {
553
675
  if (fd <= 2) return ERRNO_SUCCESS;
554
676
  const entry = fdTable.get(fd);
555
677
  if (!entry) return ERRNO_BADF;
556
- flushOpenFile(entry);
678
+ if (entry.type === 'file') flushOpenFile(entry);
557
679
  fdTable.delete(fd);
680
+ fdFlagsMap.delete(fd);
558
681
  return ERRNO_SUCCESS;
559
682
  },
560
683
  fd_sync: (fd) => {
@@ -595,18 +718,36 @@ class WasmCommand extends ScriptCommand {
595
718
  } else {
596
719
  const entry = fdTable.get(fd);
597
720
  if (!entry) return ERRNO_BADF;
598
- filetype = (entry.type === 'preopen' || entry.type === 'dir')
599
- ? FILETYPE_DIRECTORY
600
- : FILETYPE_REGULAR_FILE;
721
+ if (entry.type === 'dev_null' || entry.type === 'dev_zero' || entry.type === 'dev_urandom' || entry.type === 'dev_tty') {
722
+ filetype = FILETYPE_CHARACTER_DEVICE;
723
+ } else {
724
+ filetype = (entry.type === 'preopen' || entry.type === 'dir')
725
+ ? FILETYPE_DIRECTORY
726
+ : FILETYPE_REGULAR_FILE;
727
+ }
601
728
  }
602
729
  // struct fdstat (24 bytes): fs_filetype (u8), fs_flags (u16), rights_base (u64), rights_inheriting (u64)
603
730
  for (let i = 0; i < 24; i++) view.setUint8(stat_ptr + i, 0);
604
731
  view.setUint8(stat_ptr, filetype);
732
+ const flags = fdFlagsMap.get(fd) || (fdTable.get(fd)?.append ? FDFLAGS_APPEND : 0);
733
+ view.setUint16(stat_ptr + 2, flags, true);
605
734
  view.setBigUint64(stat_ptr + 8, 0xffffffffffffffffn, true);
606
735
  view.setBigUint64(stat_ptr + 16, 0xffffffffffffffffn, true);
607
736
  return ERRNO_SUCCESS;
608
737
  },
609
- fd_fdstat_set_flags: () => ERRNO_SUCCESS,
738
+ fd_fdstat_set_flags: (fd, flags) => {
739
+ if (!memRef) return ERRNO_BADF;
740
+ if (fd > 2 && !fdTable.has(fd)) return ERRNO_BADF;
741
+ fdFlagsMap.set(fd, flags);
742
+ const entry = fdTable.get(fd);
743
+ if (entry) {
744
+ entry.append = Boolean(flags & FDFLAGS_APPEND);
745
+ }
746
+ if ((fd === 0 || fd === 2 || (entry && entry.type === 'dev_tty')) && (flags & FDFLAGS_NONBLOCK)) {
747
+ promoteToInteractive();
748
+ }
749
+ return ERRNO_SUCCESS;
750
+ },
610
751
  fd_filestat_get: (fd, buf_ptr) => {
611
752
  if (!memRef) return ERRNO_BADF;
612
753
  const view = new DataView(memRef.buffer);
@@ -617,6 +758,11 @@ class WasmCommand extends ScriptCommand {
617
758
  }
618
759
  const entry = fdTable.get(fd);
619
760
  if (!entry) return ERRNO_BADF;
761
+ if (entry.type === 'dev_null' || entry.type === 'dev_zero' || entry.type === 'dev_urandom' || entry.type === 'dev_tty') {
762
+ view.setUint8(buf_ptr + 16, FILETYPE_CHARACTER_DEVICE);
763
+ view.setBigUint64(buf_ptr + 24, 1n, true); // nlink
764
+ return ERRNO_SUCCESS;
765
+ }
620
766
  const isDir = entry.type === 'preopen' || entry.type === 'dir';
621
767
  view.setUint8(buf_ptr + 16, isDir ? FILETYPE_DIRECTORY : FILETYPE_REGULAR_FILE);
622
768
  view.setBigUint64(buf_ptr + 24, 1n, true); // nlink
@@ -629,6 +775,33 @@ class WasmCommand extends ScriptCommand {
629
775
  const absPath = resolveGuestPath(dirfd, relPath);
630
776
  if (!absPath) return ERRNO_BADF;
631
777
 
778
+ const cleanPath = absPath.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
779
+ if (cleanPath === '/dev/null') {
780
+ const newFd = nextFd++;
781
+ fdTable.set(newFd, { type: 'dev_null', path: '/dev/null' });
782
+ new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
783
+ return ERRNO_SUCCESS;
784
+ }
785
+ if (cleanPath === '/dev/zero') {
786
+ const newFd = nextFd++;
787
+ fdTable.set(newFd, { type: 'dev_zero', path: '/dev/zero' });
788
+ new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
789
+ return ERRNO_SUCCESS;
790
+ }
791
+ if (cleanPath === '/dev/urandom' || cleanPath === '/dev/random') {
792
+ const newFd = nextFd++;
793
+ fdTable.set(newFd, { type: 'dev_urandom', path: cleanPath });
794
+ new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
795
+ return ERRNO_SUCCESS;
796
+ }
797
+ if (cleanPath === '/dev/tty') {
798
+ promoteToInteractive();
799
+ const newFd = nextFd++;
800
+ fdTable.set(newFd, { type: 'dev_tty', path: '/dev/tty' });
801
+ new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
802
+ return ERRNO_SUCCESS;
803
+ }
804
+
632
805
  const st = fs.stat(absPath);
633
806
  const exists = st !== null;
634
807
 
@@ -681,6 +854,14 @@ class WasmCommand extends ScriptCommand {
681
854
  const relPath = decoder.decode(new Uint8Array(memRef.buffer, path_ptr, path_len));
682
855
  const absPath = resolveGuestPath(dirfd, relPath);
683
856
  if (!absPath) return ERRNO_BADF;
857
+ const cleanPath = absPath.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
858
+ if (cleanPath === '/dev/null' || cleanPath === '/dev/zero' || cleanPath === '/dev/urandom' || cleanPath === '/dev/random' || cleanPath === '/dev/tty') {
859
+ const view = new DataView(memRef.buffer);
860
+ for (let i = 0; i < 64; i++) view.setUint8(buf_ptr + i, 0);
861
+ view.setUint8(buf_ptr + 16, FILETYPE_CHARACTER_DEVICE);
862
+ view.setBigUint64(buf_ptr + 24, 1n, true);
863
+ return ERRNO_SUCCESS;
864
+ }
684
865
  const st = fs.stat(absPath);
685
866
  if (!st) return ERRNO_NOENT;
686
867
  const view = new DataView(memRef.buffer);
@@ -810,6 +991,154 @@ class WasmCommand extends ScriptCommand {
810
991
  }
811
992
  return ERRNO_SUCCESS;
812
993
  },
994
+ clock_nanosleep: (id, flags, timeout_ptr, precision, rem_ptr) => {
995
+ if (!memRef) return ERRNO_BADF;
996
+ const view = new DataView(memRef.buffer);
997
+ const timeoutNs = view.getBigUint64(timeout_ptr, true);
998
+ let sleepMs = 0;
999
+ if (flags & 1) { // TIMER_ABSTIME
1000
+ const nowNs = BigInt(Date.now()) * 1_000_000n;
1001
+ sleepMs = timeoutNs > nowNs ? Number((timeoutNs - nowNs) / 1_000_000n) : 0;
1002
+ } else {
1003
+ sleepMs = Number(timeoutNs / 1_000_000n);
1004
+ }
1005
+
1006
+ if (hasAsyncify && sleepMs > 0) {
1007
+ const state = (typeof instance?.exports?.asyncify_get_state === 'function')
1008
+ ? instance.exports.asyncify_get_state()
1009
+ : 0;
1010
+
1011
+ if (state === 2) {
1012
+ instance.exports.asyncify_stop_rewind();
1013
+ return ERRNO_SUCCESS;
1014
+ }
1015
+
1016
+ instance.exports.asyncify_start_unwind(asyncifyDataAddr);
1017
+ asyncifyPromise = new Promise(resolve => setTimeout(resolve, Math.max(1, sleepMs)));
1018
+ return ERRNO_SUCCESS;
1019
+ }
1020
+ return ERRNO_SUCCESS;
1021
+ },
1022
+ poll_oneoff: (in_ptr, out_ptr, nsubscriptions, nevents_ptr) => {
1023
+ if (!memRef) return ERRNO_BADF;
1024
+ const view = new DataView(memRef.buffer);
1025
+
1026
+ if (hasAsyncify) {
1027
+ const state = (typeof instance?.exports?.asyncify_get_state === 'function')
1028
+ ? instance.exports.asyncify_get_state()
1029
+ : 0;
1030
+
1031
+ if (state === 2) {
1032
+ instance.exports.asyncify_stop_rewind();
1033
+ let nevents = 0;
1034
+ for (let i = 0; i < nsubscriptions; i++) {
1035
+ const subPtr = in_ptr + i * 48;
1036
+ const userdata = view.getBigUint64(subPtr, true);
1037
+ const type = view.getUint8(subPtr + 8);
1038
+ const outEventPtr = out_ptr + nevents * 32;
1039
+
1040
+ view.setBigUint64(outEventPtr, userdata, true);
1041
+ view.setUint16(outEventPtr + 8, ERRNO_SUCCESS, true);
1042
+ view.setUint8(outEventPtr + 10, type);
1043
+ for (let b = 11; b < 32; b++) view.setUint8(outEventPtr + b, 0);
1044
+
1045
+ if (type === 1) { // FD_READ
1046
+ view.setBigUint64(outEventPtr + 16, BigInt(inputQueue.length), true);
1047
+ }
1048
+ nevents++;
1049
+ }
1050
+ view.setUint32(nevents_ptr, nevents, true);
1051
+ return ERRNO_SUCCESS;
1052
+ }
1053
+
1054
+ let immediateCount = 0;
1055
+ let minTimeoutMs = Infinity;
1056
+
1057
+ for (let i = 0; i < nsubscriptions; i++) {
1058
+ const subPtr = in_ptr + i * 48;
1059
+ const type = view.getUint8(subPtr + 8);
1060
+
1061
+ if (type === 0) { // EVENTTYPE_CLOCK
1062
+ const timeoutNs = view.getBigUint64(subPtr + 24, true);
1063
+ const flags = view.getUint16(subPtr + 40, true);
1064
+ let sleepMs = 0;
1065
+ if (flags & 1) { // ABSTIME
1066
+ const nowNs = BigInt(Date.now()) * 1_000_000n;
1067
+ sleepMs = timeoutNs > nowNs ? Number((timeoutNs - nowNs) / 1_000_000n) : 0;
1068
+ } else {
1069
+ sleepMs = Number(timeoutNs / 1_000_000n);
1070
+ }
1071
+ if (sleepMs < minTimeoutMs) minTimeoutMs = sleepMs;
1072
+ } else if (type === 1) { // EVENTTYPE_FD_READ
1073
+ const fd = view.getUint32(subPtr + 16, true);
1074
+ const entry = fdTable.get(fd);
1075
+ const isDevTty = Boolean(entry && entry.type === 'dev_tty');
1076
+ if (fd === 0 || fd === 2 || isDevTty) {
1077
+ promoteToInteractive();
1078
+ }
1079
+ if ((fd === 0 || (isInteractive && fd === 2) || isDevTty) && inputQueue.length > 0) {
1080
+ immediateCount++;
1081
+ }
1082
+ } else if (type === 2) { // EVENTTYPE_FD_WRITE
1083
+ immediateCount++;
1084
+ }
1085
+ }
1086
+
1087
+ if (immediateCount > 0 || minTimeoutMs === 0) {
1088
+ let nevents = 0;
1089
+ for (let i = 0; i < nsubscriptions; i++) {
1090
+ const subPtr = in_ptr + i * 48;
1091
+ const userdata = view.getBigUint64(subPtr, true);
1092
+ const type = view.getUint8(subPtr + 8);
1093
+ let isReady = false;
1094
+
1095
+ if (type === 0 && minTimeoutMs === 0) isReady = true;
1096
+ else if (type === 1) {
1097
+ const fd = view.getUint32(subPtr + 16, true);
1098
+ const entry = fdTable.get(fd);
1099
+ const isDevTty = Boolean(entry && entry.type === 'dev_tty');
1100
+ if ((fd === 0 || (isInteractive && fd === 2) || isDevTty) && inputQueue.length > 0) isReady = true;
1101
+ } else if (type === 2) isReady = true;
1102
+
1103
+ if (isReady) {
1104
+ const outEventPtr = out_ptr + nevents * 32;
1105
+ view.setBigUint64(outEventPtr, userdata, true);
1106
+ view.setUint16(outEventPtr + 8, ERRNO_SUCCESS, true);
1107
+ view.setUint8(outEventPtr + 10, type);
1108
+ for (let b = 11; b < 32; b++) view.setUint8(outEventPtr + b, 0);
1109
+ if (type === 1) {
1110
+ view.setBigUint64(outEventPtr + 16, BigInt(inputQueue.length), true);
1111
+ }
1112
+ nevents++;
1113
+ }
1114
+ }
1115
+ view.setUint32(nevents_ptr, nevents, true);
1116
+ return ERRNO_SUCCESS;
1117
+ }
1118
+
1119
+ instance.exports.asyncify_start_unwind(asyncifyDataAddr);
1120
+ asyncifyPromise = new Promise(resolve => {
1121
+ let timer = null;
1122
+ const onKey = () => {
1123
+ if (timer) clearTimeout(timer);
1124
+ pendingReadResolve = null;
1125
+ resolve();
1126
+ };
1127
+ pendingReadResolve = onKey;
1128
+ if (minTimeoutMs !== Infinity) {
1129
+ timer = setTimeout(() => {
1130
+ pendingReadResolve = null;
1131
+ resolve();
1132
+ }, Math.max(1, minTimeoutMs));
1133
+ }
1134
+ });
1135
+ view.setUint32(nevents_ptr, 0, true);
1136
+ return ERRNO_SUCCESS;
1137
+ }
1138
+
1139
+ view.setUint32(nevents_ptr, 0, true);
1140
+ return ERRNO_SUCCESS;
1141
+ },
813
1142
  };
814
1143
 
815
1144
  const wasiProxy = new Proxy(wasi, { get(t, k) { return k in t ? t[k] : () => 0; } });
@@ -885,27 +1214,32 @@ class WasmCommand extends ScriptCommand {
885
1214
  new Int32Array(memRef.buffer, asyncifyDataAddr, 2).set([dataStart, dataEnd]);
886
1215
  }
887
1216
 
1217
+ if (typeof instance.exports.set_terminal_size === 'function') {
1218
+ promoteToInteractive();
1219
+ }
1220
+
888
1221
  if (isInteractive) {
889
1222
  this._enterAltScreen();
890
- const cols = (this.stdout && this.stdout.columns) || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('COLUMNS'), 10)) || 80;
891
- const rows = (this.stdout && this.stdout.rows) || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('LINES'), 10)) || 24;
892
- if (typeof instance.exports.set_terminal_size === 'function') {
893
- try { instance.exports.set_terminal_size(cols, rows); } catch {}
894
- }
1223
+ }
895
1224
 
896
- onResize = () => {
897
- const c = (this.stdout && this.stdout.columns) || 80;
898
- const r = (this.stdout && this.stdout.rows) || 24;
899
- if (typeof instance?.exports?.set_terminal_size === 'function') {
900
- try { instance.exports.set_terminal_size(c, r); } catch {}
901
- }
902
- };
903
- if (this.stdout && typeof this.stdout.on === 'function') {
904
- this.stdout.on('resize', onResize);
905
- }
906
- if (this.stdinStream && typeof this.stdinStream.on === 'function') {
907
- this.stdinStream.on('resize', onResize);
1225
+ const cols = (this.stdout && this.stdout.columns) || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('COLUMNS'), 10)) || 80;
1226
+ const rows = (this.stdout && this.stdout.rows) || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('LINES'), 10)) || 24;
1227
+ if (typeof instance.exports.set_terminal_size === 'function') {
1228
+ try { instance.exports.set_terminal_size(cols, rows); } catch {}
1229
+ }
1230
+
1231
+ onResize = () => {
1232
+ const c = (this.stdout && this.stdout.columns) || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('COLUMNS'), 10)) || 80;
1233
+ const r = (this.stdout && this.stdout.rows) || (this.context && typeof this.context.getVar === 'function' && parseInt(this.context.getVar('LINES'), 10)) || 24;
1234
+ if (typeof instance?.exports?.set_terminal_size === 'function') {
1235
+ try { instance.exports.set_terminal_size(c, r); } catch {}
908
1236
  }
1237
+ };
1238
+ if (this.stdout && typeof this.stdout.on === 'function') {
1239
+ this.stdout.on('resize', onResize);
1240
+ }
1241
+ if (this.stdinStream && typeof this.stdinStream.on === 'function') {
1242
+ this.stdinStream.on('resize', onResize);
909
1243
  }
910
1244
 
911
1245
  const start = instance.exports._start