brsh 2.8.1 → 3.1.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 (44) hide show
  1. package/.github/workflows/release.yml +3 -1
  2. package/CHANGELOG.md +32 -0
  3. package/POSIX-CHECKLIST.md +3 -3
  4. package/Readme.md +138 -223
  5. package/bin/Readme.md +70 -24
  6. package/bin/brsh-shell.js +16 -131
  7. package/bin/exportFileSystem.js +4 -0
  8. package/bin/zsh-server.js +261 -0
  9. package/dist/brsh.css +1 -1
  10. package/dist/shell.es.js +1020 -648
  11. package/dist/shell.es.js.map +1 -1
  12. package/dist/shell.min.js +34 -19
  13. package/dist/shell.min.js.map +1 -1
  14. package/dist/terminal.cjs.js +77 -100
  15. package/dist/terminal.cjs.js.map +1 -1
  16. package/dist/terminal.es.js +1382 -603
  17. package/dist/terminal.es.js.map +1 -1
  18. package/dist/terminal.min.js +77 -100
  19. package/dist/terminal.min.js.map +1 -1
  20. package/dist/wbt.es.js +410 -238
  21. package/dist/wbt.es.js.map +1 -1
  22. package/dist/wbt.min.js +10 -8
  23. package/dist/wbt.min.js.map +1 -1
  24. package/index.js +472 -0
  25. package/lib/Command.js +30 -0
  26. package/lib/InteractiveCommand.js +28 -0
  27. package/lib/Readme.md +111 -12
  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 +26 -5
  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 +3 -2
  40. package/lib/wbt/registry.js +15 -1
  41. package/package.json +4 -2
  42. package/styles/terminal.css +33 -4
  43. package/test/terminal.test.js +762 -40
  44. package/test/wbt.test.js +92 -0
package/bin/Readme.md CHANGED
@@ -1,33 +1,79 @@
1
- # Export File System
1
+ # CLI Utilities (`bin/`)
2
2
 
3
- the export file system command can be used to export a local folder structure for use as a filesystem in Shell.js
3
+ This directory contains the command-line utilities for building virtual filesystems and running `brsh` in Node.js.
4
4
 
5
- ## What Will it Do?
5
+ ---
6
6
 
7
- it will travers the directory structure from the provided base path, and import all files based on the following rules:
7
+ ## 1. `exportFileSystem`
8
8
 
9
- * Javascript files (.js): imported as node modules, whatever they export will be available to Shell JS, this is really useful for adding new commands just make sure you set module.exports to your Command class
10
- * WebAssembly files (.wasm): automatically wrapped as executable `WasmCommand` binaries (especially when placed in `/bin`) or stored as raw binary files
11
- * Binary files (.jpg, .png, .bmp, .pdf, .zip, etc.): stored as `BinaryFile` instances (or raw zero-overhead byte slices when using `--binary` / `.brfs`)
12
- * all other files: imported as UTF-8 string representations of the data inside (preserving Unix file permissions and symlinks)
9
+ `exportFileSystem` converts a local directory structure into a virtual filesystem bundle or `.brfs` binary container for use in `brsh`.
13
10
 
14
- ## CLI options
11
+ ### How Files Are Imported
15
12
 
16
- | name | alias | variable | description |
17
- | ---- | ----- | -------- | ----------- |
18
- | root | | `String` path | also the default option, this is the path to the root of your file system |
19
- | variable | v | `String` name | final variable output name for instance if set to `filesystem` when this file is loaded in a browser it will be accessible at `window.filesystem` |
20
- | output | o | `String` path | path for the output file (`.js` bundle or standalone `.brfs` binary container; if not set will output to stdout) |
21
- | binary | b | | emit an indexed `BRFS` binary container (`.brfs`) with raw binary payloads, permissions, and symlinks instead of base64-in-JS |
22
- | compress | c | | emit a gzip-compressed bundle alongside a browser decompression loader (legacy `.brsh` / `.brfs` mode) |
23
- | pretty | p | | if pretty is set we will disable code uglification and pretify the json directory structure |
24
- | hyperlinks | h | | enable experimental hyperlink support for application (this will pass through an environment variable to your filesystem FORCE_HYPERLINK some libraries will pick up on this and pass back ansi links) |
13
+ `exportFileSystem` traverses the directory structure from the provided root path and imports files according to the following rules:
25
14
 
