brsh 2.8.0 → 2.8.1
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/dist/shell.es.js +160 -81
- package/dist/shell.es.js.map +1 -1
- package/dist/shell.min.js +4 -4
- package/dist/shell.min.js.map +1 -1
- package/dist/wbt.es.js +1584 -623
- package/dist/wbt.es.js.map +1 -1
- package/dist/wbt.min.js +6 -6
- package/dist/wbt.min.js.map +1 -1
- package/lib/BaseFileSystem.js +40 -0
- package/lib/BinaryContainer.js +1 -1
- package/lib/FileSystem.js +1 -38
- package/lib/NodeFileSystem.js +4 -2
- package/lib/WasmCommand.js +168 -18
- package/lib/wbt/index.js +270 -14
- package/lib/wbt/packages/wllama.js +12 -2
- package/lib/wbt/registry.js +11 -2
- package/package.json +1 -1
- package/test/wbt.test.js +24 -5
package/lib/BaseFileSystem.js
CHANGED
|
@@ -79,4 +79,44 @@ class BaseFileSystem {
|
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Represents a binary file stored as raw bytes in the virtual filesystem.
|
|
84
|
+
* Extends Uint8Array so binary-aware commands can access bytes directly,
|
|
85
|
+
* while text-based commands (cat, grep, etc.) get the original data URI
|
|
86
|
+
* via toString() — avoiding the 33% base64 memory overhead at runtime.
|
|
87
|
+
*/
|
|
88
|
+
class BinaryFile extends Uint8Array {
|
|
89
|
+
constructor(buffer, mimeType) {
|
|
90
|
+
super(buffer);
|
|
91
|
+
Object.defineProperty(this, 'mimeType', { value: mimeType, enumerable: false, configurable: false, writable: false });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
toString() {
|
|
95
|
+
if (typeof Buffer !== 'undefined') {
|
|
96
|
+
return `data:${this.mimeType};base64,${Buffer.from(this).toString('base64')}`;
|
|
97
|
+
}
|
|
98
|
+
// Browser path — chunked to avoid stack overflow on large files
|
|
99
|
+
let binary = '';
|
|
100
|
+
const chunk = 8192;
|
|
101
|
+
for (let i = 0; i < this.length; i += chunk) {
|
|
102
|
+
binary += String.fromCharCode(...this.subarray(i, i + chunk));
|
|
103
|
+
}
|
|
104
|
+
return `data:${this.mimeType};base64,${btoa(binary)}`;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Represents a symbolic link stored in the virtual filesystem.
|
|
110
|
+
* Acts as an opaque marker: `_resolveByAbsolutePath` follows these
|
|
111
|
+
* transparently during file access, while lstat-like calls return the
|
|
112
|
+
* SymlinkRef itself so callers can detect and report symlinks.
|
|
113
|
+
*/
|
|
114
|
+
class SymlinkRef {
|
|
115
|
+
constructor(target) {
|
|
116
|
+
this.target = target;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
82
120
|
module.exports = BaseFileSystem;
|
|
121
|
+
module.exports.BinaryFile = BinaryFile;
|
|
122
|
+
module.exports.SymlinkRef = SymlinkRef;
|
package/lib/BinaryContainer.js
CHANGED
package/lib/FileSystem.js
CHANGED
|
@@ -1,44 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const BaseFileSystem = require('./BaseFileSystem');
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Represents a binary file stored as raw bytes in the virtual filesystem.
|
|
7
|
-
* Extends Uint8Array so binary-aware commands can access bytes directly,
|
|
8
|
-
* while text-based commands (cat, grep, etc.) get the original data URI
|
|
9
|
-
* via toString() — avoiding the 33% base64 memory overhead at runtime.
|
|
10
|
-
*/
|
|
11
|
-
class BinaryFile extends Uint8Array {
|
|
12
|
-
constructor(buffer, mimeType) {
|
|
13
|
-
super(buffer);
|
|
14
|
-
Object.defineProperty(this, 'mimeType', { value: mimeType, enumerable: false, configurable: false, writable: false });
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
toString() {
|
|
18
|
-
if (typeof Buffer !== 'undefined') {
|
|
19
|
-
return `data:${this.mimeType};base64,${Buffer.from(this).toString('base64')}`;
|
|
20
|
-
}
|
|
21
|
-
// Browser path — chunked to avoid stack overflow on large files
|
|
22
|
-
let binary = '';
|
|
23
|
-
const chunk = 8192;
|
|
24
|
-
for (let i = 0; i < this.length; i += chunk) {
|
|
25
|
-
binary += String.fromCharCode(...this.subarray(i, i + chunk));
|
|
26
|
-
}
|
|
27
|
-
return `data:${this.mimeType};base64,${btoa(binary)}`;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Represents a symbolic link stored in the virtual filesystem.
|
|
33
|
-
* Acts as an opaque marker: `_resolveByAbsolutePath` follows these
|
|
34
|
-
* transparently during file access, while lstat-like calls return the
|
|
35
|
-
* SymlinkRef itself so callers can detect and report symlinks.
|
|
36
|
-
*/
|
|
37
|
-
class SymlinkRef {
|
|
38
|
-
constructor(target) {
|
|
39
|
-
this.target = target;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
4
|
+
const { BinaryFile, SymlinkRef } = BaseFileSystem;
|
|
42
5
|
|
|
43
6
|
/**
|
|
44
7
|
* Recursively converts `data:<mime>;base64,<...>` strings in a filesystem
|
package/lib/NodeFileSystem.js
CHANGED
|
@@ -140,8 +140,10 @@ class NodeFileSystem extends BaseFileSystem {
|
|
|
140
140
|
if (this._virtualFiles[abs] !== undefined) {
|
|
141
141
|
return;
|
|
142
142
|
}
|
|
143
|
-
|
|
144
|
-
|
|
143
|
+
try {
|
|
144
|
+
nodeFs.chmodSync(abs, mode);
|
|
145
|
+
this._triggerChange();
|
|
146
|
+
} catch (e) { /* ignore chmod errors on virtualized paths */ }
|
|
145
147
|
}
|
|
146
148
|
|
|
147
149
|
getSize(path) {
|
package/lib/WasmCommand.js
CHANGED
|
@@ -671,7 +671,7 @@ function readBytesFromFs(fs, filepath) {
|
|
|
671
671
|
const nodeFs = require('fs');
|
|
672
672
|
return new Uint8Array(nodeFs.readFileSync(fs.absolutePath(filepath)));
|
|
673
673
|
} catch {
|
|
674
|
-
|
|
674
|
+
// Fall through to virtual file map if stored in _virtualFiles
|
|
675
675
|
}
|
|
676
676
|
}
|
|
677
677
|
const content = fs.getFileByPath(filepath);
|
|
@@ -713,17 +713,28 @@ function readBytesFromFs(fs, filepath) {
|
|
|
713
713
|
*/
|
|
714
714
|
function writeBytesToFs(fs, filepath, bytes, mimeType = 'application/octet-stream') {
|
|
715
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
716
|
const copy = new Uint8Array(uint8.byteLength);
|
|
725
717
|
copy.set(uint8);
|
|
726
718
|
const bf = new BinaryFile(copy.buffer, mimeType);
|
|
719
|
+
if (fs.isRealFilesystem) {
|
|
720
|
+
try {
|
|
721
|
+
const nodeFs = require('fs');
|
|
722
|
+
const nodePath = require('path');
|
|
723
|
+
const abs = fs.absolutePath(filepath);
|
|
724
|
+
nodeFs.mkdirSync(nodePath.dirname(abs), { recursive: true });
|
|
725
|
+
nodeFs.writeFileSync(abs, Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
|
|
726
|
+
return;
|
|
727
|
+
} catch {
|
|
728
|
+
if (typeof fs._setFileRaw === 'function') {
|
|
729
|
+
fs._setFileRaw(filepath, bf, true);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
if (typeof fs._setFileRaw === 'function' && filepath.startsWith('/var/lib/wbt/')) {
|
|
735
|
+
fs._setFileRaw(filepath, bf, true);
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
727
738
|
fs.setFileByPath(filepath, bf, true);
|
|
728
739
|
}
|
|
729
740
|
|
|
@@ -748,6 +759,12 @@ async function loadModule(pkgName, cdnUrl, customLoader = null) {
|
|
|
748
759
|
try {
|
|
749
760
|
return await import(/* @vite-ignore */ cdnUrl);
|
|
750
761
|
} catch (err) {
|
|
762
|
+
if (!/^https?:\/\/esm\.sh\//i.test(cdnUrl)) {
|
|
763
|
+
try {
|
|
764
|
+
const fallbackUrl = `https://esm.sh/${pkgName}`;
|
|
765
|
+
return await import(/* @vite-ignore */ fallbackUrl);
|
|
766
|
+
} catch { /* fall through */ }
|
|
767
|
+
}
|
|
751
768
|
throw new Error(`Failed to load WASM package '${pkgName}' from ${cdnUrl}: ${err.message || err}`);
|
|
752
769
|
}
|
|
753
770
|
}
|
|
@@ -766,13 +783,19 @@ function extractHelpFromText(text, scanBareFlags = false) {
|
|
|
766
783
|
const lines = text.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
|
|
767
784
|
const seenOpts = new Set();
|
|
768
785
|
|
|
769
|
-
|
|
786
|
+
// If a "Usage:" line exists when scanning raw binary strings, prefer scanning options from that point onward
|
|
787
|
+
const usageIdx = scanBareFlags ? lines.findIndex(l => /^usage:\s*(.+)/i.test(l)) : -1;
|
|
788
|
+
const startIdx = usageIdx >= 0 ? usageIdx : 0;
|
|
789
|
+
|
|
790
|
+
for (let i = startIdx; i < lines.length; i++) {
|
|
791
|
+
const line = lines[i];
|
|
770
792
|
if (!res.usage && /^usage:\s*(.+)/i.test(line)) {
|
|
771
793
|
res.usage = line.replace(/^usage:\s*/i, '').trim();
|
|
772
794
|
} else if (
|
|
773
795
|
/^(?:-[a-zA-Z0-9?]|--[a-zA-Z0-9][-a-zA-Z0-9]*)(?:\s|,|=|<|\[|$)/.test(line) &&
|
|
774
796
|
line.length <= 120 &&
|
|
775
|
-
!/^(?:-[hHvV],\s*)?--(?:help|version)\b/i.test(line)
|
|
797
|
+
!/^(?:-[hHvV],\s*)?--(?:help|version)\b/i.test(line) &&
|
|
798
|
+
(!scanBareFlags || /^(?:-[a-zA-Z?]|--[a-zA-Z][a-zA-Z0-9-]*)(?:,\s*--?[a-zA-Z0-9-]+)?(?:\s+[<\[a-zA-Z0-9_.->\]]+)*(?:\s+[A-Za-z`'"(][A-Za-z0-9 ,.;:()'"`/<>\[\]=+$\t_-]*|)$/.test(line))
|
|
776
799
|
) {
|
|
777
800
|
if (!seenOpts.has(line)) {
|
|
778
801
|
seenOpts.add(line);
|
|
@@ -857,7 +880,8 @@ function formatWasmHelp(binName, pkgMeta = {}, inspected = null) {
|
|
|
857
880
|
const desc = pkgMeta.description || 'WebAssembly binary';
|
|
858
881
|
const replCfg = (pkgMeta && typeof pkgMeta.repl === 'object') ? pkgMeta.repl : (pkgMeta.repl ? {} : null);
|
|
859
882
|
|
|
860
|
-
const
|
|
883
|
+
const rawDetectedUsage = (inspected && inspected.usage) || pkgMeta.usage;
|
|
884
|
+
const detectedUsage = rawDetectedUsage ? rawDetectedUsage.replace(/%s/g, binName) : null;
|
|
861
885
|
const defaultUsage = replCfg
|
|
862
886
|
? `${binName} [options] ${replCfg.evalFlag ? `[${replCfg.evalFlag} <code>] ` : ''}[file] [args...]`
|
|
863
887
|
: `${binName} [options] [args...]`;
|
|
@@ -932,17 +956,47 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
|
|
|
932
956
|
const isHelp = args.includes('--help') || args.includes('-h');
|
|
933
957
|
const isVersion = !isHelp && (args.includes('--version') || args.includes('-V') || args.includes('-v'));
|
|
934
958
|
this._inspectedWasm = null;
|
|
959
|
+
this._persistedWasmBytes = pkgMeta.wasmPath
|
|
960
|
+
? readBytesFromFs((this.context && this.context.fs) || this.fs, pkgMeta.wasmPath)
|
|
961
|
+
: null;
|
|
962
|
+
if (isHelp && this._persistedWasmBytes && this._persistedWasmBytes.byteLength > 0) {
|
|
963
|
+
this._inspectedWasm = inspectWasmBytes(this._persistedWasmBytes);
|
|
964
|
+
}
|
|
935
965
|
|
|
936
966
|
try {
|
|
937
|
-
// 1. Direct `.wasm` URL
|
|
938
|
-
if (pkgMeta.type === 'wasm' && pkgMeta.wasmUrl && !config.moduleLoader) {
|
|
939
|
-
const bytes = await this._fetchWasmBytes(pkgMeta.wasmUrl);
|
|
967
|
+
// 1. Direct `.wasm` URL or persisted raw WASI binary -> run via WasmCommand
|
|
968
|
+
if (pkgMeta.type === 'wasm' && (this._persistedWasmBytes || pkgMeta.wasmUrl) && !config.moduleLoader) {
|
|
969
|
+
const bytes = this._persistedWasmBytes || await this._fetchWasmBytes(pkgMeta.wasmUrl);
|
|
940
970
|
if (isHelp) this._inspectedWasm = inspectWasmBytes(bytes);
|
|
941
971
|
await this._runRawWasmBytes(bytes, args);
|
|
942
972
|
} else {
|
|
943
973
|
const cdnUrl = pkgMeta.cdnUrl || pkgMeta.wasmUrl || `https://esm.sh/${pkgMeta.name}`;
|
|
944
|
-
const
|
|
945
|
-
|
|
974
|
+
const origFetch = typeof globalThis.fetch === 'function' ? globalThis.fetch : null;
|
|
975
|
+
if (origFetch && this._persistedWasmBytes && this._persistedWasmBytes.byteLength > 0 && typeof Response !== 'undefined') {
|
|
976
|
+
const wasmBytes = this._persistedWasmBytes;
|
|
977
|
+
const wasmUrl = pkgMeta.wasmUrl || '';
|
|
978
|
+
globalThis.fetch = async (input, init) => {
|
|
979
|
+
const reqUrl = typeof input === 'string' ? input : (input && input.url ? input.url : '');
|
|
980
|
+
if (reqUrl && (reqUrl === wasmUrl || (!/^https?:\/\//i.test(reqUrl) && /\.wasm(\?.*)?$/i.test(reqUrl)))) {
|
|
981
|
+
return new Response(wasmBytes, {
|
|
982
|
+
status: 200,
|
|
983
|
+
headers: { 'Content-Type': 'application/wasm' }
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
return origFetch(input, init);
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
let loaded;
|
|
990
|
+
let target;
|
|
991
|
+
try {
|
|
992
|
+
loaded = await loadModule(pkgMeta.name, cdnUrl, config.moduleLoader);
|
|
993
|
+
target = (loaded && loaded.default !== undefined) ? loaded.default : loaded;
|
|
994
|
+
if (target && typeof target.then === 'function') {
|
|
995
|
+
target = await target;
|
|
996
|
+
}
|
|
997
|
+
} finally {
|
|
998
|
+
if (origFetch) globalThis.fetch = origFetch;
|
|
999
|
+
}
|
|
946
1000
|
|
|
947
1001
|
// 2. Raw WASM binary (Uint8Array or ArrayBuffer)
|
|
948
1002
|
if (target instanceof Uint8Array || target instanceof ArrayBuffer) {
|
|
@@ -965,6 +1019,19 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
|
|
|
965
1019
|
const entryFn = target.main || target.run || target.callMain || target.exec;
|
|
966
1020
|
if (typeof entryFn === 'function') {
|
|
967
1021
|
await this._invokeCliFunction(entryFn.bind(target), args);
|
|
1022
|
+
} else if (target.promised || typeof target.raw === 'function' || typeof target.json === 'function') {
|
|
1023
|
+
const jqInst = target.promised ? await target.promised : target;
|
|
1024
|
+
const flags = args.filter(a => a.startsWith('-'));
|
|
1025
|
+
const pos = args.filter(a => !a.startsWith('-'));
|
|
1026
|
+
const filter = pos.shift() || '.';
|
|
1027
|
+
const io = this._createIoBridge(args, [], []);
|
|
1028
|
+
const input = pos.length > 0 ? (io.readFile(pos[0]) || '') : (io.stdin || (isHelp || isVersion ? '{}' : ''));
|
|
1029
|
+
const out = typeof jqInst.raw === 'function'
|
|
1030
|
+
? jqInst.raw(input, filter, flags)
|
|
1031
|
+
: (!isHelp && !isVersion ? JSON.stringify(jqInst.json(JSON.parse(input || 'null'), filter)) : null);
|
|
1032
|
+
if (out != null) {
|
|
1033
|
+
String(out).replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => { this.stdOut = l; });
|
|
1034
|
+
}
|
|
968
1035
|
} else if (!isHelp && !isVersion) {
|
|
969
1036
|
this.stdErr = `${binName}: unsupported WASM module format for '${pkgMeta.name}'`;
|
|
970
1037
|
this.exitCode = 1;
|
|
@@ -1079,6 +1146,8 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
|
|
|
1079
1146
|
stdin: this.stdin !== undefined && this.stdin !== null ? String(this.stdin) : '',
|
|
1080
1147
|
fs: this.fs,
|
|
1081
1148
|
context: this.context,
|
|
1149
|
+
wasmPath: pkgMeta.wasmPath || null,
|
|
1150
|
+
wasmBytes: this._persistedWasmBytes || null,
|
|
1082
1151
|
stdout: Object.assign((line) => outLines.push(String(line)), createStream(outLines)),
|
|
1083
1152
|
stderr: Object.assign((line) => errLines.push(String(line)), createStream(errLines)),
|
|
1084
1153
|
readFile: (filename, baseDir) => {
|
|
@@ -1133,6 +1202,12 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
|
|
|
1133
1202
|
const emscriptenConfig = {
|
|
1134
1203
|
arguments: args,
|
|
1135
1204
|
noInitialRun: true,
|
|
1205
|
+
...(this._persistedWasmBytes && this._persistedWasmBytes.byteLength > 0
|
|
1206
|
+
? { wasmBinary: this._persistedWasmBytes }
|
|
1207
|
+
: {}),
|
|
1208
|
+
...(pkgMeta.wasmUrl
|
|
1209
|
+
? { locateFile: (file) => (file.endsWith('.wasm') ? pkgMeta.wasmUrl : file) }
|
|
1210
|
+
: {}),
|
|
1136
1211
|
print: (text) => { outLines.push(String(text)); },
|
|
1137
1212
|
printErr: (text) => { errLines.push(String(text)); },
|
|
1138
1213
|
stdin: () => (stdinPos < stdinBytes.length ? stdinBytes[stdinPos++] : null),
|
|
@@ -1191,6 +1266,8 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
|
|
|
1191
1266
|
} else if (typeof result.main === 'function' || typeof result.run === 'function') {
|
|
1192
1267
|
const entry = (result.main || result.run).bind(result);
|
|
1193
1268
|
await this._invokeCliFunction(entry, args, outLines, errLines);
|
|
1269
|
+
} else if (!isHelp && !isVersion && typeof result.Database === 'function') {
|
|
1270
|
+
this._runSqlJsDatabase(result, args, ioBridge, outLines);
|
|
1194
1271
|
} else {
|
|
1195
1272
|
if (typeof result.stdout === 'string' && result.stdout) {
|
|
1196
1273
|
result.stdout.replace(/\r?\n$/, '').split(/\r?\n/).forEach(l => outLines.push(l));
|
|
@@ -1216,6 +1293,80 @@ function createGenericWasmCommand(pkgMeta, config = {}, binNameOverride = null)
|
|
|
1216
1293
|
errLines.forEach(l => { this.stdErr = l; });
|
|
1217
1294
|
}
|
|
1218
1295
|
|
|
1296
|
+
_runSqlJsDatabase(SQL, args, io, outLines) {
|
|
1297
|
+
let mode = 'list';
|
|
1298
|
+
let dbPath = ':memory:';
|
|
1299
|
+
let sql = null;
|
|
1300
|
+
const positional = [];
|
|
1301
|
+
|
|
1302
|
+
for (let i = 0; i < args.length; i++) {
|
|
1303
|
+
const a = args[i];
|
|
1304
|
+
if (a === '-table' || a === '--table' || a === '-box') mode = 'table';
|
|
1305
|
+
else if (a === '-csv' || a === '--csv') mode = 'csv';
|
|
1306
|
+
else if (a === '-cmd' && i + 1 < args.length) sql = args[++i];
|
|
1307
|
+
else if (!a.startsWith('-')) positional.push(a);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
if (positional.length === 1) {
|
|
1311
|
+
if (/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|PRAGMA|WITH|BEGIN|EXPLAIN|\.)\b/i.test(positional[0])) {
|
|
1312
|
+
sql = positional[0];
|
|
1313
|
+
} else {
|
|
1314
|
+
dbPath = positional[0];
|
|
1315
|
+
}
|
|
1316
|
+
} else if (positional.length >= 2) {
|
|
1317
|
+
dbPath = positional[0];
|
|
1318
|
+
sql = positional.slice(1).join(' ');
|
|
1319
|
+
}
|
|
1320
|
+
if (!sql && io.stdin && io.stdin.trim()) {
|
|
1321
|
+
sql = io.stdin.trim();
|
|
1322
|
+
}
|
|
1323
|
+
if (!sql) return;
|
|
1324
|
+
|
|
1325
|
+
const existingBytes = dbPath !== ':memory:' ? io.readBytes(dbPath) : null;
|
|
1326
|
+
const db = existingBytes && existingBytes.byteLength > 0
|
|
1327
|
+
? new SQL.Database(existingBytes)
|
|
1328
|
+
: new SQL.Database();
|
|
1329
|
+
|
|
1330
|
+
try {
|
|
1331
|
+
if (sql.trim() === '.tables') {
|
|
1332
|
+
const res = db.exec("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name");
|
|
1333
|
+
const names = (res[0] && res[0].values) ? res[0].values.map(r => r[0]) : [];
|
|
1334
|
+
if (names.length > 0) outLines.push(names.join(' '));
|
|
1335
|
+
} else {
|
|
1336
|
+
const results = db.exec(sql);
|
|
1337
|
+
for (const r of results) {
|
|
1338
|
+
const cols = (r.columns || []).map(String);
|
|
1339
|
+
const rows = r.values || [];
|
|
1340
|
+
if (mode === 'table' && cols.length > 0) {
|
|
1341
|
+
const widths = cols.map(c => c.length);
|
|
1342
|
+
const norm = rows.map(row => cols.map((_, i) => {
|
|
1343
|
+
const s = row[i] == null ? 'NULL' : String(row[i]);
|
|
1344
|
+
if (s.length > widths[i]) widths[i] = s.length;
|
|
1345
|
+
return s;
|
|
1346
|
+
}));
|
|
1347
|
+
outLines.push(cols.map((c, i) => ' ' + c.padEnd(widths[i]) + ' ').join('|'));
|
|
1348
|
+
outLines.push(widths.map(w => '-'.repeat(w + 2)).join('+'));
|
|
1349
|
+
norm.forEach(row => outLines.push(row.map((c, i) => ' ' + c.padEnd(widths[i]) + ' ').join('|')));
|
|
1350
|
+
} else if (mode === 'csv') {
|
|
1351
|
+
const esc = (v) => {
|
|
1352
|
+
const s = v == null ? '' : String(v);
|
|
1353
|
+
return /[",\r\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
|
|
1354
|
+
};
|
|
1355
|
+
if (cols.length > 0) outLines.push(cols.map(esc).join(','));
|
|
1356
|
+
rows.forEach(row => outLines.push(cols.map((_, i) => esc(row[i])).join(',')));
|
|
1357
|
+
} else {
|
|
1358
|
+
rows.forEach(row => outLines.push(cols.map((_, i) => (row[i] == null ? '' : String(row[i]))).join('|')));
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
if (dbPath !== ':memory:') {
|
|
1363
|
+
io.writeFile(dbPath, db.export());
|
|
1364
|
+
}
|
|
1365
|
+
} finally {
|
|
1366
|
+
db.close();
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1219
1370
|
async _runVirtualFsInstance(instance, args, outLines, errLines) {
|
|
1220
1371
|
if (typeof instance.on === 'function') {
|
|
1221
1372
|
instance.on('log', ({ message }) => {
|
|
@@ -1344,4 +1495,3 @@ WasmCommand.createGenericWasmCommand = createGenericWasmCommand;
|
|
|
1344
1495
|
WasmCommand.createCommand = createGenericWasmCommand;
|
|
1345
1496
|
|
|
1346
1497
|
module.exports = WasmCommand;
|
|
1347
|
-
|