brsh 2.8.0 → 3.0.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.
Files changed (45) hide show
  1. package/.github/workflows/release.yml +3 -1
  2. package/CHANGELOG.md +32 -0
  3. package/bin/brsh-shell.js +16 -131
  4. package/bin/exportFileSystem.js +4 -0
  5. package/bin/zsh-server.js +261 -0
  6. package/dist/brsh.css +1 -1
  7. package/dist/shell.es.js +943 -499
  8. package/dist/shell.es.js.map +1 -1
  9. package/dist/shell.min.js +31 -16
  10. package/dist/shell.min.js.map +1 -1
  11. package/dist/terminal.cjs.js +77 -100
  12. package/dist/terminal.cjs.js.map +1 -1
  13. package/dist/terminal.es.js +1382 -603
  14. package/dist/terminal.es.js.map +1 -1
  15. package/dist/terminal.min.js +77 -100
  16. package/dist/terminal.min.js.map +1 -1
  17. package/dist/wbt.es.js +1863 -752
  18. package/dist/wbt.es.js.map +1 -1
  19. package/dist/wbt.min.js +8 -6
  20. package/dist/wbt.min.js.map +1 -1
  21. package/index.js +472 -0
  22. package/lib/BaseFileSystem.js +40 -0
  23. package/lib/BinaryContainer.js +1 -1
  24. package/lib/Command.js +30 -0
  25. package/lib/FileSystem.js +1 -38
  26. package/lib/InteractiveCommand.js +28 -0
  27. package/lib/NodeFileSystem.js +4 -2
  28. package/lib/ReplCommand.js +15 -0
  29. package/lib/Terminal.js +769 -510
  30. package/lib/TtyStream.js +181 -0
  31. package/lib/WasmCommand.js +168 -18
  32. package/lib/builtins/cat.js +2 -2
  33. package/lib/builtins/grep.js +2 -2
  34. package/lib/local/clear.js +3 -0
  35. package/lib/terminal/DomRenderer.js +325 -0
  36. package/lib/terminal/PtyBridge.js +169 -0
  37. package/lib/terminal/ScreenBuffer.js +594 -0
  38. package/lib/terminal/VtParser.js +728 -0
  39. package/lib/wbt/index.js +270 -14
  40. package/lib/wbt/packages/wllama.js +12 -2
  41. package/lib/wbt/registry.js +11 -2
  42. package/package.json +4 -2
  43. package/styles/terminal.css +33 -4
  44. package/test/terminal.test.js +762 -40
  45. package/test/wbt.test.js +24 -5
