brsh 2.6.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/Readme.md +127 -0
- package/bin/Readme.md +6 -3
- package/bin/brsh-shell.js +53 -8
- package/bin/exportFileSystem.js +192 -80
- package/dist/shell.es.js +2419 -1277
- package/dist/shell.es.js.map +1 -1
- package/dist/shell.min.js +21 -14
- package/dist/shell.min.js.map +1 -1
- package/dist/terminal.es.js +2475 -1333
- package/dist/terminal.es.js.map +1 -1
- package/dist/terminal.min.js +23 -16
- package/dist/terminal.min.js.map +1 -1
- package/dist/wbt.es.js +9449 -0
- package/dist/wbt.es.js.map +1 -0
- package/dist/wbt.min.js +24 -0
- package/dist/wbt.min.js.map +1 -0
- package/index.js +131 -20
- package/lib/BinaryContainer.js +528 -0
- package/lib/Command.js +2 -1
- package/lib/FileSystem.js +31 -0
- package/lib/NodeFileSystem.js +19 -9
- package/lib/ReplCommand.js +520 -0
- package/lib/ScriptCommand.js +1 -1
- package/lib/WasmCommand.js +1123 -35
- package/lib/buildFilesystemStructure.js +15 -4
- package/lib/wbt/daemon.js +264 -0
- package/lib/wbt/index.js +779 -0
- package/lib/wbt/packages/pglite.js +590 -0
- package/lib/wbt/registry.js +190 -0
- package/lib/wbt/utils.js +118 -0
- package/package.json +9 -2
- package/test/binary-filesystem.test.js +248 -0
- package/test/exportFileSystem.test.js +78 -0
- package/test/wbt.test.js +1084 -0
- package/vite.config.demo.js +4 -0
- package/vite.config.js +4 -0
- package/vite.config.wbt.js +21 -0
|
@@ -13,8 +13,13 @@ const BINARY_MIME = {
|
|
|
13
13
|
'.bmp': 'image/bmp',
|
|
14
14
|
'.webp': 'image/webp',
|
|
15
15
|
'.ico': 'image/x-icon',
|
|
16
|
+
'.wasm': 'application/wasm',
|
|
16
17
|
};
|
|
17
18
|
|
|
19
|
+
function _isWasmBuffer(buf) {
|
|
20
|
+
return buf.length >= 4 && buf[0] === 0x00 && buf[1] === 0x61 && buf[2] === 0x73 && buf[3] === 0x6d;
|
|
21
|
+
}
|
|
22
|
+
|
|
18
23
|
/**
|
|
19
24
|
* Recursively builds a filesystem structure object from a real directory.
|
|
20
25
|
* Returns { filesystem, permissions } where:
|
|
@@ -50,16 +55,22 @@ function _buildTree(root, virtualPrefix, permissions) {
|
|
|
50
55
|
const filePath = path.join(root, handle);
|
|
51
56
|
const isJavaScript = handle.endsWith('.js');
|
|
52
57
|
const ext = path.extname(handle).toLowerCase();
|
|
53
|
-
const
|
|
58
|
+
const rawBuf = isJavaScript ? null : fs.readFileSync(filePath);
|
|
59
|
+
const isWasmMagic = rawBuf !== null && _isWasmBuffer(rawBuf);
|
|
60
|
+
const isBinary = (ext in BINARY_MIME) || isWasmMagic;
|
|
61
|
+
const mime = BINARY_MIME[ext] || (isWasmMagic ? 'application/wasm' : 'application/octet-stream');
|
|
54
62
|
const fileContents = isJavaScript
|
|
55
63
|
? null
|
|
56
64
|
: isBinary
|
|
57
|
-
? `data:${
|
|
58
|
-
:
|
|
65
|
+
? `data:${mime};base64,${rawBuf.toString('base64')}`
|
|
66
|
+
: rawBuf.toString('utf8');
|
|
59
67
|
|
|
68
|
+
const isWasmExt = ext === '.wasm';
|
|
60
69
|
const key = isJavaScript
|
|
61
70
|
? handle.substring(0, handle.length - 3)
|
|
62
|
-
:
|
|
71
|
+
: isWasmExt
|
|
72
|
+
? handle.substring(0, handle.length - 5)
|
|
73
|
+
: handle;
|
|
63
74
|
|
|
64
75
|
structure[key] = isJavaScript
|
|
65
76
|
? `require('${path.resolve(root, handle)}')`
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Daemon & Virtual Localhost Server Registry for WBT / brsh.
|
|
5
|
+
*
|
|
6
|
+
* Allows WASM packages (such as `pglite` / `pg_ctl` or custom WASM servers) to:
|
|
7
|
+
* 1. Register background daemon processes on a virtual localhost port (e.g. 5432)
|
|
8
|
+
* 2. Optionally bind a real Node `http.Server` or `net.Server` when running in Node
|
|
9
|
+
* 3. Intercept `fetch('http://localhost:<port>/...')` or `fetch('http://127.0.0.1:<port>/...')`
|
|
10
|
+
* in the browser or Node so `curl http://localhost:5432/query -d "SELECT 1"` and web app
|
|
11
|
+
* `fetch()` calls hit the running WASM daemon directly!
|
|
12
|
+
*/
|
|
13
|
+
class DaemonManager {
|
|
14
|
+
constructor() {
|
|
15
|
+
this._daemons = new Map(); // id/port -> daemon entry
|
|
16
|
+
this._nextPid = 1001;
|
|
17
|
+
this._fetchPatched = false;
|
|
18
|
+
this._originalFetch = null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Registers and starts a background daemon.
|
|
23
|
+
*
|
|
24
|
+
* @param {Object} opts
|
|
25
|
+
* @param {string} opts.name - Daemon name (e.g. 'pglite')
|
|
26
|
+
* @param {number} opts.port - Port number (e.g. 5432)
|
|
27
|
+
* @param {string} [opts.host='127.0.0.1'] - Bind address
|
|
28
|
+
* @param {string} [opts.dataDir] - Associated data directory or target
|
|
29
|
+
* @param {Function} opts.handler - async ({ method, url, path, headers, body }) => { status, statusText, headers, body }
|
|
30
|
+
* @param {Function} [opts.onStop] - async cleanup callback when daemon is stopped
|
|
31
|
+
* @param {Object} [opts.instance] - Underlying WASM instance (e.g. PGlite db)
|
|
32
|
+
* @param {Object} [opts.fs] - Optional brsh filesystem to write PID file
|
|
33
|
+
* @param {string} [opts.pidFile] - Optional path to PID file (e.g. `/var/run/pglite.pid`)
|
|
34
|
+
*/
|
|
35
|
+
async startDaemon(opts) {
|
|
36
|
+
const {
|
|
37
|
+
name,
|
|
38
|
+
port = 5432,
|
|
39
|
+
host = '127.0.0.1',
|
|
40
|
+
dataDir = 'memory://',
|
|
41
|
+
handler,
|
|
42
|
+
onStop,
|
|
43
|
+
instance,
|
|
44
|
+
fs,
|
|
45
|
+
pidFile
|
|
46
|
+
} = opts;
|
|
47
|
+
|
|
48
|
+
const numericPort = Number(port);
|
|
49
|
+
if (this._daemons.has(numericPort)) {
|
|
50
|
+
throw new Error(`Port ${numericPort} is already in use by daemon '${this._daemons.get(numericPort).name}' (PID ${this._daemons.get(numericPort).pid})`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const pid = this._nextPid++;
|
|
54
|
+
let nodeHttpServer = null;
|
|
55
|
+
|
|
56
|
+
// Ensure global fetch intercepts http://localhost:<port> and http://127.0.0.1:<port>
|
|
57
|
+
this._ensureFetchInterceptor();
|
|
58
|
+
|
|
59
|
+
// Also optionally bind a real Node http server if requested and in Node
|
|
60
|
+
if (opts.bindNodeServer && typeof process !== 'undefined' && process.versions && process.versions.node) {
|
|
61
|
+
try {
|
|
62
|
+
const http = require('http');
|
|
63
|
+
nodeHttpServer = http.createServer(async (req, res) => {
|
|
64
|
+
try {
|
|
65
|
+
const chunks = [];
|
|
66
|
+
for await (const chunk of req) chunks.push(chunk);
|
|
67
|
+
const rawBody = Buffer.concat(chunks).toString('utf8');
|
|
68
|
+
const urlObj = new URL(req.url || '/', `http://${host}:${numericPort}`);
|
|
69
|
+
const resp = await handler({
|
|
70
|
+
method: req.method || 'GET',
|
|
71
|
+
url: urlObj.toString(),
|
|
72
|
+
path: urlObj.pathname,
|
|
73
|
+
searchParams: urlObj.searchParams,
|
|
74
|
+
headers: req.headers || {},
|
|
75
|
+
body: rawBody
|
|
76
|
+
});
|
|
77
|
+
const status = (resp && resp.status) || 200;
|
|
78
|
+
const respHeaders = Object.assign({
|
|
79
|
+
'content-type': 'application/json',
|
|
80
|
+
'access-control-allow-origin': '*'
|
|
81
|
+
}, (resp && resp.headers) || {});
|
|
82
|
+
res.writeHead(status, respHeaders);
|
|
83
|
+
res.end(typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body ?? {}));
|
|
84
|
+
} catch (err) {
|
|
85
|
+
res.writeHead(500, { 'content-type': 'application/json' });
|
|
86
|
+
res.end(JSON.stringify({ error: err.message || String(err) }));
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
await new Promise((resolve) => {
|
|
90
|
+
nodeHttpServer.once('error', () => {
|
|
91
|
+
nodeHttpServer = null;
|
|
92
|
+
resolve();
|
|
93
|
+
});
|
|
94
|
+
nodeHttpServer.listen(numericPort, host, () => resolve());
|
|
95
|
+
});
|
|
96
|
+
} catch {
|
|
97
|
+
nodeHttpServer = null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const entry = {
|
|
102
|
+
pid,
|
|
103
|
+
name,
|
|
104
|
+
port: numericPort,
|
|
105
|
+
host,
|
|
106
|
+
dataDir,
|
|
107
|
+
startedAt: new Date().toISOString(),
|
|
108
|
+
handler,
|
|
109
|
+
onStop,
|
|
110
|
+
instance,
|
|
111
|
+
nodeHttpServer,
|
|
112
|
+
pidFile,
|
|
113
|
+
fs
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
this._daemons.set(numericPort, entry);
|
|
117
|
+
|
|
118
|
+
if (fs && pidFile) {
|
|
119
|
+
try {
|
|
120
|
+
fs.setFileByPath(pidFile, JSON.stringify({
|
|
121
|
+
pid,
|
|
122
|
+
name,
|
|
123
|
+
port: numericPort,
|
|
124
|
+
host,
|
|
125
|
+
dataDir,
|
|
126
|
+
startedAt: entry.startedAt
|
|
127
|
+
}, null, 2), true);
|
|
128
|
+
} catch { /* ignore */ }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return entry;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async stopDaemon(portOrNameOrPid) {
|
|
135
|
+
const entry = this.getDaemon(portOrNameOrPid);
|
|
136
|
+
if (!entry) return null;
|
|
137
|
+
|
|
138
|
+
this._daemons.delete(entry.port);
|
|
139
|
+
|
|
140
|
+
if (entry.nodeHttpServer) {
|
|
141
|
+
await new Promise(resolve => entry.nodeHttpServer.close(() => resolve()));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (typeof entry.onStop === 'function') {
|
|
145
|
+
try { await entry.onStop(entry); } catch { /* ignore */ }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (entry.fs && entry.pidFile) {
|
|
149
|
+
try { entry.fs.deleteFileByPath(entry.pidFile); } catch { /* ignore */ }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return entry;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async stopAll() {
|
|
156
|
+
const ports = Array.from(this._daemons.keys());
|
|
157
|
+
for (const p of ports) {
|
|
158
|
+
await this.stopDaemon(p);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
getDaemon(portOrNameOrPid) {
|
|
163
|
+
if (portOrNameOrPid === undefined || portOrNameOrPid === null) {
|
|
164
|
+
// Return first daemon if only one is running
|
|
165
|
+
if (this._daemons.size === 1) {
|
|
166
|
+
return this._daemons.values().next().value;
|
|
167
|
+
}
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
const num = Number(portOrNameOrPid);
|
|
171
|
+
if (!Number.isNaN(num) && this._daemons.has(num)) {
|
|
172
|
+
return this._daemons.get(num);
|
|
173
|
+
}
|
|
174
|
+
for (const entry of this._daemons.values()) {
|
|
175
|
+
if (entry.pid === num || entry.name === String(portOrNameOrPid).toLowerCase() || entry.dataDir === portOrNameOrPid) {
|
|
176
|
+
return entry;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
listDaemons() {
|
|
183
|
+
return Array.from(this._daemons.values());
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
_ensureFetchInterceptor() {
|
|
187
|
+
if (this._fetchPatched || typeof globalThis.fetch !== 'function') return;
|
|
188
|
+
const originalFetch = globalThis.fetch.bind(globalThis);
|
|
189
|
+
this._originalFetch = originalFetch;
|
|
190
|
+
const self = this;
|
|
191
|
+
|
|
192
|
+
const patchedFetch = async function wbtDaemonFetch(input, init = {}) {
|
|
193
|
+
const urlStr = typeof input === 'string'
|
|
194
|
+
? input
|
|
195
|
+
: (input && typeof input.url === 'string' ? input.url : String(input));
|
|
196
|
+
|
|
197
|
+
const match = urlStr.match(/^https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0):(\d+)(\/.*)?$/i);
|
|
198
|
+
if (match) {
|
|
199
|
+
const port = Number(match[1]);
|
|
200
|
+
const daemon = self._daemons.get(port);
|
|
201
|
+
if (daemon && typeof daemon.handler === 'function') {
|
|
202
|
+
const urlObj = new URL(urlStr);
|
|
203
|
+
const method = (init.method || (input && input.method) || 'GET').toUpperCase();
|
|
204
|
+
const headers = {};
|
|
205
|
+
if (init.headers) {
|
|
206
|
+
if (typeof init.headers.forEach === 'function') {
|
|
207
|
+
init.headers.forEach((v, k) => { headers[k.toLowerCase()] = v; });
|
|
208
|
+
} else if (typeof init.headers === 'object') {
|
|
209
|
+
for (const [k, v] of Object.entries(init.headers)) {
|
|
210
|
+
headers[k.toLowerCase()] = v;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const body = init.body !== undefined && init.body !== null ? String(init.body) : null;
|
|
215
|
+
|
|
216
|
+
const resp = await daemon.handler({
|
|
217
|
+
method,
|
|
218
|
+
url: urlStr,
|
|
219
|
+
path: urlObj.pathname,
|
|
220
|
+
searchParams: urlObj.searchParams,
|
|
221
|
+
headers,
|
|
222
|
+
body
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
const status = (resp && resp.status) || 200;
|
|
226
|
+
const statusText = (resp && resp.statusText) || (status === 200 ? 'OK' : 'Error');
|
|
227
|
+
const respBody = typeof resp?.body === 'string'
|
|
228
|
+
? resp.body
|
|
229
|
+
: JSON.stringify(resp?.body ?? {});
|
|
230
|
+
const respHeaders = new Map(Object.entries(Object.assign({
|
|
231
|
+
'content-type': 'application/json',
|
|
232
|
+
'x-powered-by': `${daemon.name}-wasm-daemon`
|
|
233
|
+
}, (resp && resp.headers) || {})));
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
ok: status >= 200 && status < 300,
|
|
237
|
+
status,
|
|
238
|
+
statusText,
|
|
239
|
+
headers: {
|
|
240
|
+
get: (k) => respHeaders.get(String(k).toLowerCase()) || null,
|
|
241
|
+
forEach: (cb) => respHeaders.forEach((v, k) => cb(v, k))
|
|
242
|
+
},
|
|
243
|
+
text: async () => respBody,
|
|
244
|
+
json: async () => JSON.parse(respBody),
|
|
245
|
+
arrayBuffer: async () => new TextEncoder().encode(respBody).buffer
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
return originalFetch(input, init);
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
patchedFetch.__isWbtDaemonFetch = true;
|
|
254
|
+
globalThis.fetch = patchedFetch;
|
|
255
|
+
this._fetchPatched = true;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const daemonManager = new DaemonManager();
|
|
260
|
+
|
|
261
|
+
module.exports = {
|
|
262
|
+
DaemonManager,
|
|
263
|
+
daemonManager
|
|
264
|
+
};
|