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
package/lib/WasmCommand.js
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const ScriptCommand = require('./ScriptCommand');
|
|
4
|
+
const { BinaryFile } = require('./FileSystem');
|
|
5
|
+
|
|
6
|
+
// WASI errno constants
|
|
7
|
+
const ERRNO_SUCCESS = 0;
|
|
8
|
+
const ERRNO_BADF = 8;
|
|
9
|
+
const ERRNO_EXIST = 20;
|
|
10
|
+
const ERRNO_INVAL = 28;
|
|
11
|
+
const ERRNO_ISDIR = 31;
|
|
12
|
+
const ERRNO_NOENT = 44;
|
|
13
|
+
const ERRNO_NOTDIR = 54;
|
|
14
|
+
const ERRNO_SPIPE = 70;
|
|
15
|
+
|
|
16
|
+
// WASI filetype constants
|
|
17
|
+
const FILETYPE_UNKNOWN = 0;
|
|
18
|
+
const FILETYPE_CHARACTER_DEVICE = 2;
|
|
19
|
+
const FILETYPE_DIRECTORY = 3;
|
|
20
|
+
const FILETYPE_REGULAR_FILE = 4;
|
|
21
|
+
|
|
22
|
+
// WASI oflags
|
|
23
|
+
const OFLAGS_CREAT = 1 << 0;
|
|
24
|
+
const OFLAGS_DIRECTORY = 1 << 1;
|
|
25
|
+
const OFLAGS_EXCL = 1 << 2;
|
|
26
|
+
const OFLAGS_TRUNC = 1 << 3;
|
|
27
|
+
|
|
28
|
+
// WASI fdflags
|
|
29
|
+
const FDFLAGS_APPEND = 1 << 0;
|
|
4
30
|
|
|
5
31
|
class WasmCommand extends ScriptCommand {
|
|
6
32
|
// this.script = filepath (set by ScriptCommand parent constructor)
|
|
@@ -91,6 +117,7 @@ class WasmCommand extends ScriptCommand {
|
|
|
91
117
|
|
|
92
118
|
const outBuf = { 1: '', 2: '' };
|
|
93
119
|
const decoder = new TextDecoder();
|
|
120
|
+
const encoder = new TextEncoder();
|
|
94
121
|
let memRef = null;
|
|
95
122
|
|
|
96
123
|
const writeFd = (fd, text) => {
|
|
@@ -108,104 +135,446 @@ class WasmCommand extends ScriptCommand {
|
|
|
108
135
|
if (outBuf[2]) { this.stdErr = outBuf[2]; outBuf[2] = ''; }
|
|
109
136
|
};
|
|
110
137
|
|
|
111
|
-
const stdinBytes =
|
|
138
|
+
const stdinBytes = encoder.encode(this.stdin || '');
|
|
112
139
|
let stdinPos = 0;
|
|
113
140
|
|
|
141
|
+
// ── Virtual WASI file descriptor table backed by this.context.fs ──
|
|
142
|
+
// fd 0: stdin, fd 1: stdout, fd 2: stderr
|
|
143
|
+
// fd 3: pre-opened root directory '/'
|
|
144
|
+
// fd 4: pre-opened current working directory '.'
|
|
145
|
+
const fs = this.context && this.context.fs ? this.context.fs : this.fs;
|
|
146
|
+
let nextFd = 5;
|
|
147
|
+
const fdTable = new Map([
|
|
148
|
+
[3, { type: 'preopen', path: '/', guestName: '/' }],
|
|
149
|
+
[4, { type: 'preopen', path: (fs && fs.cwd) || '/', guestName: '.' }]
|
|
150
|
+
]);
|
|
151
|
+
|
|
152
|
+
const resolveGuestPath = (dirFd, relPath) => {
|
|
153
|
+
const dirEntry = fdTable.get(dirFd);
|
|
154
|
+
if (!dirEntry || (dirEntry.type !== 'preopen' && dirEntry.type !== 'dir')) return null;
|
|
155
|
+
if (relPath.startsWith('/')) return fs.absolutePath(relPath);
|
|
156
|
+
const base = dirEntry.path.endsWith('/') ? dirEntry.path : dirEntry.path + '/';
|
|
157
|
+
return fs.absolutePath(base + relPath);
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const flushOpenFile = (entry) => {
|
|
161
|
+
if (!entry || entry.type !== 'file' || !entry.dirty || !fs) return;
|
|
162
|
+
try {
|
|
163
|
+
// Check if bytes are valid UTF-8 text without null bytes
|
|
164
|
+
let isText = true;
|
|
165
|
+
for (let i = 0; i < entry.bytes.length; i++) {
|
|
166
|
+
if (entry.bytes[i] === 0) { isText = false; break; }
|
|
167
|
+
}
|
|
168
|
+
if (isText) {
|
|
169
|
+
const str = decoder.decode(entry.bytes);
|
|
170
|
+
fs.setFileByPath(entry.path, str, true);
|
|
171
|
+
} else {
|
|
172
|
+
const copy = new Uint8Array(entry.bytes.length);
|
|
173
|
+
copy.set(entry.bytes);
|
|
174
|
+
fs.setFileByPath(entry.path, new BinaryFile(copy.buffer, 'application/octet-stream'), true);
|
|
175
|
+
}
|
|
176
|
+
entry.dirty = false;
|
|
177
|
+
} catch {
|
|
178
|
+
// ignore write errors on close
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
// Environment variables from context.vars
|
|
183
|
+
const envPairs = Object.entries((this.context && this.context.vars) || {})
|
|
184
|
+
.map(([k, v]) => `${k}=${v}`);
|
|
185
|
+
|
|
114
186
|
const wasi = {
|
|
115
187
|
fd_write: (fd, iovs, iovs_len, nwritten_ptr) => {
|
|
116
|
-
if (!memRef) return
|
|
188
|
+
if (!memRef) return ERRNO_BADF;
|
|
117
189
|
const view = new DataView(memRef.buffer);
|
|
190
|
+
|
|
191
|
+
if (fd === 1 || fd === 2) {
|
|
192
|
+
let total = 0;
|
|
193
|
+
for (let i = 0; i < iovs_len; i++) {
|
|
194
|
+
const ptr = view.getUint32(iovs + i * 8, true);
|
|
195
|
+
const len = view.getUint32(iovs + i * 8 + 4, true);
|
|
196
|
+
if (len > 0) writeFd(fd, decoder.decode(new Uint8Array(memRef.buffer, ptr, len)));
|
|
197
|
+
total += len;
|
|
198
|
+
}
|
|
199
|
+
view.setUint32(nwritten_ptr, total, true);
|
|
200
|
+
return ERRNO_SUCCESS;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const entry = fdTable.get(fd);
|
|
204
|
+
if (!entry || entry.type !== 'file') return ERRNO_BADF;
|
|
205
|
+
|
|
118
206
|
let total = 0;
|
|
119
207
|
for (let i = 0; i < iovs_len; i++) {
|
|
120
208
|
const ptr = view.getUint32(iovs + i * 8, true);
|
|
121
209
|
const len = view.getUint32(iovs + i * 8 + 4, true);
|
|
122
|
-
if (len > 0)
|
|
123
|
-
|
|
210
|
+
if (len > 0) {
|
|
211
|
+
const chunk = new Uint8Array(memRef.buffer, ptr, len);
|
|
212
|
+
const writePos = entry.append ? entry.bytes.length : entry.pos;
|
|
213
|
+
const needed = writePos + len;
|
|
214
|
+
if (needed > entry.bytes.length) {
|
|
215
|
+
const grown = new Uint8Array(needed);
|
|
216
|
+
grown.set(entry.bytes);
|
|
217
|
+
entry.bytes = grown;
|
|
218
|
+
}
|
|
219
|
+
entry.bytes.set(chunk, writePos);
|
|
220
|
+
entry.pos = writePos + len;
|
|
221
|
+
entry.dirty = true;
|
|
222
|
+
total += len;
|
|
223
|
+
}
|
|
124
224
|
}
|
|
125
225
|
view.setUint32(nwritten_ptr, total, true);
|
|
126
|
-
return
|
|
226
|
+
return ERRNO_SUCCESS;
|
|
127
227
|
},
|
|
128
228
|
fd_read: (fd, iovs, iovs_len, nread_ptr) => {
|
|
129
|
-
if (
|
|
229
|
+
if (!memRef) return ERRNO_BADF;
|
|
130
230
|
const view = new DataView(memRef.buffer);
|
|
231
|
+
|
|
232
|
+
if (fd === 0) {
|
|
233
|
+
let total = 0;
|
|
234
|
+
for (let i = 0; i < iovs_len && stdinPos < stdinBytes.length; i++) {
|
|
235
|
+
const ptr = view.getUint32(iovs + i * 8, true);
|
|
236
|
+
const len = view.getUint32(iovs + i * 8 + 4, true);
|
|
237
|
+
const chunk = Math.min(len, stdinBytes.length - stdinPos);
|
|
238
|
+
new Uint8Array(memRef.buffer).set(stdinBytes.slice(stdinPos, stdinPos + chunk), ptr);
|
|
239
|
+
stdinPos += chunk;
|
|
240
|
+
total += chunk;
|
|
241
|
+
}
|
|
242
|
+
view.setUint32(nread_ptr, total, true);
|
|
243
|
+
return ERRNO_SUCCESS;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const entry = fdTable.get(fd);
|
|
247
|
+
if (!entry || entry.type !== 'file') return ERRNO_BADF;
|
|
248
|
+
|
|
131
249
|
let total = 0;
|
|
132
|
-
for (let i = 0; i < iovs_len &&
|
|
250
|
+
for (let i = 0; i < iovs_len && entry.pos < entry.bytes.length; i++) {
|
|
133
251
|
const ptr = view.getUint32(iovs + i * 8, true);
|
|
134
252
|
const len = view.getUint32(iovs + i * 8 + 4, true);
|
|
135
|
-
const chunk = Math.min(len,
|
|
136
|
-
new Uint8Array(memRef.buffer).set(
|
|
137
|
-
|
|
253
|
+
const chunk = Math.min(len, entry.bytes.length - entry.pos);
|
|
254
|
+
new Uint8Array(memRef.buffer).set(entry.bytes.subarray(entry.pos, entry.pos + chunk), ptr);
|
|
255
|
+
entry.pos += chunk;
|
|
138
256
|
total += chunk;
|
|
139
257
|
}
|
|
140
258
|
view.setUint32(nread_ptr, total, true);
|
|
141
|
-
return
|
|
259
|
+
return ERRNO_SUCCESS;
|
|
260
|
+
},
|
|
261
|
+
fd_seek: (fd, offset_low, offset_high, whence, newoffset_ptr) => {
|
|
262
|
+
if (!memRef) return ERRNO_BADF;
|
|
263
|
+
if (fd <= 2) return ERRNO_SPIPE;
|
|
264
|
+
const entry = fdTable.get(fd);
|
|
265
|
+
if (!entry || entry.type !== 'file') return ERRNO_BADF;
|
|
266
|
+
|
|
267
|
+
// Support both BigInt (i64) and split 32-bit calls
|
|
268
|
+
let off;
|
|
269
|
+
let wh;
|
|
270
|
+
let outPtr;
|
|
271
|
+
if (typeof offset_low === 'bigint') {
|
|
272
|
+
off = Number(offset_low);
|
|
273
|
+
wh = offset_high;
|
|
274
|
+
outPtr = whence;
|
|
275
|
+
} else {
|
|
276
|
+
off = offset_low;
|
|
277
|
+
wh = whence;
|
|
278
|
+
outPtr = newoffset_ptr;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
let target = entry.pos;
|
|
282
|
+
if (wh === 0) target = off; // SEEK_SET
|
|
283
|
+
else if (wh === 1) target = entry.pos + off; // SEEK_CUR
|
|
284
|
+
else if (wh === 2) target = entry.bytes.length + off; // SEEK_END
|
|
285
|
+
else return ERRNO_INVAL;
|
|
286
|
+
|
|
287
|
+
if (target < 0) return ERRNO_INVAL;
|
|
288
|
+
entry.pos = target;
|
|
289
|
+
if (outPtr) {
|
|
290
|
+
new DataView(memRef.buffer).setBigUint64(outPtr, BigInt(entry.pos), true);
|
|
291
|
+
}
|
|
292
|
+
return ERRNO_SUCCESS;
|
|
293
|
+
},
|
|
294
|
+
fd_tell: (fd, offset_ptr) => {
|
|
295
|
+
if (!memRef) return ERRNO_BADF;
|
|
296
|
+
const entry = fdTable.get(fd);
|
|
297
|
+
if (!entry || entry.type !== 'file') return ERRNO_BADF;
|
|
298
|
+
new DataView(memRef.buffer).setBigUint64(offset_ptr, BigInt(entry.pos), true);
|
|
299
|
+
return ERRNO_SUCCESS;
|
|
300
|
+
},
|
|
301
|
+
fd_close: (fd) => {
|
|
302
|
+
if (fd <= 2) return ERRNO_SUCCESS;
|
|
303
|
+
const entry = fdTable.get(fd);
|
|
304
|
+
if (!entry) return ERRNO_BADF;
|
|
305
|
+
flushOpenFile(entry);
|
|
306
|
+
fdTable.delete(fd);
|
|
307
|
+
return ERRNO_SUCCESS;
|
|
308
|
+
},
|
|
309
|
+
fd_sync: (fd) => {
|
|
310
|
+
const entry = fdTable.get(fd);
|
|
311
|
+
if (entry) flushOpenFile(entry);
|
|
312
|
+
return ERRNO_SUCCESS;
|
|
313
|
+
},
|
|
314
|
+
fd_datasync: (fd) => {
|
|
315
|
+
const entry = fdTable.get(fd);
|
|
316
|
+
if (entry) flushOpenFile(entry);
|
|
317
|
+
return ERRNO_SUCCESS;
|
|
318
|
+
},
|
|
319
|
+
fd_prestat_get: (fd, buf_ptr) => {
|
|
320
|
+
if (!memRef) return ERRNO_BADF;
|
|
321
|
+
const entry = fdTable.get(fd);
|
|
322
|
+
if (!entry || entry.type !== 'preopen') return ERRNO_BADF;
|
|
323
|
+
const view = new DataView(memRef.buffer);
|
|
324
|
+
const nameBytes = encoder.encode(entry.guestName);
|
|
325
|
+
view.setUint8(buf_ptr, 0); // PREOPENTYPE_DIR
|
|
326
|
+
view.setUint32(buf_ptr + 4, nameBytes.length, true);
|
|
327
|
+
return ERRNO_SUCCESS;
|
|
328
|
+
},
|
|
329
|
+
fd_prestat_dir_name: (fd, path_ptr, path_len) => {
|
|
330
|
+
if (!memRef) return ERRNO_BADF;
|
|
331
|
+
const entry = fdTable.get(fd);
|
|
332
|
+
if (!entry || entry.type !== 'preopen') return ERRNO_BADF;
|
|
333
|
+
const nameBytes = encoder.encode(entry.guestName);
|
|
334
|
+
new Uint8Array(memRef.buffer, path_ptr, Math.min(path_len, nameBytes.length))
|
|
335
|
+
.set(nameBytes.subarray(0, path_len));
|
|
336
|
+
return ERRNO_SUCCESS;
|
|
337
|
+
},
|
|
338
|
+
fd_fdstat_get: (fd, stat_ptr) => {
|
|
339
|
+
if (!memRef) return ERRNO_BADF;
|
|
340
|
+
const view = new DataView(memRef.buffer);
|
|
341
|
+
let filetype = FILETYPE_UNKNOWN;
|
|
342
|
+
if (fd <= 2) {
|
|
343
|
+
filetype = FILETYPE_CHARACTER_DEVICE;
|
|
344
|
+
} else {
|
|
345
|
+
const entry = fdTable.get(fd);
|
|
346
|
+
if (!entry) return ERRNO_BADF;
|
|
347
|
+
filetype = (entry.type === 'preopen' || entry.type === 'dir')
|
|
348
|
+
? FILETYPE_DIRECTORY
|
|
349
|
+
: FILETYPE_REGULAR_FILE;
|
|
350
|
+
}
|
|
351
|
+
// struct fdstat (24 bytes): fs_filetype (u8), fs_flags (u16), rights_base (u64), rights_inheriting (u64)
|
|
352
|
+
for (let i = 0; i < 24; i++) view.setUint8(stat_ptr + i, 0);
|
|
353
|
+
view.setUint8(stat_ptr, filetype);
|
|
354
|
+
view.setBigUint64(stat_ptr + 8, 0xffffffffffffffffn, true);
|
|
355
|
+
view.setBigUint64(stat_ptr + 16, 0xffffffffffffffffn, true);
|
|
356
|
+
return ERRNO_SUCCESS;
|
|
357
|
+
},
|
|
358
|
+
fd_fdstat_set_flags: () => ERRNO_SUCCESS,
|
|
359
|
+
fd_filestat_get: (fd, buf_ptr) => {
|
|
360
|
+
if (!memRef) return ERRNO_BADF;
|
|
361
|
+
const view = new DataView(memRef.buffer);
|
|
362
|
+
for (let i = 0; i < 64; i++) view.setUint8(buf_ptr + i, 0);
|
|
363
|
+
if (fd <= 2) {
|
|
364
|
+
view.setUint8(buf_ptr + 16, FILETYPE_CHARACTER_DEVICE);
|
|
365
|
+
return ERRNO_SUCCESS;
|
|
366
|
+
}
|
|
367
|
+
const entry = fdTable.get(fd);
|
|
368
|
+
if (!entry) return ERRNO_BADF;
|
|
369
|
+
const isDir = entry.type === 'preopen' || entry.type === 'dir';
|
|
370
|
+
view.setUint8(buf_ptr + 16, isDir ? FILETYPE_DIRECTORY : FILETYPE_REGULAR_FILE);
|
|
371
|
+
view.setBigUint64(buf_ptr + 24, 1n, true); // nlink
|
|
372
|
+
view.setBigUint64(buf_ptr + 32, BigInt(entry.bytes ? entry.bytes.length : 0), true);
|
|
373
|
+
return ERRNO_SUCCESS;
|
|
374
|
+
},
|
|
375
|
+
path_open: (dirfd, dirflags, path_ptr, path_len, oflags, fs_rights_base, fs_rights_inh, fdflags, opened_fd_ptr) => {
|
|
376
|
+
if (!memRef || !fs) return ERRNO_BADF;
|
|
377
|
+
const relPath = decoder.decode(new Uint8Array(memRef.buffer, path_ptr, path_len));
|
|
378
|
+
const absPath = resolveGuestPath(dirfd, relPath);
|
|
379
|
+
if (!absPath) return ERRNO_BADF;
|
|
380
|
+
|
|
381
|
+
const st = fs.stat(absPath);
|
|
382
|
+
const exists = st !== null;
|
|
383
|
+
|
|
384
|
+
if ((oflags & OFLAGS_EXCL) && (oflags & OFLAGS_CREAT) && exists) {
|
|
385
|
+
return ERRNO_EXIST;
|
|
386
|
+
}
|
|
387
|
+
if ((oflags & OFLAGS_DIRECTORY)) {
|
|
388
|
+
if (!exists) return ERRNO_NOENT;
|
|
389
|
+
if (!st.isDirectory) return ERRNO_NOTDIR;
|
|
390
|
+
const newFd = nextFd++;
|
|
391
|
+
fdTable.set(newFd, { type: 'dir', path: absPath });
|
|
392
|
+
new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
|
|
393
|
+
return ERRNO_SUCCESS;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
if (exists && st.isDirectory) {
|
|
397
|
+
return ERRNO_ISDIR;
|
|
398
|
+
}
|
|
399
|
+
if (!exists && !(oflags & OFLAGS_CREAT)) {
|
|
400
|
+
return ERRNO_NOENT;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
let initialBytes = new Uint8Array(0);
|
|
404
|
+
let dirty = false;
|
|
405
|
+
if (exists && !(oflags & OFLAGS_TRUNC)) {
|
|
406
|
+
const content = fs.getFileByPath(absPath);
|
|
407
|
+
if (content !== null && content !== undefined) {
|
|
408
|
+
initialBytes = typeof content === 'string'
|
|
409
|
+
? encoder.encode(content)
|
|
410
|
+
: new Uint8Array(this._contentToBytes(content));
|
|
411
|
+
}
|
|
412
|
+
} else {
|
|
413
|
+
dirty = true;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const newFd = nextFd++;
|
|
417
|
+
fdTable.set(newFd, {
|
|
418
|
+
type: 'file',
|
|
419
|
+
path: absPath,
|
|
420
|
+
bytes: initialBytes,
|
|
421
|
+
pos: (fdflags & FDFLAGS_APPEND) ? initialBytes.length : 0,
|
|
422
|
+
append: Boolean(fdflags & FDFLAGS_APPEND),
|
|
423
|
+
dirty
|
|
424
|
+
});
|
|
425
|
+
new DataView(memRef.buffer).setUint32(opened_fd_ptr, newFd, true);
|
|
426
|
+
return ERRNO_SUCCESS;
|
|
427
|
+
},
|
|
428
|
+
path_filestat_get: (dirfd, flags, path_ptr, path_len, buf_ptr) => {
|
|
429
|
+
if (!memRef || !fs) return ERRNO_BADF;
|
|
430
|
+
const relPath = decoder.decode(new Uint8Array(memRef.buffer, path_ptr, path_len));
|
|
431
|
+
const absPath = resolveGuestPath(dirfd, relPath);
|
|
432
|
+
if (!absPath) return ERRNO_BADF;
|
|
433
|
+
const st = fs.stat(absPath);
|
|
434
|
+
if (!st) return ERRNO_NOENT;
|
|
435
|
+
const view = new DataView(memRef.buffer);
|
|
436
|
+
for (let i = 0; i < 64; i++) view.setUint8(buf_ptr + i, 0);
|
|
437
|
+
view.setUint8(buf_ptr + 16, st.isDirectory ? FILETYPE_DIRECTORY : FILETYPE_REGULAR_FILE);
|
|
438
|
+
view.setBigUint64(buf_ptr + 24, 1n, true);
|
|
439
|
+
view.setBigUint64(buf_ptr + 32, BigInt(fs.getSize(absPath) || 0), true);
|
|
440
|
+
return ERRNO_SUCCESS;
|
|
441
|
+
},
|
|
442
|
+
path_create_directory: (dirfd, path_ptr, path_len) => {
|
|
443
|
+
if (!memRef || !fs) return ERRNO_BADF;
|
|
444
|
+
const relPath = decoder.decode(new Uint8Array(memRef.buffer, path_ptr, path_len));
|
|
445
|
+
const absPath = resolveGuestPath(dirfd, relPath);
|
|
446
|
+
if (!absPath) return ERRNO_BADF;
|
|
447
|
+
try {
|
|
448
|
+
fs.setFileByPath(absPath, {}, true);
|
|
449
|
+
return ERRNO_SUCCESS;
|
|
450
|
+
} catch {
|
|
451
|
+
return ERRNO_INVAL;
|
|
452
|
+
}
|
|
453
|
+
},
|
|
454
|
+
path_unlink_file: (dirfd, path_ptr, path_len) => {
|
|
455
|
+
if (!memRef || !fs) return ERRNO_BADF;
|
|
456
|
+
const relPath = decoder.decode(new Uint8Array(memRef.buffer, path_ptr, path_len));
|
|
457
|
+
const absPath = resolveGuestPath(dirfd, relPath);
|
|
458
|
+
if (!absPath || !fs.exists(absPath)) return ERRNO_NOENT;
|
|
459
|
+
try {
|
|
460
|
+
fs.deleteFileByPath(absPath);
|
|
461
|
+
return ERRNO_SUCCESS;
|
|
462
|
+
} catch {
|
|
463
|
+
return ERRNO_INVAL;
|
|
464
|
+
}
|
|
465
|
+
},
|
|
466
|
+
path_remove_directory: (dirfd, path_ptr, path_len) => {
|
|
467
|
+
if (!memRef || !fs) return ERRNO_BADF;
|
|
468
|
+
const relPath = decoder.decode(new Uint8Array(memRef.buffer, path_ptr, path_len));
|
|
469
|
+
const absPath = resolveGuestPath(dirfd, relPath);
|
|
470
|
+
if (!absPath || !fs.exists(absPath)) return ERRNO_NOENT;
|
|
471
|
+
try {
|
|
472
|
+
fs.deleteFileByPath(absPath);
|
|
473
|
+
return ERRNO_SUCCESS;
|
|
474
|
+
} catch {
|
|
475
|
+
return ERRNO_INVAL;
|
|
476
|
+
}
|
|
142
477
|
},
|
|
143
478
|
proc_exit: (code) => {
|
|
144
479
|
if (code !== 0) this.exitCode = code;
|
|
145
480
|
throw { _wasmExit: true, code };
|
|
146
481
|
},
|
|
147
482
|
args_sizes_get: (argc_ptr, buf_size_ptr) => {
|
|
148
|
-
if (!memRef) return
|
|
483
|
+
if (!memRef) return ERRNO_INVAL;
|
|
149
484
|
const args = [this.script, ...(this.arguments || [])];
|
|
150
485
|
const view = new DataView(memRef.buffer);
|
|
151
486
|
view.setUint32(argc_ptr, args.length, true);
|
|
152
|
-
view.setUint32(buf_size_ptr, args.reduce((s, a) => s + a.length + 1, 0), true);
|
|
153
|
-
return
|
|
487
|
+
view.setUint32(buf_size_ptr, args.reduce((s, a) => s + encoder.encode(a).length + 1, 0), true);
|
|
488
|
+
return ERRNO_SUCCESS;
|
|
154
489
|
},
|
|
155
490
|
args_get: (argv_ptr, buf_ptr) => {
|
|
156
|
-
if (!memRef) return
|
|
491
|
+
if (!memRef) return ERRNO_INVAL;
|
|
157
492
|
const args = [this.script, ...(this.arguments || [])];
|
|
158
493
|
const view = new DataView(memRef.buffer);
|
|
159
|
-
const enc = new TextEncoder();
|
|
160
494
|
let offset = buf_ptr;
|
|
161
495
|
for (let i = 0; i < args.length; i++) {
|
|
162
496
|
view.setUint32(argv_ptr + i * 4, offset, true);
|
|
163
|
-
const encoded =
|
|
497
|
+
const encoded = encoder.encode(args[i] + '\0');
|
|
164
498
|
new Uint8Array(memRef.buffer).set(encoded, offset);
|
|
165
499
|
offset += encoded.length;
|
|
166
500
|
}
|
|
167
|
-
return
|
|
501
|
+
return ERRNO_SUCCESS;
|
|
168
502
|
},
|
|
169
|
-
environ_sizes_get: (
|
|
170
|
-
if (memRef)
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
503
|
+
environ_sizes_get: (cnt_ptr, sz_ptr) => {
|
|
504
|
+
if (!memRef) return ERRNO_INVAL;
|
|
505
|
+
const view = new DataView(memRef.buffer);
|
|
506
|
+
view.setUint32(cnt_ptr, envPairs.length, true);
|
|
507
|
+
const totalBytes = envPairs.reduce((s, p) => s + encoder.encode(p).length + 1, 0);
|
|
508
|
+
view.setUint32(sz_ptr, totalBytes, true);
|
|
509
|
+
return ERRNO_SUCCESS;
|
|
510
|
+
},
|
|
511
|
+
environ_get: (environ_ptr, environ_buf_ptr) => {
|
|
512
|
+
if (!memRef) return ERRNO_INVAL;
|
|
513
|
+
const view = new DataView(memRef.buffer);
|
|
514
|
+
let offset = environ_buf_ptr;
|
|
515
|
+
for (let i = 0; i < envPairs.length; i++) {
|
|
516
|
+
view.setUint32(environ_ptr + i * 4, offset, true);
|
|
517
|
+
const encoded = encoder.encode(envPairs[i] + '\0');
|
|
518
|
+
new Uint8Array(memRef.buffer).set(encoded, offset);
|
|
519
|
+
offset += encoded.length;
|
|
174
520
|
}
|
|
175
|
-
return
|
|
521
|
+
return ERRNO_SUCCESS;
|
|
176
522
|
},
|
|
177
|
-
environ_get: () => 0,
|
|
178
523
|
clock_time_get: (id, prec, time_ptr) => {
|
|
179
524
|
if (memRef) {
|
|
180
525
|
const ns = BigInt(Date.now()) * 1_000_000n;
|
|
181
526
|
new DataView(memRef.buffer).setBigUint64(time_ptr, ns, true);
|
|
182
527
|
}
|
|
183
|
-
return
|
|
528
|
+
return ERRNO_SUCCESS;
|
|
184
529
|
},
|
|
185
|
-
fd_close: () => 0,
|
|
186
|
-
fd_seek: () => 70, // ESPIPE—no seekable fds
|
|
187
|
-
fd_prestat_get: () => 8, // EBADF—no pre-opened dirs
|
|
188
|
-
fd_prestat_dir_name: () => 8,
|
|
189
|
-
path_open: () => 76, // ENOTDIR
|
|
190
530
|
random_get: (buf_ptr, buf_len) => {
|
|
191
531
|
if (memRef) {
|
|
192
532
|
const arr = new Uint8Array(memRef.buffer, buf_ptr, buf_len);
|
|
193
533
|
for (let i = 0; i < buf_len; i++) arr[i] = Math.random() * 256 | 0;
|
|
194
534
|
}
|
|
195
|
-
return
|
|
535
|
+
return ERRNO_SUCCESS;
|
|
196
536
|
},
|
|
197
537
|
};
|
|
198
538
|
|
|
199
539
|
const wasiProxy = new Proxy(wasi, { get(t, k) { return k in t ? t[k] : () => 0; } });
|
|
200
540
|
|
|
541
|
+
// Helper for AssemblyScript UTF-16 managed strings (`ptr - 4` stores byte length)
|
|
542
|
+
const readAsUtf16 = (ptr) => {
|
|
543
|
+
if (!memRef || !ptr) return '';
|
|
544
|
+
try {
|
|
545
|
+
const view = new DataView(memRef.buffer);
|
|
546
|
+
const byteLen = view.getUint32(ptr - 4, true);
|
|
547
|
+
const u16 = new Uint16Array(memRef.buffer, ptr, byteLen >>> 1);
|
|
548
|
+
return String.fromCharCode(...u16);
|
|
549
|
+
} catch {
|
|
550
|
+
return '';
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
|
|
201
554
|
const imports = {
|
|
202
555
|
wasi_snapshot_preview1: wasiProxy,
|
|
203
556
|
wasi_unstable: wasiProxy,
|
|
204
557
|
env: new Proxy({
|
|
205
|
-
// Simple non-WASI
|
|
558
|
+
// Simple non-WASI & AssemblyScript imports
|
|
206
559
|
print: (ptr, len) => { if (memRef) writeFd(1, decoder.decode(new Uint8Array(memRef.buffer, ptr, len))); },
|
|
207
560
|
eprint: (ptr, len) => { if (memRef) writeFd(2, decoder.decode(new Uint8Array(memRef.buffer, ptr, len))); },
|
|
208
|
-
|
|
561
|
+
log: (ptr) => { writeFd(1, readAsUtf16(ptr) + '\n'); },
|
|
562
|
+
logi: (v) => { writeFd(1, String(v) + '\n'); },
|
|
563
|
+
logf: (v) => { writeFd(1, String(v) + '\n'); },
|
|
564
|
+
trace: (ptr, n, ...args) => {
|
|
565
|
+
const extra = n > 0 ? ' ' + args.slice(0, n).join(', ') : '';
|
|
566
|
+
writeFd(1, `trace: ${readAsUtf16(ptr)}${extra}\n`);
|
|
567
|
+
},
|
|
568
|
+
seed: () => Date.now() * Math.random(),
|
|
569
|
+
abort: (msgPtr, filePtr, line, col) => {
|
|
570
|
+
const msg = readAsUtf16(msgPtr);
|
|
571
|
+
const file = readAsUtf16(filePtr);
|
|
572
|
+
if (msg || file) {
|
|
573
|
+
writeFd(2, `abort: ${msg || 'aborted'} at ${file || this.script}:${line || 0}:${col || 0}\n`);
|
|
574
|
+
}
|
|
575
|
+
this.exitCode = 134;
|
|
576
|
+
throw { _wasmExit: true, code: 134 };
|
|
577
|
+
},
|
|
209
578
|
}, { get(t, k) { return k in t ? t[k] : () => 0; } }),
|
|
210
579
|
};
|
|
211
580
|
|
|
@@ -233,7 +602,13 @@ class WasmCommand extends ScriptCommand {
|
|
|
233
602
|
|| instance.exports.run;
|
|
234
603
|
|
|
235
604
|
if (!start) {
|
|
236
|
-
|
|
605
|
+
const fnExports = Object.entries(instance.exports)
|
|
606
|
+
.filter(([, v]) => typeof v === 'function')
|
|
607
|
+
.map(([k]) => k);
|
|
608
|
+
const exportHint = fnExports.length > 0
|
|
609
|
+
? ` (module is a library exporting: ${fnExports.join(', ')})`
|
|
610
|
+
: '';
|
|
611
|
+
this.stdErr = `${this.script}: no CLI entry point found (expected _start, main, or run)${exportHint}`;
|
|
237
612
|
this.exitCode = 1;
|
|
238
613
|
} else {
|
|
239
614
|
try {
|
|
@@ -250,10 +625,723 @@ class WasmCommand extends ScriptCommand {
|
|
|
250
625
|
this.stdErr = `${this.script}: ${e?.message || String(e)}`;
|
|
251
626
|
this.exitCode = 1;
|
|
252
627
|
}
|
|
628
|
+
} finally {
|
|
629
|
+
// Flush any open dirty WASI file descriptors back to the brsh filesystem
|
|
630
|
+
for (const entry of fdTable.values()) {
|
|
631
|
+
flushOpenFile(entry);
|
|
632
|
+
}
|
|
253
633
|
}
|
|
254
634
|
|
|
255
635
|
flushFd();
|
|
636
|
+
|
|
637
|
+
// Standard `--help` / `--version` fallback for raw WASI `.wasm` / `.wat` binaries
|
|
638
|
+
// that do not inspect `argv` or print their own help/version output:
|
|
639
|
+
// introspects the `.wasm` binary's data section and exports at runtime.
|
|
640
|
+
const args = this.arguments || [];
|
|
641
|
+
const hasOutput = this.result && this.result.getStdOutput && this.result.getStdOutput().length > 0;
|
|
642
|
+
if (!hasOutput && (this.exitCode === 0 || this.exitCode === undefined)) {
|
|
643
|
+
const binLabel = (this.script || 'wasm').split('/').pop();
|
|
644
|
+
const meta = Object.assign({
|
|
645
|
+
name: binLabel,
|
|
646
|
+
version: 'wasi',
|
|
647
|
+
description: `WebAssembly WASI binary (${this.script})`
|
|
648
|
+
}, this._pkgMeta || {});
|
|
649
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
650
|
+
const inspected = inspectWasmBytes(bytes);
|
|
651
|
+
for (const line of formatWasmHelp(binLabel, meta, inspected)) {
|
|
652
|
+
this.stdOut = line;
|
|
653
|
+
}
|
|
654
|
+
} else if (args.includes('--version') || args.includes('-V') || args.includes('-v')) {
|
|
655
|
+
this.stdOut = `${binLabel} (${meta.name} ${meta.version} wasm)`;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// Shared cache of downloaded .wasm binaries across invocations
|
|
662
|
+
const wasmByteCache = new Map();
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* Reads a file from the brsh filesystem as a Uint8Array (or null if missing).
|
|
666
|
+
*/
|
|
667
|
+
function readBytesFromFs(fs, filepath) {
|
|
668
|
+
if (!fs || !fs.exists(filepath)) return null;
|
|
669
|
+
if (fs.isRealFilesystem) {
|
|
670
|
+
try {
|
|
671
|
+
const nodeFs = require('fs');
|
|
672
|
+
return new Uint8Array(nodeFs.readFileSync(fs.absolutePath(filepath)));
|
|
673
|
+
} catch {
|
|
674
|
+
return null;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
const content = fs.getFileByPath(filepath);
|
|
678
|
+
if (content == null) return null;
|
|
679
|
+
if (content instanceof Uint8Array) {
|
|
680
|
+
return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
|
|
681
|
+
}
|
|
682
|
+
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(content)) {
|
|
683
|
+
return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
|
|
684
|
+
}
|
|
685
|
+
if (content instanceof ArrayBuffer) {
|
|
686
|
+
return new Uint8Array(content);
|
|
687
|
+
}
|
|
688
|
+
if (typeof content === 'string') {
|
|
689
|
+
if (content.startsWith('data:')) {
|
|
690
|
+
const comma = content.indexOf(',');
|
|
691
|
+
if (comma !== -1) {
|
|
692
|
+
const b64 = content.slice(comma + 1);
|
|
693
|
+
if (typeof Buffer !== 'undefined') {
|
|
694
|
+
return new Uint8Array(Buffer.from(b64, 'base64'));
|
|
695
|
+
}
|
|
696
|
+
const bin = atob(b64);
|
|
697
|
+
const bytes = new Uint8Array(bin.length);
|
|
698
|
+
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
|
699
|
+
return bytes;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
const bytes = new Uint8Array(content.length);
|
|
703
|
+
for (let i = 0; i < content.length; i++) {
|
|
704
|
+
bytes[i] = content.charCodeAt(i) & 0xff;
|
|
705
|
+
}
|
|
706
|
+
return bytes;
|
|
707
|
+
}
|
|
708
|
+
return null;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* Writes a Uint8Array to the brsh filesystem (as a BinaryFile on virtual FS, or Buffer on real FS).
|
|
713
|
+
*/
|
|
714
|
+
function writeBytesToFs(fs, filepath, bytes, mimeType = 'application/octet-stream') {
|
|
715
|
+
const uint8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
716
|
+
if (fs.isRealFilesystem) {
|
|
717
|
+
const nodeFs = require('fs');
|
|
718
|
+
const nodePath = require('path');
|
|
719
|
+
const abs = fs.absolutePath(filepath);
|
|
720
|
+
nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
|
|
721
|
+
nodeFs.writeFileSync(abs, Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
const copy = new Uint8Array(uint8.byteLength);
|
|
725
|
+
copy.set(uint8);
|
|
726
|
+
const bf = new BinaryFile(copy.buffer, mimeType);
|
|
727
|
+
fs.setFileByPath(filepath, bf, true);
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* Dynamically imports a WASM/JS package by trying local module resolution first, then CDN URL.
|
|
732
|
+
* Supports dependency injection via `customLoader` for offline testing.
|
|
733
|
+
*/
|
|
734
|
+
async function loadModule(pkgName, cdnUrl, customLoader = null) {
|
|
735
|
+
if (typeof customLoader === 'function') {
|
|
736
|
+
const res = await customLoader(pkgName, cdnUrl);
|
|
737
|
+
if (res) return res;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
try {
|
|
741
|
+
const mod = await import(/* @vite-ignore */ pkgName);
|
|
742
|
+
if (mod) return mod;
|
|
743
|
+
} catch {
|
|
744
|
+
// Fallback to CDN
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
if (cdnUrl) {
|
|
748
|
+
try {
|
|
749
|
+
return await import(/* @vite-ignore */ cdnUrl);
|
|
750
|
+
} catch (err) {
|
|
751
|
+
throw new Error(`Failed to load WASM package '${pkgName}' from ${cdnUrl}: ${err.message || err}`);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
throw new Error(`Package '${pkgName}' could not be loaded`);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* Parses `Usage:` and CLI option lines (`-f`, `--flag`) from runtime `--help` output
|
|
760
|
+
* or extracted WebAssembly data-section text.
|
|
761
|
+
*/
|
|
762
|
+
function extractHelpFromText(text, scanBareFlags = false) {
|
|
763
|
+
const res = { usage: null, options: [] };
|
|
764
|
+
if (!text || typeof text !== 'string') return res;
|
|
765
|
+
|
|
766
|
+
const lines = text.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
|
|
767
|
+
const seenOpts = new Set();
|
|
768
|
+
|
|
769
|
+
for (const line of lines) {
|
|
770
|
+
if (!res.usage && /^usage:\s*(.+)/i.test(line)) {
|
|
771
|
+
res.usage = line.replace(/^usage:\s*/i, '').trim();
|
|
772
|
+
} else if (
|
|
773
|
+
/^(?:-[a-zA-Z0-9?]|--[a-zA-Z0-9][-a-zA-Z0-9]*)(?:\s|,|=|<|\[|$)/.test(line) &&
|
|
774
|
+
line.length <= 120 &&
|
|
775
|
+
!/^(?:-[hHvV],\s*)?--(?:help|version)\b/i.test(line)
|
|
776
|
+
) {
|
|
777
|
+
if (!seenOpts.has(line)) {
|
|
778
|
+
seenOpts.add(line);
|
|
779
|
+
res.options.push(line);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
if (scanBareFlags && res.options.length === 0) {
|
|
785
|
+
const flagMatches = text.match(/--[a-z][a-z0-9-]{1,24}/g) || [];
|
|
786
|
+
for (const fl of Array.from(new Set(flagMatches)).slice(0, 12)) {
|
|
787
|
+
if (fl !== '--help' && fl !== '--version') {
|
|
788
|
+
res.options.push(fl);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
return res;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* Introspects a compiled WebAssembly binary (`Uint8Array`) at runtime to extract:
|
|
798
|
+
* - Embedded `Usage:` strings and CLI option flags (`--flag`, `-f`) from the `.wasm` data section
|
|
799
|
+
* - Exported WASM functions (`_start`, `main`, custom exports)
|
|
800
|
+
* - Imported WASI capabilities (`args_get`, `path_open`, `fd_read`, `fd_write`, etc.)
|
|
801
|
+
*/
|
|
802
|
+
function inspectWasmBytes(bytes) {
|
|
803
|
+
const info = {
|
|
804
|
+
usage: null,
|
|
805
|
+
options: [],
|
|
806
|
+
exports: [],
|
|
807
|
+
wasiImports: []
|
|
808
|
+
};
|
|
809
|
+
if (!(bytes instanceof Uint8Array) || bytes.length < 8) return info;
|
|
810
|
+
|
|
811
|
+
try {
|
|
812
|
+
if (typeof WebAssembly !== 'undefined' && WebAssembly.Module) {
|
|
813
|
+
const mod = new WebAssembly.Module(bytes);
|
|
814
|
+
info.exports = WebAssembly.Module.exports(mod)
|
|
815
|
+
.filter(e => e.kind === 'function')
|
|
816
|
+
.map(e => e.name);
|
|
817
|
+
info.wasiImports = WebAssembly.Module.imports(mod)
|
|
818
|
+
.filter(i => i.module.startsWith('wasi_'))
|
|
819
|
+
.map(i => i.name);
|
|
820
|
+
}
|
|
821
|
+
} catch {
|
|
822
|
+
// Ignore if bytes are WAT or non-standard
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
try {
|
|
826
|
+
const chunks = [];
|
|
827
|
+
let cur = '';
|
|
828
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
829
|
+
const b = bytes[i];
|
|
830
|
+
if ((b >= 32 && b <= 126) || b === 9 || b === 10) {
|
|
831
|
+
cur += String.fromCharCode(b);
|
|
832
|
+
} else {
|
|
833
|
+
if (cur.length >= 4) chunks.push(cur);
|
|
834
|
+
cur = '';
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
if (cur.length >= 4) chunks.push(cur);
|
|
838
|
+
|
|
839
|
+
const parsed = extractHelpFromText(chunks.join('\n'), true);
|
|
840
|
+
info.usage = parsed.usage;
|
|
841
|
+
info.options = parsed.options;
|
|
842
|
+
} catch {
|
|
843
|
+
// Ignore string scan errors
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
return info;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* Formats a fallback `--help` screen for a WASM binary when the binary itself
|
|
851
|
+
* does not print its own `--help` output to stdout/stderr. Uses runtime WASM
|
|
852
|
+
* binary introspection (`inspectWasmBytes`) when available.
|
|
853
|
+
*/
|
|
854
|
+
function formatWasmHelp(binName, pkgMeta = {}, inspected = null) {
|
|
855
|
+
const pkgName = pkgMeta.name || binName;
|
|
856
|
+
const version = pkgMeta.version || 'wasm';
|
|
857
|
+
const desc = pkgMeta.description || 'WebAssembly binary';
|
|
858
|
+
const replCfg = (pkgMeta && typeof pkgMeta.repl === 'object') ? pkgMeta.repl : (pkgMeta.repl ? {} : null);
|
|
859
|
+
|
|
860
|
+
const detectedUsage = (inspected && inspected.usage) || pkgMeta.usage;
|
|
861
|
+
const defaultUsage = replCfg
|
|
862
|
+
? `${binName} [options] ${replCfg.evalFlag ? `[${replCfg.evalFlag} <code>] ` : ''}[file] [args...]`
|
|
863
|
+
: `${binName} [options] [args...]`;
|
|
864
|
+
|
|
865
|
+
const lines = [
|
|
866
|
+
`${binName} (${pkgName} ${version} wasm) — ${desc}`,
|
|
867
|
+
`Usage: ${detectedUsage || defaultUsage}`
|
|
868
|
+
];
|
|
869
|
+
|
|
870
|
+
if (pkgMeta.details) {
|
|
871
|
+
lines.push('', pkgMeta.details);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
lines.push('', 'Options:');
|
|
875
|
+
const detectedOptions = (inspected && inspected.options && inspected.options.length > 0)
|
|
876
|
+
? inspected.options
|
|
877
|
+
: (Array.isArray(pkgMeta.options) ? pkgMeta.options : []);
|
|
878
|
+
|
|
879
|
+
if (detectedOptions.length > 0) {
|
|
880
|
+
for (const opt of detectedOptions) {
|
|
881
|
+
lines.push(` ${opt}`);
|
|
882
|
+
}
|
|
883
|
+
} else if (replCfg) {
|
|
884
|
+
if (replCfg.evalFlag) {
|
|
885
|
+
lines.push(` ${replCfg.evalFlag.padEnd(20)}Evaluate inline code and print result`);
|
|
886
|
+
}
|
|
887
|
+
lines.push(` (no arguments) Start interactive ${binName} REPL shell`);
|
|
888
|
+
}
|
|
889
|
+
lines.push(' -h, --help Show this help message and exit');
|
|
890
|
+
lines.push(' -V, --version Show WebAssembly binary version and exit');
|
|
891
|
+
|
|
892
|
+
if (inspected && inspected.exports && inspected.exports.length > 0) {
|
|
893
|
+
lines.push('', `WASM Exports: ${inspected.exports.join(', ')}`);
|
|
894
|
+
}
|
|
895
|
+
if (Array.isArray(pkgMeta.aliases) && pkgMeta.aliases.length > 0) {
|
|
896
|
+
lines.push('', `Aliases: ${pkgMeta.aliases.join(', ')}`);
|
|
256
897
|
}
|
|
898
|
+
if (pkgMeta.homepage || pkgMeta.cdnUrl || pkgMeta.wasmUrl) {
|
|
899
|
+
lines.push(`Source: ${pkgMeta.homepage || pkgMeta.cdnUrl || pkgMeta.wasmUrl}`);
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
return lines;
|
|
257
903
|
}
|
|
258
904
|
|
|
905
|
+
/**
|
|
906
|
+
* Pure generic non-interactive WASM & CLI Command builder for brsh.
|
|
907
|
+
*
|
|
908
|
+
* Supports three standard, runtime-agnostic execution conventions:
|
|
909
|
+
* 1. Raw WebAssembly binary (`.wasm` / `.wat` via `wasmUrl`, `Uint8Array`, `ArrayBuffer`, or `{ wasmBytes }`) ->
|
|
910
|
+
* Executed via `WasmCommand` with full WASI (`wasi_snapshot_preview1`) filesystem, argv, env, and stdio.
|
|
911
|
+
* 2. Emscripten modularized factory (`export default async function Module(opts)`) ->
|
|
912
|
+
* Syncs input/output files between the `brsh` filesystem and Emscripten `FS` (or `writeFile`/`readFile`),
|
|
913
|
+
* wires `stdin`/`print`/`printErr`, and invokes `callMain(args)` or `exec(args)`.
|
|
914
|
+
* 3. Standard CLI module interface (`main(args, io)`, `run(args, io)`, `callMain(args)`, `exec(args)`) ->
|
|
915
|
+
* Passes `args` and a standard `{ binName, args, stdin, fs, context, stdout, stderr, readFile, writeFile }`
|
|
916
|
+
* I/O bridge to the module's entry function.
|
|
917
|
+
*
|
|
918
|
+
* Interactive REPL support is provided separately by `ReplCommand` (`lib/ReplCommand.js`),
|
|
919
|
+
* which extends `createGenericWasmCommand`.
|
|
920
|
+
*/
|
|
921
|
+
function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null) {
|
|
922
|
+
const LocalCommand = require('./local/LocalCommand');
|
|
923
|
+
const binName = (binNameOverride || pkgMeta.bin || pkgMeta.name).toLowerCase();
|
|
924
|
+
|
|
925
|
+
class GenericWasmCommand extends LocalCommand {
|
|
926
|
+
static get name() { return binName; }
|
|
927
|
+
get name() { return binName; }
|
|
928
|
+
get requiresFilesystem() { return true; }
|
|
929
|
+
|
|
930
|
+
async run() {
|
|
931
|
+
const args = [...(this.arguments || [])];
|
|
932
|
+
const isHelp = args.includes('--help') || args.includes('-h');
|
|
933
|
+
const isVersion = !isHelp && (args.includes('--version') || args.includes('-V') || args.includes('-v'));
|
|
934
|
+
this._inspectedWasm = null;
|
|
935
|
+
|
|
936
|
+
try {
|
|
937
|
+
// 1. Direct `.wasm` URL -> fetch and run raw WASI binary via WasmCommand
|
|
938
|
+
if (pkgMeta.type === 'wasm' && pkgMeta.wasmUrl && !config.moduleLoader) {
|
|
939
|
+
const bytes = await this._fetchWasmBytes(pkgMeta.wasmUrl);
|
|
940
|
+
if (isHelp) this._inspectedWasm = inspectWasmBytes(bytes);
|
|
941
|
+
await this._runRawWasmBytes(bytes, args);
|
|
942
|
+
} else {
|
|
943
|
+
const cdnUrl = pkgMeta.cdnUrl || pkgMeta.wasmUrl || `https://esm.sh/${pkgMeta.name}`;
|
|
944
|
+
const loaded = await loadModule(pkgMeta.name, cdnUrl, config.moduleLoader);
|
|
945
|
+
const target = (loaded && loaded.default !== undefined) ? loaded.default : loaded;
|
|
946
|
+
|
|
947
|
+
// 2. Raw WASM binary (Uint8Array or ArrayBuffer)
|
|
948
|
+
if (target instanceof Uint8Array || target instanceof ArrayBuffer) {
|
|
949
|
+
const bytes = target instanceof Uint8Array ? target : new Uint8Array(target);
|
|
950
|
+
if (isHelp) this._inspectedWasm = inspectWasmBytes(bytes);
|
|
951
|
+
await this._runRawWasmBytes(bytes, args);
|
|
952
|
+
} else if (target && (target.wasmBytes instanceof Uint8Array || target.wasm instanceof Uint8Array)) {
|
|
953
|
+
const bytes = target.wasmBytes || target.wasm;
|
|
954
|
+
if (isHelp) this._inspectedWasm = inspectWasmBytes(bytes);
|
|
955
|
+
await this._runRawWasmBytes(bytes, args);
|
|
956
|
+
} else if (typeof target === 'function') {
|
|
957
|
+
// 3. Factory / constructor / CLI function (`export default function(opts)` or class)
|
|
958
|
+
await this._runFunctionOrEmscripten(target, args, isHelp);
|
|
959
|
+
} else if (target && typeof target === 'object') {
|
|
960
|
+
// 4. Standard CLI module object (`main`, `run`, `callMain`, `exec`)
|
|
961
|
+
if (target.ready) await target.ready;
|
|
962
|
+
if (isHelp && (target.HEAPU8 instanceof Uint8Array || target.wasmBinary instanceof Uint8Array)) {
|
|
963
|
+
this._inspectedWasm = inspectWasmBytes(target.wasmBinary || target.HEAPU8);
|
|
964
|
+
}
|
|
965
|
+
const entryFn = target.main || target.run || target.callMain || target.exec;
|
|
966
|
+
if (typeof entryFn === 'function') {
|
|
967
|
+
await this._invokeCliFunction(entryFn.bind(target), args);
|
|
968
|
+
} else if (!isHelp && !isVersion) {
|
|
969
|
+
this.stdErr = `${binName}: unsupported WASM module format for '${pkgMeta.name}'`;
|
|
970
|
+
this.exitCode = 1;
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
} else if (!isHelp && !isVersion) {
|
|
974
|
+
this.stdErr = `${binName}: unsupported WASM module format for '${pkgMeta.name}'`;
|
|
975
|
+
this.exitCode = 1;
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
} catch (err) {
|
|
980
|
+
if (!isHelp && !isVersion) {
|
|
981
|
+
if (err && typeof err.status === 'number') {
|
|
982
|
+
this.exitCode = err.status;
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
this.stdErr = `${binName}: ${err.message || err}`;
|
|
986
|
+
this.exitCode = 1;
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// If `--help` or `--version` was requested:
|
|
992
|
+
// - If the WASM binary emitted its own native help output, pass it through directly!
|
|
993
|
+
// - Otherwise, fall back to runtime binary inspection (`this._inspectedWasm`) + `formatWasmHelp`.
|
|
994
|
+
if (isHelp || isVersion) {
|
|
995
|
+
const stdLines = (this.result && this.result.getStdOutput) ? this.result.getStdOutput() : [];
|
|
996
|
+
const allText = stdLines.map(l => l.string).join('\n');
|
|
997
|
+
const parsedHelp = isHelp ? extractHelpFromText(allText) : null;
|
|
998
|
+
const hasNativeHelp = isHelp && Boolean(
|
|
999
|
+
(parsedHelp && (parsedHelp.usage || parsedHelp.options.length > 0)) ||
|
|
1000
|
+
stdLines.some(l => /\b(usage|options):/i.test(l.string))
|
|
1001
|
+
);
|
|
1002
|
+
const outOnly = stdLines.filter(l => l.type === 'out').map(l => l.string);
|
|
1003
|
+
const hasNativeVersion = isVersion && outOnly.length > 0 && (this.exitCode === 0 || this.exitCode === undefined);
|
|
1004
|
+
|
|
1005
|
+
if (isHelp) {
|
|
1006
|
+
if (hasNativeHelp) {
|
|
1007
|
+
// Promote any stderr help lines to stdout and return exitCode 0
|
|
1008
|
+
const nativeLines = stdLines.map(l => l.string);
|
|
1009
|
+
if (this.result && Array.isArray(this.result.std)) {
|
|
1010
|
+
this.result.std.length = 0;
|
|
1011
|
+
}
|
|
1012
|
+
this.exitCode = 0;
|
|
1013
|
+
for (const line of nativeLines) {
|
|
1014
|
+
this.stdOut = line;
|
|
1015
|
+
}
|
|
1016
|
+
} else {
|
|
1017
|
+
if (this.result && Array.isArray(this.result.std)) {
|
|
1018
|
+
this.result.std.length = 0;
|
|
1019
|
+
}
|
|
1020
|
+
this.exitCode = 0;
|
|
1021
|
+
for (const line of formatWasmHelp(binName, pkgMeta, this._inspectedWasm)) {
|
|
1022
|
+
this.stdOut = line;
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
} else if (isVersion && !hasNativeVersion) {
|
|
1026
|
+
if (this.result && Array.isArray(this.result.std)) {
|
|
1027
|
+
this.result.std.length = 0;
|
|
1028
|
+
}
|
|
1029
|
+
this.exitCode = 0;
|
|
1030
|
+
this.stdOut = `${binName} (${pkgMeta.name} ${pkgMeta.version || 'wasm'} wasm)`;
|
|
1031
|
+
} else {
|
|
1032
|
+
this.exitCode = 0;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
async _fetchWasmBytes(url) {
|
|
1038
|
+
if (wasmByteCache.has(url)) return wasmByteCache.get(url);
|
|
1039
|
+
const fetchFn = config.fetch || (typeof fetch === 'function' ? fetch : null);
|
|
1040
|
+
if (!fetchFn) throw new Error('fetch is not available in this environment');
|
|
1041
|
+
const res = await fetchFn(url);
|
|
1042
|
+
if (!res || !res.ok) throw new Error(`HTTP ${res ? res.status : 'error'} fetching ${url}`);
|
|
1043
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
1044
|
+
wasmByteCache.set(url, bytes);
|
|
1045
|
+
return bytes;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
async _runRawWasmBytes(bytes, args) {
|
|
1049
|
+
const wasmCmd = new WasmCommand(binName, args, this.context);
|
|
1050
|
+
wasmCmd.script = binName;
|
|
1051
|
+
wasmCmd.arguments = args;
|
|
1052
|
+
wasmCmd.context = this.context;
|
|
1053
|
+
wasmCmd.fs = this.fs;
|
|
1054
|
+
wasmCmd._pkgMeta = pkgMeta;
|
|
1055
|
+
if (this.stdin !== undefined) {
|
|
1056
|
+
wasmCmd.stdin = this.stdin;
|
|
1057
|
+
}
|
|
1058
|
+
await wasmCmd._runWasm(bytes);
|
|
1059
|
+
for (const line of wasmCmd.result.getStdOutput()) {
|
|
1060
|
+
if (line.type === 'out') this.stdOut = line.string;
|
|
1061
|
+
else if (line.type === 'err') this.stdErr = line.string;
|
|
1062
|
+
}
|
|
1063
|
+
this.exitCode = wasmCmd.result.getExitCode();
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
_createIoBridge(args, outLines, errLines) {
|
|
1067
|
+
const createStream = (lines) => ({
|
|
1068
|
+
write(chunk) {
|
|
1069
|
+
const str = chunk instanceof Uint8Array
|
|
1070
|
+
? new TextDecoder().decode(chunk)
|
|
1071
|
+
: String(chunk ?? '');
|
|
1072
|
+
str.replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => lines.push(l));
|
|
1073
|
+
}
|
|
1074
|
+
});
|
|
1075
|
+
|
|
1076
|
+
return {
|
|
1077
|
+
binName,
|
|
1078
|
+
args,
|
|
1079
|
+
stdin: this.stdin !== undefined && this.stdin !== null ? String(this.stdin) : '',
|
|
1080
|
+
fs: this.fs,
|
|
1081
|
+
context: this.context,
|
|
1082
|
+
stdout: Object.assign((line) => outLines.push(String(line)), createStream(outLines)),
|
|
1083
|
+
stderr: Object.assign((line) => errLines.push(String(line)), createStream(errLines)),
|
|
1084
|
+
readFile: (filename, baseDir) => {
|
|
1085
|
+
if (!this.fs) return null;
|
|
1086
|
+
const relPath = baseDir && baseDir !== '.' && !filename.startsWith('/')
|
|
1087
|
+
? `${baseDir.replace(/\/+$/, '')}/${filename}`
|
|
1088
|
+
: filename;
|
|
1089
|
+
const content = this.fs.getFileByPath(relPath) ?? this.fs.getFileByPath(filename);
|
|
1090
|
+
if (content === null || content === undefined) return null;
|
|
1091
|
+
return typeof content === 'string' ? content : new TextDecoder().decode(content);
|
|
1092
|
+
},
|
|
1093
|
+
readBytes: (filename) => readBytesFromFs(this.fs, filename),
|
|
1094
|
+
writeFile: (filename, contents, baseDir) => {
|
|
1095
|
+
if (!this.fs) return;
|
|
1096
|
+
const targetPath = baseDir && baseDir !== '.' && !filename.startsWith('/')
|
|
1097
|
+
? `${baseDir.replace(/\/+$/, '')}/${filename}`
|
|
1098
|
+
: filename;
|
|
1099
|
+
if (contents instanceof Uint8Array || ArrayBuffer.isView(contents)) {
|
|
1100
|
+
const mime = targetPath.endsWith('.wasm') ? 'application/wasm' : 'application/octet-stream';
|
|
1101
|
+
writeBytesToFs(this.fs, targetPath, contents, mime);
|
|
1102
|
+
} else {
|
|
1103
|
+
this.fs.setFileByPath(targetPath, String(contents), true);
|
|
1104
|
+
}
|
|
1105
|
+
if (targetPath.endsWith('.wasm') || targetPath.endsWith('.wat')) {
|
|
1106
|
+
try {
|
|
1107
|
+
if (this.context && this.context.fs) this.context.fs.setMode(targetPath, 0o755);
|
|
1108
|
+
else this.fs.setMode(targetPath, 0o755);
|
|
1109
|
+
} catch { /* ignore */ }
|
|
1110
|
+
}
|
|
1111
|
+
},
|
|
1112
|
+
listFiles: (dirname, baseDir) => {
|
|
1113
|
+
if (!this.fs) return [];
|
|
1114
|
+
const targetDir = baseDir && baseDir !== '.' && !dirname.startsWith('/')
|
|
1115
|
+
? `${baseDir.replace(/\/+$/, '')}/${dirname}`
|
|
1116
|
+
: dirname;
|
|
1117
|
+
const dirObj = this.fs.getFileByPath(targetDir);
|
|
1118
|
+
if (dirObj && typeof dirObj === 'object' && !(dirObj instanceof Uint8Array)) {
|
|
1119
|
+
return Object.keys(dirObj);
|
|
1120
|
+
}
|
|
1121
|
+
return [];
|
|
1122
|
+
}
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
async _runFunctionOrEmscripten(fn, args, isHelp = false) {
|
|
1127
|
+
const outLines = [];
|
|
1128
|
+
const errLines = [];
|
|
1129
|
+
const stdinBytes = new TextEncoder().encode(this.stdin || '');
|
|
1130
|
+
let stdinPos = 0;
|
|
1131
|
+
|
|
1132
|
+
let preSyncedFiles = new Set();
|
|
1133
|
+
const emscriptenConfig = {
|
|
1134
|
+
arguments: args,
|
|
1135
|
+
noInitialRun: true,
|
|
1136
|
+
print: (text) => { outLines.push(String(text)); },
|
|
1137
|
+
printErr: (text) => { errLines.push(String(text)); },
|
|
1138
|
+
stdin: () => (stdinPos < stdinBytes.length ? stdinBytes[stdinPos++] : null),
|
|
1139
|
+
preRun: [
|
|
1140
|
+
(mod) => {
|
|
1141
|
+
if (mod && mod.FS) {
|
|
1142
|
+
preSyncedFiles = this._syncBrshToEmscriptenFs(mod.FS, args);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
]
|
|
1146
|
+
};
|
|
1147
|
+
|
|
1148
|
+
const ioBridge = this._createIoBridge(args, outLines, errLines);
|
|
1149
|
+
|
|
1150
|
+
let result;
|
|
1151
|
+
try {
|
|
1152
|
+
if (fn.prototype && fn.prototype.constructor === fn && Object.getOwnPropertyNames(fn.prototype).length > 1) {
|
|
1153
|
+
result = new fn(emscriptenConfig, ioBridge);
|
|
1154
|
+
} else {
|
|
1155
|
+
result = await fn(emscriptenConfig, ioBridge);
|
|
1156
|
+
}
|
|
1157
|
+
} catch (err) {
|
|
1158
|
+
if (err && typeof err.status === 'number') {
|
|
1159
|
+
this.exitCode = err.status;
|
|
1160
|
+
} else {
|
|
1161
|
+
throw err;
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
if (result && typeof result === 'object') {
|
|
1166
|
+
if (isHelp && (result.wasmBinary instanceof Uint8Array || result.HEAPU8 instanceof Uint8Array)) {
|
|
1167
|
+
this._inspectedWasm = inspectWasmBytes(result.wasmBinary || result.HEAPU8);
|
|
1168
|
+
}
|
|
1169
|
+
if (typeof result.callMain === 'function') {
|
|
1170
|
+
if (result.FS && preSyncedFiles.size === 0) {
|
|
1171
|
+
preSyncedFiles = this._syncBrshToEmscriptenFs(result.FS, args);
|
|
1172
|
+
}
|
|
1173
|
+
try {
|
|
1174
|
+
const code = await result.callMain(args);
|
|
1175
|
+
if (typeof code === 'number' && code !== 0) {
|
|
1176
|
+
this.exitCode = code;
|
|
1177
|
+
}
|
|
1178
|
+
} catch (err) {
|
|
1179
|
+
if (err && typeof err.status === 'number') {
|
|
1180
|
+
this.exitCode = err.status;
|
|
1181
|
+
} else {
|
|
1182
|
+
errLines.push(err.message || String(err));
|
|
1183
|
+
this.exitCode = 1;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
if (result.FS) {
|
|
1187
|
+
this._syncEmscriptenFsToBrsh(result.FS, args, preSyncedFiles);
|
|
1188
|
+
}
|
|
1189
|
+
} else if (typeof result.exec === 'function' && typeof result.writeFile === 'function') {
|
|
1190
|
+
await this._runVirtualFsInstance(result, args, outLines, errLines);
|
|
1191
|
+
} else if (typeof result.main === 'function' || typeof result.run === 'function') {
|
|
1192
|
+
const entry = (result.main || result.run).bind(result);
|
|
1193
|
+
await this._invokeCliFunction(entry, args, outLines, errLines);
|
|
1194
|
+
} else {
|
|
1195
|
+
if (typeof result.stdout === 'string' && result.stdout) {
|
|
1196
|
+
result.stdout.replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => outLines.push(l));
|
|
1197
|
+
}
|
|
1198
|
+
if (typeof result.stderr === 'string' && result.stderr) {
|
|
1199
|
+
result.stderr.replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => errLines.push(l));
|
|
1200
|
+
}
|
|
1201
|
+
if (result.error && errLines.length === 0) {
|
|
1202
|
+
errLines.push(result.error.message || String(result.error));
|
|
1203
|
+
this.exitCode = 1;
|
|
1204
|
+
}
|
|
1205
|
+
if (typeof result.exitCode === 'number') {
|
|
1206
|
+
this.exitCode = result.exitCode;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
} else if (typeof result === 'string') {
|
|
1210
|
+
result.replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => outLines.push(l));
|
|
1211
|
+
} else if (typeof result === 'number') {
|
|
1212
|
+
this.exitCode = result;
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
outLines.forEach(l => { this.stdOut = l; });
|
|
1216
|
+
errLines.forEach(l => { this.stdErr = l; });
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
async _runVirtualFsInstance(instance, args, outLines, errLines) {
|
|
1220
|
+
if (typeof instance.on === 'function') {
|
|
1221
|
+
instance.on('log', ({ message }) => {
|
|
1222
|
+
if (message) outLines.push(message);
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
if (!instance.loaded && typeof instance.load === 'function') {
|
|
1226
|
+
await instance.load(pkgMeta.coreUrl ? { coreURL: pkgMeta.coreUrl } : undefined);
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
const existingInputs = new Set();
|
|
1230
|
+
const candidatePaths = [];
|
|
1231
|
+
for (const arg of args) {
|
|
1232
|
+
if (arg.startsWith('-')) continue;
|
|
1233
|
+
candidatePaths.push(arg);
|
|
1234
|
+
if (this.fs.exists(arg)) {
|
|
1235
|
+
const bytes = readBytesFromFs(this.fs, arg);
|
|
1236
|
+
if (bytes) {
|
|
1237
|
+
await instance.writeFile(arg, bytes);
|
|
1238
|
+
existingInputs.add(arg);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
const code = await instance.exec(args);
|
|
1244
|
+
for (const candidate of candidatePaths) {
|
|
1245
|
+
if (existingInputs.has(candidate)) continue;
|
|
1246
|
+
try {
|
|
1247
|
+
if (typeof instance.readFile === 'function') {
|
|
1248
|
+
const outData = await instance.readFile(candidate);
|
|
1249
|
+
if (outData) writeBytesToFs(this.fs, candidate, outData);
|
|
1250
|
+
}
|
|
1251
|
+
} catch { /* ignore */ }
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
if (typeof code === 'number' && code !== 0) {
|
|
1255
|
+
this.exitCode = code;
|
|
1256
|
+
if (errLines.length === 0 && outLines.length > 0) {
|
|
1257
|
+
errLines.push(...outLines.splice(0, outLines.length));
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
async _invokeCliFunction(fn, args, existingOut = null, existingErr = null) {
|
|
1263
|
+
const outLines = existingOut || [];
|
|
1264
|
+
const errLines = existingErr || [];
|
|
1265
|
+
const ioBridge = this._createIoBridge(args, outLines, errLines);
|
|
1266
|
+
|
|
1267
|
+
const res = await fn(args, ioBridge);
|
|
1268
|
+
if (typeof res === 'string') {
|
|
1269
|
+
res.replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => outLines.push(l));
|
|
1270
|
+
} else if (typeof res === 'number') {
|
|
1271
|
+
this.exitCode = res;
|
|
1272
|
+
} else if (res && typeof res === 'object') {
|
|
1273
|
+
if (typeof res.stdout === 'string' && res.stdout) {
|
|
1274
|
+
res.stdout.replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => outLines.push(l));
|
|
1275
|
+
}
|
|
1276
|
+
if (typeof res.stderr === 'string' && res.stderr) {
|
|
1277
|
+
res.stderr.replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => errLines.push(l));
|
|
1278
|
+
}
|
|
1279
|
+
if (res.error) {
|
|
1280
|
+
if (errLines.length === 0) errLines.push(res.error.message || String(res.error));
|
|
1281
|
+
this.exitCode = typeof res.exitCode === 'number' ? res.exitCode : 1;
|
|
1282
|
+
} else if (typeof res.exitCode === 'number') {
|
|
1283
|
+
this.exitCode = res.exitCode;
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
if (!existingOut) {
|
|
1288
|
+
outLines.forEach(l => { this.stdOut = l; });
|
|
1289
|
+
errLines.forEach(l => { this.stdErr = l; });
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
_syncBrshToEmscriptenFs(emFs, args) {
|
|
1294
|
+
const synced = new Set();
|
|
1295
|
+
if (!this.fs || !emFs || typeof emFs.writeFile !== 'function') return synced;
|
|
1296
|
+
for (const arg of args) {
|
|
1297
|
+
if (arg.startsWith('-')) continue;
|
|
1298
|
+
if (this.fs.exists(arg)) {
|
|
1299
|
+
const bytes = readBytesFromFs(this.fs, arg);
|
|
1300
|
+
if (bytes) {
|
|
1301
|
+
try {
|
|
1302
|
+
emFs.writeFile(arg, bytes);
|
|
1303
|
+
synced.add(arg);
|
|
1304
|
+
} catch { /* ignore */ }
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
return synced;
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
_syncEmscriptenFsToBrsh(emFs, args, preSyncedFiles) {
|
|
1312
|
+
if (!this.fs || !emFs || typeof emFs.readFile !== 'function') return;
|
|
1313
|
+
for (const arg of args) {
|
|
1314
|
+
if (arg.startsWith('-') || preSyncedFiles.has(arg)) continue;
|
|
1315
|
+
try {
|
|
1316
|
+
const data = emFs.readFile(arg);
|
|
1317
|
+
if (data) {
|
|
1318
|
+
const mime = arg.endsWith('.wasm') ? 'application/wasm' : 'application/octet-stream';
|
|
1319
|
+
writeBytesToFs(this.fs, arg, data, mime);
|
|
1320
|
+
if (arg.endsWith('.wasm') || arg.endsWith('.wat')) {
|
|
1321
|
+
try {
|
|
1322
|
+
if (this.context && this.context.fs) this.context.fs.setMode(arg, 0o755);
|
|
1323
|
+
else this.fs.setMode(arg, 0o755);
|
|
1324
|
+
} catch { /* ignore */ }
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
} catch {
|
|
1328
|
+
// Not an output file in Emscripten FS
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
return GenericWasmCommand;
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
WasmCommand.readBytesFromFs = readBytesFromFs;
|
|
1338
|
+
WasmCommand.writeBytesToFs = writeBytesToFs;
|
|
1339
|
+
WasmCommand.loadModule = loadModule;
|
|
1340
|
+
WasmCommand.extractHelpFromText = extractHelpFromText;
|
|
1341
|
+
WasmCommand.inspectWasmBytes = inspectWasmBytes;
|
|
1342
|
+
WasmCommand.formatWasmHelp = formatWasmHelp;
|
|
1343
|
+
WasmCommand.createGenericWasmCommand = createGenericWasmCommand;
|
|
1344
|
+
WasmCommand.createCommand = createGenericWasmCommand;
|
|
1345
|
+
|
|
259
1346
|
module.exports = WasmCommand;
|
|
1347
|
+
|