@@ -0,0 +1,325 @@
1
+ 'use strict';
2
+
3
+ import {
4
+ ATTR_BOLD,
5
+ ATTR_DIM,
6
+ ATTR_ITALIC,
7
+ ATTR_UNDERLINE,
8
+ ATTR_BLINK,
9
+ ATTR_INVERSE,
10
+ ATTR_HIDDEN,
11
+ ATTR_STRIKE
12
+ } from './ScreenBuffer.js';
13
+ import { sanitizeUrl, DEFAULT_URL_WHITELIST } from './VtParser.js';
14
+
15
+ const ANSI_COLOR_NAMES = [
16
+ 'ansi-black',
17
+ 'ansi-red',
18
+ 'ansi-green',
19
+ 'ansi-yellow',
20
+ 'ansi-blue',
21
+ 'ansi-magenta',
22
+ 'ansi-cyan',
23
+ 'ansi-white',
24
+ 'ansi-bright-black',
25
+ 'ansi-bright-red',
26
+ 'ansi-bright-green',
27
+ 'ansi-bright-yellow',
28
+ 'ansi-bright-blue',
29
+ 'ansi-bright-magenta',
30
+ 'ansi-bright-cyan',
31
+ 'ansi-bright-white'
32
+ ];
33
+
34
+ const CUBE_STEPS = [0, 95, 135, 175, 215, 255];
35
+
36
+ function colorIndexToCss(idx) {
37
+ if (typeof idx === 'string') return idx;
38
+ if (typeof idx !== 'number' || idx < 16 || idx > 255) return null;
39
+ if (idx >= 232) {
40
+ const v = 8 + (idx - 232) * 10;
41
+ return `rgb(${v}, ${v}, ${v})`;
42
+ }
43
+ const n = idx - 16;
44
+ const r = CUBE_STEPS[Math.floor(n / 36) % 6];
45
+ const g = CUBE_STEPS[Math.floor(n / 6) % 6];
46
+ const b = CUBE_STEPS[n % 6];
47
+ return `rgb(${r}, ${g}, ${b})`;
48
+ }
49
+
50
+ function escapeHtml(str) {
51
+ return str
52
+ .replace(/&/g, '&amp;')
53
+ .replace(/</g, '&lt;')
54
+ .replace(/>/g, '&gt;')
55
+ .replace(/"/g, '&quot;');
56
+ }
57
+
58
+ const AUTO_URL_REGEX = /(?:https?:\/\/|mailto:|tel:)[^\s<>"'`]+/g;
59
+
60
+ function trimUrlTrailingPunct(url) {
61
+ let end = url.length;
62
+ while (end > 0) {
63
+ const ch = url[end - 1];
64
+ if ('.!?,;:'.includes(ch)) {
65
+ end--;
66
+ } else if (ch === ')') {
67
+ const slice = url.slice(0, end);
68
+ const opens = (slice.match(/\(/g) || []).length;
69
+ const closes = (slice.match(/\)/g) || []).length;
70
+ if (closes > opens) end--;
71
+ else break;
72
+ } else if (ch === ']') {
73
+ const slice = url.slice(0, end);
74
+ const opens = (slice.match(/\[/g) || []).length;
75
+ const closes = (slice.match(/\]/g) || []).length;
76
+ if (closes > opens) end--;
77
+ else break;
78
+ } else {
79
+ break;
80
+ }
81
+ }
82
+ return url.slice(0, end);
83
+ }
84
+
85
+ function detectRowLinks(rowCells, whitelist = DEFAULT_URL_WHITELIST) {
86
+ let lineStr = '';
87
+ for (let c = 0; c < rowCells.length; c++) {
88
+ lineStr += rowCells[c].ch || ' ';
89
+ }
90
+
91
+ const links = new Array(rowCells.length).fill(null);
92
+ for (let c = 0; c < rowCells.length; c++) {
93
+ if (rowCells[c].link) {
94
+ links[c] = rowCells[c].link;
95
+ }
96
+ }
97
+
98
+ AUTO_URL_REGEX.lastIndex = 0;
99
+ let match;
100
+ while ((match = AUTO_URL_REGEX.exec(lineStr)) !== null) {
101
+ const cleaned = trimUrlTrailingPunct(match[0]);
102
+ const valid = sanitizeUrl(cleaned, whitelist);
103
+ if (!valid) continue;
104
+ const start = match.index;
105
+ const end = start + cleaned.length;
106
+ for (let c = start; c < end && c < links.length; c++) {
107
+ if (!links[c]) {
108
+ links[c] = valid;
109
+ }
110
+ }
111
+ }
112
+ return links;
113
+ }
114
+
115
+ class DomRenderer {
116
+ constructor(container, screen, options = {}) {
117
+ this.container = container;
118
+ this.screen = screen;
119
+ this.cursorStyle = options.cursor || 'none';
120
+ this.urlWhitelist = options.urlWhitelist || DEFAULT_URL_WHITELIST;
121
+ this._rowElements = [];
122
+ this._rafId = null;
123
+ this._lastCursorRow = -1;
124
+ this._lastCursorCol = -1;
125
+ this._lastCursorVisible = false;
126
+ }
127
+
128
+ scheduleRender() {
129
+ if (this._rafId !== null) return;
130
+ if (typeof requestAnimationFrame === 'function') {
131
+ this._rafId = requestAnimationFrame(() => {
132
+ this._rafId = null;
133
+ this.flushRender();
134
+ });
135
+ } else {
136
+ this.flushRender();
137
+ }
138
+ }
139
+
140
+ flushRender() {
141
+ if (this._rafId !== null && typeof cancelAnimationFrame === 'function') {
142
+ cancelAnimationFrame(this._rafId);
143
+ this._rafId = null;
144
+ }
145
+ if (!this.container || typeof document === 'undefined') return;
146
+
147
+ const rows = this.screen.rows;
148
+ this._ensureRowElements(rows);
149
+
150
+ const showCursor = this.cursorStyle !== 'none'
151
+ && this.screen.cursorVisible
152
+ && this.screen.viewportOffset === 0;
153
+ const curRow = showCursor ? this.screen.cursorRow : -1;
154
+ const curCol = showCursor ? this.screen.cursorCol : -1;
155
+
156
+ if (this._lastCursorRow !== curRow || this._lastCursorCol !== curCol || this._lastCursorVisible !== showCursor) {
157
+ if (this._lastCursorRow >= 0 && this._lastCursorRow < rows) {
158
+ this.screen.dirtyRows.add(this._lastCursorRow);
159
+ }
160
+ if (curRow >= 0 && curRow < rows) {
161
+ this.screen.dirtyRows.add(curRow);
162
+ }
163
+ this._lastCursorRow = curRow;
164
+ this._lastCursorCol = curCol;
165
+ this._lastCursorVisible = showCursor;
166
+ }
167
+
168
+ for (const r of this.screen.dirtyRows) {
169
+ if (r >= 0 && r < rows) {
170
+ this._renderRow(r, r === curRow ? curCol : -1);
171
+ }
172
+ }
173
+ this.screen.dirtyRows.clear();
174
+ this.screen.fullRedrawNeeded = false;
175
+ }
176
+
177
+ _ensureRowElements(count) {
178
+ while (this._rowElements.length < count) {
179
+ const el = document.createElement('li');
180
+ if (el.classList) {
181
+ el.classList.add('terminal__line');
182
+ el.classList.add('terminal__row');
183
+ }
184
+ this.container.appendChild(el);
185
+ this._rowElements.push(el);
186
+ }
187
+ while (this._rowElements.length > count) {
188
+ const removed = this._rowElements.pop();
189
+ if (removed && removed.parentNode === this.container && this.container.removeChild) {
190
+ this.container.removeChild(removed);
191
+ }
192
+ }
193
+ }
194
+
195
+ _renderRow(rowIndex, cursorCol) {
196
+ const rowEl = this._rowElements[rowIndex];
197
+ const cells = this.screen.getVisibleRow(rowIndex);
198
+ if (!rowEl || !cells) return;
199
+
200
+ const links = detectRowLinks(cells, this.urlWhitelist);
201
+
202
+ // Determine rightmost meaningful cell so we don't emit trailing unstyled spaces
203
+ // unless in alt screen or up to the cursor column.
204
+ let lastCol = this.screen.isAltScreen ? cells.length - 1 : -1;
205
+ if (!this.screen.isAltScreen) {
206
+ for (let c = cells.length - 1; c >= 0; c--) {
207
+ const cell = cells[c];
208
+ if (cell.ch !== ' ' || cell.fg !== null || cell.bg !== null || cell.flags !== 0 || links[c] !== null) {
209
+ lastCol = c;
210
+ break;
211
+ }
212
+ }
213
+ if (cursorCol > lastCol) {
214
+ lastCol = cursorCol;
215
+ }
216
+ }
217
+
218
+ if (lastCol < 0) {
219
+ rowEl.innerHTML = '';
220
+ return;
221
+ }
222
+
223
+ let html = '';
224
+ let runText = '';
225
+ let runKey = null;
226
+ let runCell = null;
227
+ let runLink = null;
228
+ let runIsCursor = false;
229
+
230
+ const flushRun = () => {
231
+ if (!runText) return;
232
+ html += this._formatRun(runText, runCell, runLink, runIsCursor);
233
+ runText = '';
234
+ };
235
+
236
+ for (let c = 0; c <= lastCol; c++) {
237
+ const cell = cells[c];
238
+ const link = links[c];
239
+ const isCursor = c === cursorCol;
240
+ const key = `${cell.fg ?? ''}|${cell.bg ?? ''}|${cell.flags}|${link ?? ''}|${isCursor ? 1 : 0}`;
241
+
242
+ if (key !== runKey) {
243
+ flushRun();
244
+ runKey = key;
245
+ runCell = cell;
246
+ runLink = link;
247
+ runIsCursor = isCursor;
248
+ }
249
+ runText += cell.ch || ' ';
250
+ }
251
+ flushRun();
252
+
253
+ rowEl.innerHTML = html;
254
+ }
255
+
256
+ _formatRun(text, cell, link, isCursor) {
257
+ const classes = [];
258
+ const styles = [];
259
+ const flags = cell.flags || 0;
260
+ const inverse = (flags & ATTR_INVERSE) !== 0;
261
+
262
+ const fg = inverse ? cell.bg : cell.fg;
263
+ const bg = inverse ? cell.fg : cell.bg;
264
+
265
+ if (inverse && cell.fg === null && cell.bg === null) {
266
+ classes.push('terminal__inverse');
267
+ }
268
+
269
+ if (typeof fg === 'number' && fg >= 0 && fg < 16) {
270
+ classes.push(`${ANSI_COLOR_NAMES[fg]}-fg`);
271
+ } else if (fg !== null) {
272
+ const css = colorIndexToCss(fg);
273
+ if (css) styles.push(`color:${css}`);
274
+ }
275
+
276
+ if (typeof bg === 'number' && bg >= 0 && bg < 16) {
277
+ classes.push(`${ANSI_COLOR_NAMES[bg]}-bg`);
278
+ } else if (bg !== null) {
279
+ const css = colorIndexToCss(bg);
280
+ if (css) styles.push(`background-color:${css}`);
281
+ }
282
+
283
+ if (flags & ATTR_BOLD) styles.push('font-weight:bold');
284
+ if (flags & ATTR_DIM) styles.push('opacity:0.65');
285
+ if (flags & ATTR_ITALIC) styles.push('font-style:italic');
286
+ if ((flags & ATTR_UNDERLINE) && (flags & ATTR_STRIKE)) {
287
+ styles.push('text-decoration:underline line-through');
288
+ } else if (flags & ATTR_UNDERLINE) {
289
+ styles.push('text-decoration:underline');
290
+ } else if (flags & ATTR_STRIKE) {
291
+ styles.push('text-decoration:line-through');
292
+ }
293
+ if (flags & ATTR_BLINK) classes.push('terminal__blink');
294
+ if (flags & ATTR_HIDDEN) styles.push('visibility:hidden');
295
+
296
+ if (isCursor) {
297
+ classes.push('terminal__cursor');
298
+ classes.push(this.cursorStyle);
299
+ }
300
+
301
+ const escapedText = escapeHtml(text);
302
+ let inner = escapedText;
303
+
304
+ if (classes.length > 0 || styles.length > 0) {
305
+ const classAttr = classes.length > 0 ? ` class="${classes.join(' ')}"` : '';
306
+ const styleAttr = styles.length > 0 ? ` style="${styles.join(';')}"` : '';
307
+ inner = `<span${classAttr}${styleAttr}>${escapedText}</span>`;
308
+ }
309
+
310
+ if (link) {
311
+ const safeHref = escapeHtml(link);
312
+ return `<a href="${safeHref}" target="_blank" rel="noopener noreferrer" class="terminal__link">${inner}</a>`;
313
+ }
314
+
315
+ return inner;
316
+ }
317
+ }
318
+
319
+ export {
320
+ DomRenderer,
321
+ detectRowLinks,
322
+ trimUrlTrailingPunct,
323
+ colorIndexToCss
324
+ };
325
+ export default DomRenderer;
@@ -0,0 +1,169 @@
1
+ 'use strict';
2
+
3
+ const PY_PTY_BRIDGE = `
4
+ import os, sys, pty, select, fcntl, termios, struct, signal, json
5
+
6
+ cmd = sys.argv[1]
7
+ args = json.loads(sys.argv[2])
8
+ cols = int(sys.argv[3])
9
+ rows = int(sys.argv[4])
10
+ cwd = sys.argv[5]
11
+
12
+ pid, fd = pty.fork()
13
+ if pid == 0:
14
+ if cwd:
15
+ try: os.chdir(cwd)
16
+ except Exception: pass
17
+ os.execvp(cmd, [cmd] + args)
18
+
19
+ def set_winsize(c, r):
20
+ try:
21
+ fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", r, c, 0, 0))
22
+ os.kill(pid, signal.SIGWINCH)
23
+ except Exception:
24
+ pass
25
+
26
+ set_winsize(cols, rows)
27
+ stdin_fd = sys.stdin.fileno()
28
+ stdout_fd = sys.stdout.fileno()
29
+
30
+ try:
31
+ while True:
32
+ rlist, _, _ = select.select([fd, stdin_fd], [], [])
33
+ if fd in rlist:
34
+ try:
35
+ data = os.read(fd, 8192)
36
+ if not data:
37
+ break
38
+ os.write(stdout_fd, data)
39
+ except OSError:
40
+ break
41
+ if stdin_fd in rlist:
42
+ try:
43
+ chunk = os.read(stdin_fd, 8192)
44
+ if not chunk:
45
+ break
46
+ # Check for inline resize control packet: \\x1b]9999;cols;rows\\x07
47
+ while b"\\x1b]9999;" in chunk:
48
+ start = chunk.find(b"\\x1b]9999;")
49
+ end = chunk.find(b"\\x07", start)
50
+ if end == -1:
51
+ break
52
+ packet = chunk[start+7:end].decode("ascii", "ignore")
53
+ parts = packet.split(";")
54
+ if len(parts) == 2:
55
+ set_winsize(int(parts[0]), int(parts[1]))
56
+ chunk = chunk[:start] + chunk[end+1:]
57
+ if chunk:
58
+ os.write(fd, chunk)
59
+ except OSError:
60
+ break
61
+ finally:
62
+ try:
63
+ os.close(fd)
64
+ except Exception:
65
+ pass
66
+ try:
67
+ _, status = os.waitpid(pid, 0)
68
+ sys.exit(os.waitstatus_to_exitcode(status) if hasattr(os, "waitstatus_to_exitcode") else 0)
69
+ except Exception:
70
+ sys.exit(0)
71
+ `;
72
+
73
+ function getDefaultShell(req) {
74
+ if (typeof process !== 'undefined' && process.env && process.env.SHELL) {
75
+ return process.env.SHELL;
76
+ }
77
+ try {
78
+ const fs = req ? req('fs') : null;
79
+ if (fs) {
80
+ for (const candidate of ['/bin/zsh', '/usr/bin/zsh', '/bin/bash', '/usr/bin/bash', '/bin/sh']) {
81
+ if (fs.existsSync(candidate)) return candidate;
82
+ }
83
+ }
84
+ } catch (_) {}
85
+ return '/bin/sh';
86
+ }
87
+
88
+ export function spawnPty(command, args = [], options = {}) {
89
+ // Dynamic require so browser bundles don't fail trying to bundle child_process
90
+ const req = typeof require === 'function'
91
+ ? require
92
+ : (typeof globalThis !== 'undefined' && globalThis.process && globalThis.process.getBuiltinModule
93
+ ? (m) => globalThis.process.getBuiltinModule(m)
94
+ : null);
95
+
96
+ if (!req) {
97
+ throw new Error('spawnPty is only available in a Node.js environment');
98
+ }
99
+
100
+ const shellCmd = command || getDefaultShell(req);
101
+ const { spawn } = req('child_process');
102
+ const cols = options.cols || 80;
103
+ const rows = options.rows || 24;
104
+ const cwd = options.cwd || (typeof process !== 'undefined' ? process.cwd() : '');
105
+ const env = Object.assign(
106
+ {},
107
+ typeof process !== 'undefined' ? process.env : {},
108
+ {
109
+ TERM: 'xterm-256color',
110
+ COLORTERM: 'truecolor',
111
+ COLUMNS: String(cols),
112
+ LINES: String(rows)
113
+ },
114
+ options.env || {}
115
+ );
116
+
117
+ const child = spawn(
118
+ 'python3',
119
+ ['-u', '-c', PY_PTY_BRIDGE, shellCmd, JSON.stringify(args), String(cols), String(rows), cwd],
120
+ {
121
+ env,
122
+ stdio: ['pipe', 'pipe', 'pipe']
123
+ }
124
+ );
125
+
126
+ const listeners = new Map();
127
+ const emit = (ev, ...a) => {
128
+ const list = listeners.get(ev);
129
+ if (!list) return;
130
+ for (const fn of [...list]) fn(...a);
131
+ };
132
+
133
+ child.stdout.on('data', (chunk) => emit('data', chunk));
134
+ child.on('exit', (code, signal) => emit('exit', code, signal));
135
+ child.on('close', (code) => emit('close', code));
136
+ child.on('error', (err) => emit('error', err));
137
+
138
+ return {
139
+ pid: child.pid,
140
+ process: child,
141
+ write(data) {
142
+ if (child.stdin && !child.stdin.destroyed) {
143
+ child.stdin.write(data);
144
+ }
145
+ },
146
+ resize(c, r) {
147
+ if (child.stdin && !child.stdin.destroyed) {
148
+ child.stdin.write(`\x1b]9999;${Math.max(1, c)};${Math.max(1, r)}\x07`);
149
+ }
150
+ },
151
+ on(event, fn) {
152
+ if (!listeners.has(event)) listeners.set(event, []);
153
+ listeners.get(event).push(fn);
154
+ return this;
155
+ },
156
+ removeListener(event, fn) {
157
+ const list = listeners.get(event);
158
+ if (!list) return this;
159
+ const idx = list.indexOf(fn);
160
+ if (idx !== -1) list.splice(idx, 1);
161
+ return this;
162
+ },
163
+ kill(sig = 'SIGTERM') {
164
+ try { child.kill(sig); } catch (e) { /* ignore */ }
165
+ }
166
+ };
167
+ }
168
+
169
+ export default spawnPty;