26
- ## how does it work
15
+ * **JavaScript files (`.js`)**: Bundled via `esbuild` as CommonJS/ESM modules. Whatever they export is available directly to `brsh` — useful for adding custom `Command` classes (`module.exports = MyCommand`).
16
+ * **WebAssembly files (`.wasm`)**: Automatically wrapped as executable `WasmCommand` binaries (when placed in `/bin`) or stored as raw binary files.
17
+ * **Binary files (`.jpg`, `.png`, `.gif`, `.bmp`, `.webp`, `.ico`, `.pdf`, `.zip`, etc.)**: Stored as `BinaryFile` (`Uint8Array`) instances (or zero-overhead byte slices when using `--binary` / `.brfs`).
18
+ * **All other files**: Imported as UTF-8 strings, preserving Unix file permissions (`mode`) and symbolic links (`SymlinkRef`).
27
19
 
28
- most of the heavy lifting is done by [browserify](http://browserify.org/) and the following awesome plugins:
20
+ ### CLI Options
29
21
 
30
- * [Stringify](http://johnpostlethwait.github.io/stringify/)
31
- * [Imgurify](https://github.com/asbjornenge/imgurify)
32
- * [Bundle Collapser](https://github.com/substack/bundle-collapser)
33
- * [Uglifyify](https://github.com/hughsk/uglifyify)
22
+ | Option | Alias | Type | Description |
23
+ | ------ | ----- | ---- | ----------- |
24
+ | `root` | | `String` path | *(Default positional option, required)* Path to the root directory of your filesystem |
25
+ | `variable` | `-v` | `String` name | Global variable name (`globalThis.<variable>`) assigned when outputting a `.js` bundle (`{ filesystem, permissions }`). Not required when `-o` ends with `.brfs` |
26
+ | `output` | `-o` | `String` path | Output file path (`.js` bundle or standalone `.brfs` binary container) |
27
+ | `binary` | `-b` | `Boolean` | Emit an indexed `BRFS` binary container (`.brfs`) with raw binary payloads, permissions, symlinks, and bundled JS commands instead of base64-in-JS |
28
+ | `compress` | `-c` | `Boolean` | Gzip-compress the emitted `.brfs` container (or JS bundle) and generate a browser `DecompressionStream` loader when outputting `.js` |
29
+ | `pretty` | `-p` | `Boolean` | Disable minification and pretty-print the JSON directory structure |
30
+ | `hyperlinks` | `-h` | `Boolean` | Set `process.env.FORCE_HYPERLINK="true"` in bundled JS commands so libraries emit ANSI OSC 8 hyperlinks |
31
+
32
+ ### Examples
33
+
34
+ ```shell
35
+ # Standard JS bundle (sets globalThis.fs = { filesystem, permissions })
36
+ exportFileSystem ./demo/filesystem -o ./demo/fs.js -v fs
37
+
38
+ # Standalone .brfs binary container (pass URL or Uint8Array directly to new Shell({ filesystem: '/fs.brfs' }))
39
+ exportFileSystem ./demo/filesystem -o ./demo/fs.brfs
40
+
41
+ # Binary .brfs container + tiny JS loader (sets globalThis.fs = Promise<{ filesystem, permissions }>)
42
+ exportFileSystem ./demo/filesystem -o ./demo/fs.js -v fs --binary --compress
43
+ ```
44
+
45
+ ### How It Works
46
+
47
+ `exportFileSystem` uses [`lib/buildFilesystemStructure.js`](../lib/buildFilesystemStructure.js) to walk the directory tree and record file contents, permissions, and symlinks, [`esbuild`](https://esbuild.github.io/) with `esbuild-plugin-polyfill-node` to bundle any `.js` command modules for the browser, and [`lib/BinaryContainer.js`](../lib/BinaryContainer.js) to serialize `.brfs` binary containers.
48
+
49
+ ---
50
+
51
+ ## 2. `brsh` (`bin/brsh-shell.js`)
52
+
53
+ Interactive Node.js REPL and non-interactive script/command runner backed by `brsh` (with `wbt` and `pico` pre-registered).
54
+
55
+ ```shell
56
+ # Interactive REPL against the real Node.js filesystem
57
+ brsh
58
+
59
+ # Interactive REPL against the virtual demo filesystem
60
+ brsh --demo
61
+
62
+ # Run a single command string and exit
63
+ brsh -c "ls -la | grep Readme"
64
+
65
+ # Run a script file with arguments and shell flags (-e, -x)
66
+ brsh -e -x ./myscript.sh arg1 arg2
67
+ ```
68
+
69
+ ---
70
+
71
+ ## 3. `bin/brsh-cmd.js`
72
+
73
+ Multi-call CLI wrapper used by the BusyBox compatibility test suite. Can be invoked directly (`node bin/brsh-cmd.js grep foo file.txt`) or symlinked under a command's name (`cat`, `cp`, `grep`, `ls`, `mv`, `rm`, `busybox`, etc.) to run any `brsh` command against the real Node.js filesystem.
74
+
75
+ ---
76
+
77
+ ## 4. `bin/zsh-server.js`
78
+
79
+ Zero-dependency HTTP + WebSocket server (`npm run demo:zsh`) that spawns a real OS shell (`$SHELL` / `/bin/zsh`) via [`lib/terminal/PtyBridge.js`](../lib/terminal/PtyBridge.js) and attaches it to `brsh/terminal` in the browser at `http://127.0.0.1:3080`.
package/bin/brsh-shell.js CHANGED
@@ -14,7 +14,6 @@ const Shell = require('../index.js');
14
14
  const Wbt = require('../lib/wbt');
15
15
  const Pico = require('../demo/pico');
16
16
  const { buildStructure } = require('../lib/buildFilesystemStructure');
17
- const readline = require('readline');
18
17
  const nodePath = require('path');
19
18
 
20
19
  function resolveRequireNodes(node) {
@@ -99,11 +98,7 @@ const shell = new Shell(shellOptions);
99
98
  shell.context.setCommand(Wbt);
100
99
  shell.context.setCommand(Pico);
101
100
 
102
- let destroyed = false;
103
- let rl;
104
- let inInteractiveApp = false;
105
-
106
- // ── Terminal size reporting ───────────────────────────────────────────────────
101
+ // ── Terminal streams & size reporting ─────────────────────────────────────────
107
102
 
108
103
  function reportSize() {
109
104
  if (process.stdout.isTTY) {
@@ -111,36 +106,8 @@ function reportSize() {
111
106
  }
112
107
  }
113
108
 
114
- process.stdout.on('resize', () => { if (inInteractiveApp) reportSize(); });
115
-
116
- let inProgressLine = false;
117
- shell.on('stdOut', line => {
118
- if (inInteractiveApp) {
119
- process.stdout.write(line);
120
- } else if (typeof line === 'string' && line.startsWith('\r')) {
121
- inProgressLine = true;
122
- process.stdout.write('\r\x1b[K' + line.slice(1));
123
- } else {
124
- if (inProgressLine) {
125
- process.stdout.write('\n');
126
- inProgressLine = false;
127
- }
128
- process.stdout.write(line + '\n');
129
- }
130
- });
131
- shell.on('stdErr', line => {
132
- if (inProgressLine) {
133
- process.stdout.write('\n');
134
- inProgressLine = false;
135
- }
136
- process.stderr.write(line + '\n');
137
- });
138
-
139
- shell.on('exit', code => {
140
- destroyed = true;
141
- if (rl) rl.close();
142
- process.exit(code);
143
- });
109
+ process.stdout.on('resize', reportSize);
110
+ reportSize();
144
111
 
145
112
  // ── Non-interactive execution ─────────────────────────────────────────────────
146
113
 
@@ -173,6 +140,10 @@ async function runNonInteractive() {
173
140
  }
174
141
 
175
142
  if (!isInteractive) {
143
+ shell.stdout.pipe(process.stdout);
144
+ shell.stderr.pipe(process.stderr);
145
+ process.stdin.pipe(shell.stdinStream);
146
+
176
147
  const onReady = status => {
177
148
  if (status === Shell.STATUS_READY) {
178
149
  shell.removeListener('status', onReady);
@@ -185,105 +156,19 @@ if (!isInteractive) {
185
156
 
186
157
  // ── Interactive mode ──────────────────────────────────────────────────────────
187
158
 
188
- shell.on('status', status => {
189
- if (status !== Shell.STATUS_READY) return;
190
- if (inInteractiveApp) {
191
- inInteractiveApp = false;
192
- process.stdin.removeListener('data', rawDataHandler);
193
- if (process.stdin.isTTY) process.stdin.setRawMode(false);
194
- rl.resume();
195
- }
196
- ask();
197
- });
198
-
199
- function prompt() {
200
- const cwd = (shell.context.fs && shell.context.fs.cwd) || '~';
201
- const host = shell.context.getVar('HOST') || 'brsh';
202
- return `${host}:${cwd}$ `;
203
- }
204
-
205
- function completer(line) {
206
- const tokens = line.split(/\s+/);
207
- const partial = tokens[tokens.length - 1];
208
- const result = shell.context.fs.autoComplete(partial, shell.context.getVar('PATH'));
209
- if (!result) return [[], partial];
210
- const prefix = result.path ? result.path + '/' : '';
211
- const completions = result.options.map(opt => prefix + opt);
212
- return [completions, partial];
159
+ if (process.stdin.isTTY) {
160
+ process.stdin.setRawMode(true);
161
+ process.stdin.resume();
213
162
  }
214
163
 
215
- rl = readline.createInterface({
216
- input: process.stdin,
217
- output: process.stdout,
218
- terminal: true,
219
- completer
220
- });
221
-
222
- // Report initial terminal size so COLUMNS/LINES are correct from the start
223
- reportSize();
224
-
225
- function ask() {
226
- rl.question(prompt(), line => {
227
- if (line === null) {
228
- rl.close();
229
- process.exit(0);
230
- }
231
- shell.onCommand(line)
232
- .then(() => ask())
233
- .catch(() => ask());
234
- });
235
- }
236
-
237
- rl.on('close', () => { if (!destroyed) process.exit(0); });
238
-
239
- // Forward typed lines to commands waiting for input (e.g. `read`)
240
- rl.on('line', function(line) {
241
- if (shell.runningCommand && shell.runningCommand.captureInput && !inInteractiveApp) {
242
- for (const char of line) { shell.onInput(char); }
243
- shell.onInput('Enter');
244
- }
245
- });
164
+ process.stdin.pipe(shell.stdinStream);
165
+ shell.stdout.pipe(process.stdout);
166
+ shell.stderr.pipe(process.stderr);
246
167
 
247
- // ── Raw key input for interactive full-screen apps ────────────────────────────
248
-
249
- function parseRawKey(buf) {
250
- const str = buf.toString('binary');
251
- if (str.length === 1) {
252
- const code = str.charCodeAt(0);
253
- if (code === 0x0d || code === 0x0a) return 'Enter';
254
- if (code === 0x7f || code === 0x08) return 'Backspace';
255
- if (code === 0x09) return 'Tab';
256
- if (code === 0x1b) return 'Escape';
257
- if (code >= 0x01 && code <= 0x1a) return '^' + String.fromCharCode(code + 0x40);
258
- return str;
259
- }
260
- if (str.startsWith('\x1b[') || str.startsWith('\x1bO')) {
261
- const seq = str.slice(2);
262
- const named = {
263
- A: 'ArrowUp', B: 'ArrowDown', C: 'ArrowRight', D: 'ArrowLeft',
264
- H: 'Home', F: 'End',
265
- '1~': 'Home', '3~': 'Delete', '4~': 'End',
266
- '5~': 'PageUp', '6~': 'PageDown',
267
- '7~': 'Home', '8~': 'End'
268
- };
269
- return named[seq] || null;
270
- }
271
- return null;
272
- }
273
-
274
- function rawDataHandler(buf) {
275
- const key = parseRawKey(buf);
276
- if (key !== null) shell.onInput(key);
277
- }
278
-
279
- shell.on('interactive', () => {
280
- inInteractiveApp = true;
281
- reportSize();
282
- rl.pause();
168
+ shell.on('exit', code => {
283
169
  if (process.stdin.isTTY) {
284
- process.stdin.setRawMode(true);
285
- process.stdin.resume();
170
+ try { process.stdin.setRawMode(false); } catch (_) {}
286
171
  }
287
- process.stdin.on('data', rawDataHandler);
172
+ process.exit(code);
288
173
  });
289
174
 
@@ -302,5 +302,9 @@ if (useBinaryContainer) {
302
302
  console.log(`Compressed bundle written to ${gzPath}`);
303
303
  }
304
304
  console.log('Build succeeded');
305
+ })
306
+ .catch(err => {
307
+ console.error(err);
308
+ process.exit(1);
305
309
  });
306
310
  }
@@ -0,0 +1,261 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const http = require('http');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const crypto = require('crypto');
8
+
9
+ const PORT = parseInt(process.env.PORT || '3080', 10);
10
+ const SHELL_CMD = process.env.SHELL || '/bin/zsh';
11
+
12
+ const HTML_PAGE = `<!DOCTYPE html>
13
+ <html lang="en">
14
+ <head>
15
+ <meta charset="UTF-8">
16
+ <title>brsh Terminal — Real zsh PTY</title>
17
+ <link rel="stylesheet" href="/dist/brsh.css">
18
+ <style>
19
+ html, body {
20
+ margin: 0;
21
+ padding: 0;
22
+ width: 100%;
23
+ height: 100%;
24
+ background: #14161b;
25
+ color: #e6e8ee;
26
+ display: flex;
27
+ flex-direction: column;
28
+ overflow: hidden;
29
+ font-family: 'Roboto Mono', monospace;
30
+ }
31
+ header {
32
+ background: #1f232b;
33
+ border-bottom: 1px solid #2e3440;
34
+ padding: 6px 14px;
35
+ font-size: 12px;
36
+ display: flex;
37
+ justify-content: space-between;
38
+ align-items: center;
39
+ user-select: none;
40
+ }
41
+ header .badge {
42
+ background: #2e7d32;
43
+ color: #fff;
44
+ padding: 2px 8px;
45
+ border-radius: 4px;
46
+ font-weight: bold;
47
+ }
48
+ #terminal {
49
+ flex: 1;
50
+ padding: 8px 10px;
51
+ overflow-y: auto;
52
+ box-sizing: border-box;
53
+ }
54
+ </style>
55
+ </head>
56
+ <body>
57
+ <header>
58
+ <span id="term-title">brsh/terminal — Connected to ${SHELL_CMD}</span>
59
+ <span class="badge" id="status-badge">LIVE PTY</span>
60
+ </header>
61
+ <div id="terminal"></div>
62
+ <script src="/dist/terminal.min.js"></script>
63
+ <script>
64
+ const ws = new WebSocket(\`ws://\${location.host}/pty\`);
65
+ const statusBadge = document.getElementById('status-badge');
66
+ const titleEl = document.getElementById('term-title');
67
+
68
+ ws.addEventListener('open', () => {
69
+ const term = new Terminal({
70
+ el: document.getElementById('terminal'),
71
+ stream: ws,
72
+ cursor: 'blink',
73
+ lineWrap: false
74
+ });
75
+
76
+ term.onResize(({ cols, rows }) => {
77
+ if (ws.readyState === WebSocket.OPEN) {
78
+ ws.send(\`\\x1b]9999;\${cols};\${rows}\\x07\`);
79
+ }
80
+ });
81
+
82
+ term.onTitleChange((title) => {
83
+ titleEl.textContent = title || 'brsh/terminal';
84
+ });
85
+
86
+ // Send initial measured size once ready
87
+ setTimeout(() => {
88
+ term._measureAndSetSize();
89
+ if (ws.readyState === WebSocket.OPEN) {
90
+ ws.send(\`\\x1b]9999;\${term.cols};\${term.rows}\\x07\`);
91
+ }
92
+ }, 100);
93
+
94
+ window.term = term;
95
+ });
96
+
97
+ ws.addEventListener('close', () => {
98
+ statusBadge.textContent = 'EXITED';
99
+ statusBadge.style.background = '#c62828';
100
+ });
101
+ </script>
102
+ </body>
103
+ </html>`;
104
+
105
+ function encodeWsFrame(str) {
106
+ const payload = Buffer.from(str, 'utf8');
107
+ const len = payload.length;
108
+ let header;
109
+ if (len < 126) {
110
+ header = Buffer.alloc(2);
111
+ header[0] = 0x81; // FIN + text frame
112
+ header[1] = len;
113
+ } else if (len < 65536) {
114
+ header = Buffer.alloc(4);
115
+ header[0] = 0x81;
116
+ header[1] = 126;
117
+ header.writeUInt16BE(len, 2);
118
+ } else {
119
+ header = Buffer.alloc(10);
120
+ header[0] = 0x81;
121
+ header[1] = 127;
122
+ header.writeBigUInt64BE(BigInt(len), 2);
123
+ }
124
+ return Buffer.concat([header, payload]);
125
+ }
126
+
127
+ function decodeWsFrames(buffer, onMessage, onClose) {
128
+ let offset = 0;
129
+ while (offset + 2 <= buffer.length) {
130
+ const byte0 = buffer[offset];
131
+ const byte1 = buffer[offset + 1];
132
+ const opcode = byte0 & 0x0f;
133
+ const isMasked = (byte1 & 0x80) !== 0;
134
+ let payloadLen = byte1 & 0x7f;
135
+ let headerLen = 2;
136
+
137
+ if (payloadLen === 126) {
138
+ if (offset + 4 > buffer.length) break;
139
+ payloadLen = buffer.readUInt16BE(offset + 2);
140
+ headerLen = 4;
141
+ } else if (payloadLen === 127) {
142
+ if (offset + 10 > buffer.length) break;
143
+ payloadLen = Number(buffer.readBigUInt64BE(offset + 2));
144
+ headerLen = 10;
145
+ }
146
+
147
+ const maskLen = isMasked ? 4 : 0;
148
+ const totalFrameLen = headerLen + maskLen + payloadLen;
149
+ if (offset + totalFrameLen > buffer.length) break;
150
+
151
+ if (opcode === 0x08) {
152
+ onClose();
153
+ return Buffer.alloc(0);
154
+ }
155
+
156
+ if (opcode === 0x01 || opcode === 0x02) {
157
+ const payload = Buffer.alloc(payloadLen);
158
+ const dataStart = offset + headerLen + maskLen;
159
+ if (isMasked) {
160
+ const maskOffset = offset + headerLen;
161
+ for (let i = 0; i < payloadLen; i++) {
162
+ payload[i] = buffer[dataStart + i] ^ buffer[maskOffset + (i & 3)];
163
+ }
164
+ } else {
165
+ buffer.copy(payload, 0, dataStart, dataStart + payloadLen);
166
+ }
167
+ onMessage(payload.toString('utf8'));
168
+ }
169
+
170
+ offset += totalFrameLen;
171
+ }
172
+ return buffer.slice(offset);
173
+ }
174
+
175
+ async function startServer() {
176
+ const { spawnPty } = await import('../lib/terminal/PtyBridge.js');
177
+
178
+ const server = http.createServer((req, res) => {
179
+ if (req.url === '/' || req.url === '/index.html') {
180
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
181
+ res.end(HTML_PAGE);
182
+ return;
183
+ }
184
+
185
+ if (req.url.startsWith('/dist/')) {
186
+ const safeName = path.basename(req.url);
187
+ const filePath = path.join(__dirname, '..', 'dist', safeName);
188
+ if (fs.existsSync(filePath)) {
189
+ const ext = path.extname(safeName);
190
+ const mime = ext === '.css' ? 'text/css' : ext === '.js' ? 'application/javascript' : 'application/octet-stream';
191
+ res.writeHead(200, { 'Content-Type': mime });
192
+ res.end(fs.readFileSync(filePath));
193
+ return;
194
+ }
195
+ }
196
+
197
+ res.writeHead(404);
198
+ res.end('Not found');
199
+ });
200
+
201
+ server.on('upgrade', (req, socket) => {
202
+ if (req.url !== '/pty') {
203
+ socket.destroy();
204
+ return;
205
+ }
206
+
207
+ const key = req.headers['sec-websocket-key'];
208
+ const accept = crypto
209
+ .createHash('sha1')
210
+ .update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
211
+ .digest('base64');
212
+
213
+ socket.write(
214
+ 'HTTP/1.1 101 Switching Protocols\r\n' +
215
+ 'Upgrade: websocket\r\n' +
216
+ 'Connection: Upgrade\r\n' +
217
+ `Sec-WebSocket-Accept: ${accept}\r\n\r\n`
218
+ );
219
+
220
+ const pty = spawnPty(SHELL_CMD, ['-i'], {
221
+ cols: 80,
222
+ rows: 24,
223
+ cwd: process.cwd()
224
+ });
225
+
226
+ pty.on('data', (chunk) => {
227
+ if (!socket.destroyed) {
228
+ const str = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
229
+ socket.write(encodeWsFrame(str));
230
+ }
231
+ });
232
+
233
+ pty.on('exit', () => {
234
+ if (!socket.destroyed) {
235
+ socket.end(Buffer.from([0x88, 0x00]));
236
+ }
237
+ });
238
+
239
+ let rxBuffer = Buffer.alloc(0);
240
+ socket.on('data', (chunk) => {
241
+ rxBuffer = Buffer.concat([rxBuffer, chunk]);
242
+ rxBuffer = decodeWsFrames(
243
+ rxBuffer,
244
+ (msg) => pty.write(msg),
245
+ () => {
246
+ pty.kill();
247
+ socket.end();
248
+ }
249
+ );
250
+ });
251
+
252
+ socket.on('close', () => pty.kill());
253
+ socket.on('error', () => pty.kill());
254
+ });
255
+
256
+ server.listen(PORT, '127.0.0.1', () => {
257
+ console.log(`zsh terminal server listening on http://127.0.0.1:${PORT}`);
258
+ });
259
+ }
260
+
261
+ startServer();
package/dist/brsh.css CHANGED
@@ -1,2 +1,2 @@
1
- .terminal__cursor{display:inline-block}.terminal__screen{white-space:pre;flex:1;margin:0;padding:0;line-height:1.15em;display:none;overflow:hidden}.terminal__char-measure{visibility:hidden;pointer-events:none;white-space:pre;line-height:1.15em;position:absolute}.terminal__cursor.blink{animation:1s step-end .5s infinite blink}.terminal__cursor.block{color:rgb(from currentColor calc(255 - r) calc(255 - g) calc(255 - b));background-color:currentColor}.terminal__line{white-space:pre;min-height:1.15em;line-height:1.15em;overflow:hidden}.terminal--wrap .terminal__line,.terminal--wrap li{white-space:pre-wrap;overflow:visible}@keyframes blink{0%,to{-webkit-text-fill-color:rgb(from currentColor calc(255 - r) calc(255 - g) calc(255 - b));background-color:currentColor}50%{-webkit-text-fill-color:unset;background-color:#0000}}.ansi-black-fg{color:#000}.ansi-black-bg{background:#000}.ansi-red-fg{color:#b00}.ansi-red-bg{background:#b00}.ansi-green-fg{color:#0b0}.ansi-green-bg{background:#0b0}.ansi-yellow-fg{color:#bb0}.ansi-yellow-bg{background:#bb0}.ansi-blue-fg{color:#00b}.ansi-blue-bg{background:#00b}.ansi-magenta-fg{color:#b0b}.ansi-magenta-bg{background:#b0b}.ansi-cyan-fg{color:#0bb}.ansi-cyan-bg{background:#0bb}.ansi-white-fg{color:#fff}.ansi-white-bg{background:#fff}.ansi-bright-black-fg{color:#555}.ansi-bright-black-bg{background:#555}.ansi-bright-red-fg{color:#f55}.ansi-bright-red-bg{background:#f55}.ansi-bright-green-fg{color:#0f0}.ansi-bright-green-bg{background:#0f0}.ansi-bright-yellow-fg{color:#ff5}.ansi-bright-yellow-bg{background:#ff5}.ansi-bright-blue-fg{color:#55f}.ansi-bright-blue-bg{background:#55f}.ansi-bright-magenta-fg{color:#f5f}.ansi-bright-magenta-bg{background:#f5f}.ansi-bright-cyan-fg{color:#5ff}.ansi-bright-cyan-bg{background:#5ff}.ansi-bright-white-fg{color:#fff}.ansi-bright-white-bg{background:#fff}
1
+ .terminal__cursor{display:inline-block}.terminal__screen{white-space:pre;flex:1;margin:0;padding:0;line-height:1.15em;display:none;overflow:hidden}.terminal__char-measure{visibility:hidden;pointer-events:none;white-space:pre;line-height:1.15em;position:absolute}.terminal__cursor.block,.terminal__cursor.blink{-webkit-text-fill-color:rgb(from currentColor calc(255 - r) calc(255 - g) calc(255 - b));color:rgb(from currentColor calc(255 - r) calc(255 - g) calc(255 - b));background-color:currentColor}.terminal__cursor.blink{animation:1s step-end infinite blink}.terminal__inverse{-webkit-text-fill-color:rgb(from currentColor calc(255 - r) calc(255 - g) calc(255 - b));color:rgb(from currentColor calc(255 - r) calc(255 - g) calc(255 - b));background-color:currentColor}.terminal__blink{animation:1s step-end infinite blink-text}.terminal__link{color:inherit;cursor:pointer;text-decoration:underline}.terminal__line{white-space:pre;min-height:1.15em;line-height:1.15em;overflow:hidden}.terminal--wrap .terminal__line,.terminal--wrap li{white-space:pre-wrap;overflow:visible}@keyframes blink{0%,49.9%{-webkit-text-fill-color:rgb(from currentColor calc(255 - r) calc(255 - g) calc(255 - b));color:rgb(from currentColor calc(255 - r) calc(255 - g) calc(255 - b));background-color:currentColor}50%,to{-webkit-text-fill-color:unset;color:inherit;background-color:#0000}}@keyframes blink-text{0%,49.9%{opacity:1}50%,to{opacity:0}}.ansi-black-fg{color:#000}.ansi-black-bg{background:#000}.ansi-red-fg{color:#b00}.ansi-red-bg{background:#b00}.ansi-green-fg{color:#0b0}.ansi-green-bg{background:#0b0}.ansi-yellow-fg{color:#bb0}.ansi-yellow-bg{background:#bb0}.ansi-blue-fg{color:#00b}.ansi-blue-bg{background:#00b}.ansi-magenta-fg{color:#b0b}.ansi-magenta-bg{background:#b0b}.ansi-cyan-fg{color:#0bb}.ansi-cyan-bg{background:#0bb}.ansi-white-fg{color:#fff}.ansi-white-bg{background:#fff}.ansi-bright-black-fg{color:#555}.ansi-bright-black-bg{background:#555}.ansi-bright-red-fg{color:#f55}.ansi-bright-red-bg{background:#f55}.ansi-bright-green-fg{color:#0f0}.ansi-bright-green-bg{background:#0f0}.ansi-bright-yellow-fg{color:#ff5}.ansi-bright-yellow-bg{background:#ff5}.ansi-bright-blue-fg{color:#55f}.ansi-bright-blue-bg{background:#55f}.ansi-bright-magenta-fg{color:#f5f}.ansi-bright-magenta-bg{background:#f5f}.ansi-bright-cyan-fg{color:#5ff}.ansi-bright-cyan-bg{background:#5ff}.ansi-bright-white-fg{color:#fff}.ansi-bright-white-bg{background:#fff}
2
2
  /*$vite$:1*/