@innovatorved/code-lab 0.1.12 → 0.1.13
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/ARCHITECTURE.md +5 -5
- package/README.md +6 -6
- package/dist/code-lab.css +165 -0
- package/dist/code-lab.d.ts +1 -1
- package/dist/code-lab.esm.js +2016 -430
- package/dist/code-lab.js +2014 -429
- package/dist/preview-sw.js +1 -1
- package/dist/runtime.d.ts +1 -0
- package/dist/runtime.esm.js +966 -401
- package/dist/runtime.js +964 -401
- package/dist/shell.esm.js +806 -1
- package/dist/shell.js +806 -1
- package/dist/terminal.esm.js +1 -1
- package/dist/terminal.js +1 -1
- package/package.json +1 -1
- package/src/code-lab.css +165 -0
- package/src/runtime.ts +964 -400
- package/src/shell.ts +805 -0
- package/src/workbench.ts +238 -22
package/dist/code-lab.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab v0.1.
|
|
3
|
+
* @innovatorved/code-lab v0.1.13 — Standalone Browser Code IDE & Virtual Runtime
|
|
4
4
|
* ============================================================
|
|
5
5
|
* Features:
|
|
6
6
|
* - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
|
|
@@ -4376,6 +4376,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4376
4376
|
function createVirtualPortTable() {
|
|
4377
4377
|
const table = new Map();
|
|
4378
4378
|
const listeners = new Map(); // event name -> Set<Function>
|
|
4379
|
+
const chaosRules = new Map(); // port -> ChaosRule
|
|
4379
4380
|
|
|
4380
4381
|
function emit(event, ...args) {
|
|
4381
4382
|
const set = listeners.get(event);
|
|
@@ -4391,6 +4392,43 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4391
4392
|
}
|
|
4392
4393
|
}
|
|
4393
4394
|
|
|
4395
|
+
function normalizeChaosRule(port, partial = {}, existing = null) {
|
|
4396
|
+
const p = Number(port);
|
|
4397
|
+
const base = existing || {
|
|
4398
|
+
port: p,
|
|
4399
|
+
latencyMs: 0,
|
|
4400
|
+
jitterMs: 0,
|
|
4401
|
+
dropRate: 0,
|
|
4402
|
+
errorRate: 0,
|
|
4403
|
+
statusCode: 503,
|
|
4404
|
+
partitionFromPorts: [],
|
|
4405
|
+
crashed: false
|
|
4406
|
+
};
|
|
4407
|
+
const merged = Object.assign({}, base, partial, { port: p });
|
|
4408
|
+
merged.latencyMs = Math.max(0, Number(merged.latencyMs) || 0);
|
|
4409
|
+
merged.jitterMs = Math.max(0, Number(merged.jitterMs) || 0);
|
|
4410
|
+
merged.dropRate = Math.max(0, Math.min(1, Number(merged.dropRate) || 0));
|
|
4411
|
+
merged.errorRate = Math.max(0, Math.min(1, Number(merged.errorRate) || 0));
|
|
4412
|
+
merged.statusCode = Number(merged.statusCode) || 503;
|
|
4413
|
+
merged.partitionFromPorts = Array.isArray(merged.partitionFromPorts)
|
|
4414
|
+
? Array.from(new Set(merged.partitionFromPorts.map(Number).filter((n) => Number.isFinite(n) && n > 0)))
|
|
4415
|
+
: [];
|
|
4416
|
+
merged.crashed = Boolean(merged.crashed);
|
|
4417
|
+
return merged;
|
|
4418
|
+
}
|
|
4419
|
+
|
|
4420
|
+
function isRuleActive(rule) {
|
|
4421
|
+
if (!rule) return false;
|
|
4422
|
+
return Boolean(
|
|
4423
|
+
rule.crashed ||
|
|
4424
|
+
rule.latencyMs > 0 ||
|
|
4425
|
+
rule.jitterMs > 0 ||
|
|
4426
|
+
rule.dropRate > 0 ||
|
|
4427
|
+
rule.errorRate > 0 ||
|
|
4428
|
+
(Array.isArray(rule.partitionFromPorts) && rule.partitionFromPorts.length > 0)
|
|
4429
|
+
);
|
|
4430
|
+
}
|
|
4431
|
+
|
|
4394
4432
|
return {
|
|
4395
4433
|
on(event, fn) {
|
|
4396
4434
|
if (typeof fn !== 'function') return () => {};
|
|
@@ -4456,22 +4494,125 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4456
4494
|
listServers() {
|
|
4457
4495
|
return Array.from(table.values());
|
|
4458
4496
|
},
|
|
4497
|
+
setChaosRule(port, partial = {}) {
|
|
4498
|
+
const p = Number(port);
|
|
4499
|
+
const updated = normalizeChaosRule(p, partial, chaosRules.get(p) || null);
|
|
4500
|
+
if (isRuleActive(updated)) {
|
|
4501
|
+
chaosRules.set(p, updated);
|
|
4502
|
+
} else {
|
|
4503
|
+
chaosRules.delete(p);
|
|
4504
|
+
}
|
|
4505
|
+
emit('chaos', p, updated);
|
|
4506
|
+
return updated;
|
|
4507
|
+
},
|
|
4508
|
+
getChaosRule(port) {
|
|
4509
|
+
return chaosRules.get(Number(port)) || null;
|
|
4510
|
+
},
|
|
4511
|
+
listChaosRules() {
|
|
4512
|
+
return Array.from(chaosRules.values());
|
|
4513
|
+
},
|
|
4514
|
+
clearChaosRules(port) {
|
|
4515
|
+
if (port !== undefined && port !== null && port !== '') {
|
|
4516
|
+
const p = Number(port);
|
|
4517
|
+
const deleted = chaosRules.delete(p);
|
|
4518
|
+
emit('chaos', p, null);
|
|
4519
|
+
return deleted;
|
|
4520
|
+
}
|
|
4521
|
+
chaosRules.clear();
|
|
4522
|
+
emit('chaos', null, null);
|
|
4523
|
+
return true;
|
|
4524
|
+
},
|
|
4459
4525
|
async dispatchRequest(url, init = {}) {
|
|
4460
4526
|
const parsed = new URL(url);
|
|
4461
4527
|
const port = Number(parsed.port || (parsed.protocol === 'https:' ? 443 : 80));
|
|
4528
|
+
const rawHdrs = (init && init.headers) || {};
|
|
4529
|
+
const hdrFromPort = typeof rawHdrs.get === 'function'
|
|
4530
|
+
? rawHdrs.get('x-codelab-from-port')
|
|
4531
|
+
: (rawHdrs['x-codelab-from-port'] || rawHdrs['X-CodeLab-From-Port']);
|
|
4532
|
+
const fromPort = Number((init && init._fromPort) || hdrFromPort || 0) || null;
|
|
4533
|
+
const rule = chaosRules.get(port);
|
|
4534
|
+
let appliedDelayMs = 0;
|
|
4535
|
+
|
|
4536
|
+
if (rule) {
|
|
4537
|
+
let delay = Number(rule.latencyMs) || 0;
|
|
4538
|
+
if (rule.jitterMs > 0) {
|
|
4539
|
+
delay += Math.round((Math.random() * 2 - 1) * Number(rule.jitterMs));
|
|
4540
|
+
}
|
|
4541
|
+
delay = Math.max(0, delay);
|
|
4542
|
+
if (delay > 0) {
|
|
4543
|
+
appliedDelayMs = delay;
|
|
4544
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
4545
|
+
}
|
|
4546
|
+
|
|
4547
|
+
if (rule.crashed) {
|
|
4548
|
+
const err = new Error(`connect ECONNREFUSED 127.0.0.1:${port} (chaos: node crashed)`);
|
|
4549
|
+
err.code = 'ECONNREFUSED';
|
|
4550
|
+
err.chaosEffect = 'CRASHED';
|
|
4551
|
+
err.fromPort = fromPort;
|
|
4552
|
+
throw err;
|
|
4553
|
+
}
|
|
4554
|
+
|
|
4555
|
+
if (fromPort && Array.isArray(rule.partitionFromPorts) && rule.partitionFromPorts.includes(fromPort)) {
|
|
4556
|
+
const err = new Error(`connect EHOSTUNREACH 127.0.0.1:${port} (chaos: network partition from :${fromPort})`);
|
|
4557
|
+
err.code = 'EHOSTUNREACH';
|
|
4558
|
+
err.chaosEffect = `PARTITION(:${fromPort}-x->:${port})`;
|
|
4559
|
+
err.fromPort = fromPort;
|
|
4560
|
+
throw err;
|
|
4561
|
+
}
|
|
4562
|
+
|
|
4563
|
+
if (rule.dropRate > 0 && Math.random() < rule.dropRate) {
|
|
4564
|
+
const err = new Error(`socket hang up 127.0.0.1:${port} (chaos: packet dropped)`);
|
|
4565
|
+
err.code = 'ETIMEDOUT';
|
|
4566
|
+
err.chaosEffect = 'DROPPED';
|
|
4567
|
+
err.fromPort = fromPort;
|
|
4568
|
+
throw err;
|
|
4569
|
+
}
|
|
4570
|
+
|
|
4571
|
+
if (rule.errorRate > 0 && Math.random() < rule.errorRate) {
|
|
4572
|
+
const status = Number(rule.statusCode) || 503;
|
|
4573
|
+
const statusText = status === 429
|
|
4574
|
+
? 'Too Many Requests'
|
|
4575
|
+
: (status === 504 ? 'Gateway Timeout' : 'Service Unavailable');
|
|
4576
|
+
const chaosTag = appliedDelayMs > 0 ? `ERROR_${status}+${appliedDelayMs}ms` : `ERROR_${status}`;
|
|
4577
|
+
const res = new Response(
|
|
4578
|
+
JSON.stringify({ error: `${statusText} (Chaos Injected)`, chaos: true, port, status }),
|
|
4579
|
+
{
|
|
4580
|
+
status,
|
|
4581
|
+
statusText,
|
|
4582
|
+
headers: {
|
|
4583
|
+
'content-type': 'application/json',
|
|
4584
|
+
'x-codelab-chaos': chaosTag
|
|
4585
|
+
}
|
|
4586
|
+
}
|
|
4587
|
+
);
|
|
4588
|
+
res._chaosEffect = chaosTag;
|
|
4589
|
+
res._fromPort = fromPort;
|
|
4590
|
+
return res;
|
|
4591
|
+
}
|
|
4592
|
+
}
|
|
4593
|
+
|
|
4462
4594
|
const entry = table.get(port);
|
|
4463
4595
|
if (!entry) {
|
|
4464
4596
|
const err = new Error(`connect ECONNREFUSED 127.0.0.1:${port}`);
|
|
4465
4597
|
err.code = 'ECONNREFUSED';
|
|
4598
|
+
err.fromPort = fromPort;
|
|
4466
4599
|
throw err;
|
|
4467
4600
|
}
|
|
4601
|
+
let res;
|
|
4468
4602
|
if (entry.fetch) {
|
|
4469
|
-
|
|
4603
|
+
res = await entry.fetch(new Request(url, init));
|
|
4604
|
+
} else if (entry.server && typeof entry.server.dispatchRequest === 'function') {
|
|
4605
|
+
res = await entry.server.dispatchRequest(url, init);
|
|
4606
|
+
} else {
|
|
4607
|
+
res = new Response('OK', { status: 200 });
|
|
4470
4608
|
}
|
|
4471
|
-
if (
|
|
4472
|
-
|
|
4609
|
+
if (res && typeof res === 'object') {
|
|
4610
|
+
res._fromPort = fromPort;
|
|
4611
|
+
if (appliedDelayMs > 0 && !res._chaosEffect) {
|
|
4612
|
+
res._chaosEffect = `DELAY_+${appliedDelayMs}ms`;
|
|
4613
|
+
}
|
|
4473
4614
|
}
|
|
4474
|
-
return
|
|
4615
|
+
return res;
|
|
4475
4616
|
}
|
|
4476
4617
|
};
|
|
4477
4618
|
}
|
|
@@ -4803,6 +4944,78 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4803
4944
|
return;
|
|
4804
4945
|
}
|
|
4805
4946
|
const server = activeServers.get(this.port);
|
|
4947
|
+
const hasChaosRule = Boolean(
|
|
4948
|
+
activePortTable &&
|
|
4949
|
+
typeof activePortTable.getChaosRule === 'function' &&
|
|
4950
|
+
activePortTable.getChaosRule(this.port)
|
|
4951
|
+
);
|
|
4952
|
+
const hasPortTableServer = Boolean(
|
|
4953
|
+
activePortTable &&
|
|
4954
|
+
typeof activePortTable.getServer === 'function' &&
|
|
4955
|
+
activePortTable.getServer(this.port)
|
|
4956
|
+
);
|
|
4957
|
+
if ((!server || !server._listening || hasChaosRule) && activePortTable && (hasPortTableServer || hasChaosRule) && typeof activePortTable.dispatchRequest === 'function') {
|
|
4958
|
+
let inferredFromPort = null;
|
|
4959
|
+
if (activeServers.size > 0) {
|
|
4960
|
+
const firstLocalPort = Array.from(activeServers.keys()).find((p) => Number(p) !== Number(this.port));
|
|
4961
|
+
if (firstLocalPort) inferredFromPort = firstLocalPort;
|
|
4962
|
+
} else if (resourceTracker && resourceTracker.pid && typeof activePortTable.listServers === 'function') {
|
|
4963
|
+
const owned = activePortTable.listServers().find((s) => s && s.pid === resourceTracker.pid && Number(s.port) !== Number(this.port));
|
|
4964
|
+
if (owned) inferredFromPort = owned.port;
|
|
4965
|
+
}
|
|
4966
|
+
const reqBody = this._bodyChunks.length > 0 ? VirtualBuffer.concat(this._bodyChunks) : undefined;
|
|
4967
|
+
const fullUrl = `http://${this.host}:${this.port}${this.path.startsWith('/') ? '' : '/'}${this.path}`;
|
|
4968
|
+
activePortTable.dispatchRequest(fullUrl, {
|
|
4969
|
+
method: this.method,
|
|
4970
|
+
headers: { ...this.headers },
|
|
4971
|
+
body: reqBody,
|
|
4972
|
+
_fromPort: inferredFromPort
|
|
4973
|
+
}).then(async (res) => {
|
|
4974
|
+
if (this.destroyed) {
|
|
4975
|
+
this._finishInFlight();
|
|
4976
|
+
return;
|
|
4977
|
+
}
|
|
4978
|
+
const resHeaders = {};
|
|
4979
|
+
if (res && res.headers && typeof res.headers.forEach === 'function') {
|
|
4980
|
+
res.headers.forEach((v, k) => { resHeaders[String(k).toLowerCase()] = String(v); });
|
|
4981
|
+
}
|
|
4982
|
+
let buf = VirtualBuffer.alloc(0);
|
|
4983
|
+
if (res && typeof res.arrayBuffer === 'function') {
|
|
4984
|
+
const ab = await res.arrayBuffer();
|
|
4985
|
+
buf = VirtualBuffer.from(ab);
|
|
4986
|
+
}
|
|
4987
|
+
traceEntry.status = (res && res.status) || 200;
|
|
4988
|
+
traceEntry.durationMs = Math.max(0, performance.now() - traceEntry._t0);
|
|
4989
|
+
traceEntry.responseBytes = buf.length;
|
|
4990
|
+
traceEntry.responseHeaders = resHeaders;
|
|
4991
|
+
if (inferredFromPort) traceEntry.fromPort = inferredFromPort;
|
|
4992
|
+
if (res && res._chaosEffect) traceEntry.chaosEffect = res._chaosEffect;
|
|
4993
|
+
const clientRes = new IncomingMessage({
|
|
4994
|
+
statusCode: (res && res.status) || 200,
|
|
4995
|
+
headers: resHeaders
|
|
4996
|
+
});
|
|
4997
|
+
this._onResponseHeaders(clientRes);
|
|
4998
|
+
if (buf.length > 0) clientRes._pushData(buf);
|
|
4999
|
+
clientRes._pushEnd();
|
|
5000
|
+
this._finishInFlight();
|
|
5001
|
+
}).catch((err) => {
|
|
5002
|
+
if (this.destroyed) {
|
|
5003
|
+
this._finishInFlight();
|
|
5004
|
+
return;
|
|
5005
|
+
}
|
|
5006
|
+
err.errno = err.errno || -61;
|
|
5007
|
+
err.syscall = err.syscall || 'connect';
|
|
5008
|
+
err.address = this.host;
|
|
5009
|
+
err.port = this.port;
|
|
5010
|
+
traceEntry.status = err.code || 'ECONNREFUSED';
|
|
5011
|
+
traceEntry.durationMs = Math.max(0, performance.now() - traceEntry._t0);
|
|
5012
|
+
if (inferredFromPort) traceEntry.fromPort = inferredFromPort;
|
|
5013
|
+
if (err && err.chaosEffect) traceEntry.chaosEffect = err.chaosEffect;
|
|
5014
|
+
this._finishInFlight();
|
|
5015
|
+
this.emit('error', err);
|
|
5016
|
+
});
|
|
5017
|
+
return;
|
|
5018
|
+
}
|
|
4806
5019
|
if (!server || !server._listening) {
|
|
4807
5020
|
const err = new Error(`connect ECONNREFUSED ${this.host}:${this.port}`);
|
|
4808
5021
|
err.code = 'ECONNREFUSED';
|
|
@@ -8381,411 +8594,114 @@ function __initVirtualRuntime(rootScope) {
|
|
|
8381
8594
|
});
|
|
8382
8595
|
});
|
|
8383
8596
|
|
|
8384
|
-
|
|
8385
|
-
constructor(filename = ':memory:') {
|
|
8386
|
-
this.filename = filename;
|
|
8387
|
-
this.tables = new Map();
|
|
8388
|
-
}
|
|
8389
|
-
|
|
8390
|
-
run(sql, params = []) {
|
|
8391
|
-
const stmt = sql.trim();
|
|
8392
|
-
if (/^CREATE\s+TABLE/i.test(stmt)) {
|
|
8393
|
-
const match = stmt.match(/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s*\((.*)\)/is);
|
|
8394
|
-
if (match) {
|
|
8395
|
-
const tableName = match[1];
|
|
8396
|
-
const colDefs = match[2].split(',').map(c => c.trim());
|
|
8397
|
-
const cols = [];
|
|
8398
|
-
for (const c of colDefs) {
|
|
8399
|
-
const parts = c.split(/\s+/);
|
|
8400
|
-
const colName = parts[0];
|
|
8401
|
-
const isPk = /PRIMARY\s+KEY/i.test(c);
|
|
8402
|
-
const isAuto = /AUTOINCREMENT/i.test(c) || (/INTEGER/i.test(parts[1]) && isPk);
|
|
8403
|
-
cols.push({ name: colName, type: parts[1] || 'TEXT', isPk, isAuto });
|
|
8404
|
-
}
|
|
8405
|
-
if (!this.tables.has(tableName)) {
|
|
8406
|
-
this.tables.set(tableName, { columns: cols, rows: [], autoInc: 0 });
|
|
8407
|
-
}
|
|
8408
|
-
}
|
|
8409
|
-
return { changes: 0, lastInsertRowid: 0 };
|
|
8410
|
-
}
|
|
8411
|
-
|
|
8412
|
-
if (/^DROP\s+TABLE/i.test(stmt)) {
|
|
8413
|
-
const match = stmt.match(/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);
|
|
8414
|
-
if (match) this.tables.delete(match[1]);
|
|
8415
|
-
return { changes: 0, lastInsertRowid: 0 };
|
|
8416
|
-
}
|
|
8417
|
-
|
|
8418
|
-
if (/^INSERT\s+INTO/i.test(stmt)) {
|
|
8419
|
-
const match = stmt.match(/^INSERT\s+INTO\s+([a-zA-Z0-9_]+)(?:\s*\(([^)]+)\))?\s*VALUES\s*\((.*)\)/is);
|
|
8420
|
-
if (match) {
|
|
8421
|
-
const tableName = match[1];
|
|
8422
|
-
const table = this.tables.get(tableName);
|
|
8423
|
-
if (!table) throw new Error(`no such table: ${tableName}`);
|
|
8424
|
-
const colNames = match[2] ? match[2].split(',').map(s => s.trim()) : table.columns.filter(c => !c.isPk).map(c => c.name);
|
|
8425
|
-
const valExprs = match[3].split(',').map(s => s.trim());
|
|
8426
|
-
const pList = Array.isArray(params) ? [...params] : [params];
|
|
8427
|
-
const row = {};
|
|
8597
|
+
const SqliteDatabase = createSqliteDatabase(vfs, () => sandboxProcess.cwd());
|
|
8428
8598
|
|
|
8429
|
-
|
|
8430
|
-
|
|
8431
|
-
|
|
8432
|
-
row[pkCol.name] = table.autoInc;
|
|
8433
|
-
}
|
|
8599
|
+
function crc32Hash(str) {
|
|
8600
|
+
return VirtualZlib.crc32( typeof str === 'string' || str instanceof Uint8Array ? str : String(str) );
|
|
8601
|
+
}
|
|
8434
8602
|
|
|
8435
|
-
|
|
8436
|
-
|
|
8437
|
-
|
|
8438
|
-
|
|
8439
|
-
|
|
8440
|
-
|
|
8441
|
-
|
|
8442
|
-
|
|
8443
|
-
|
|
8444
|
-
} else {
|
|
8445
|
-
row[cName] = expr;
|
|
8446
|
-
}
|
|
8447
|
-
}
|
|
8448
|
-
table.rows.push(row);
|
|
8449
|
-
return { changes: 1, lastInsertRowid: table.autoInc };
|
|
8450
|
-
}
|
|
8451
|
-
}
|
|
8603
|
+
const bunHashFn = function hash(val) {
|
|
8604
|
+
return crc32Hash(val);
|
|
8605
|
+
};
|
|
8606
|
+
bunHashFn.crc32 = (val) => crc32Hash(val);
|
|
8607
|
+
bunHashFn.cityHash64 = (val) => {
|
|
8608
|
+
const h1 = crc32Hash(val);
|
|
8609
|
+
const h2 = crc32Hash(String(val) + ':seed64');
|
|
8610
|
+
return (BigInt(h1) << 32n) | BigInt(h2);
|
|
8611
|
+
};
|
|
8452
8612
|
|
|
8453
|
-
|
|
8454
|
-
|
|
8455
|
-
|
|
8456
|
-
const table = this.tables.get(match[1]);
|
|
8457
|
-
if (!table) throw new Error(`no such table: ${match[1]}`);
|
|
8458
|
-
const whereClause = match[2] ? match[2].trim() : null;
|
|
8459
|
-
const pList = Array.isArray(params) ? [...params] : [params];
|
|
8460
|
-
const beforeLen = table.rows.length;
|
|
8461
|
-
if (!whereClause) {
|
|
8462
|
-
table.rows = [];
|
|
8463
|
-
} else {
|
|
8464
|
-
table.rows = table.rows.filter(r => !this._matchWhere(r, whereClause, pList));
|
|
8465
|
-
}
|
|
8466
|
-
return { changes: beforeLen - table.rows.length, lastInsertRowid: table.autoInc };
|
|
8467
|
-
}
|
|
8468
|
-
}
|
|
8613
|
+
function deepEquals(a, b) {
|
|
8614
|
+
return isDeepEqual(a, b, true);
|
|
8615
|
+
}
|
|
8469
8616
|
|
|
8470
|
-
|
|
8471
|
-
|
|
8472
|
-
|
|
8473
|
-
|
|
8474
|
-
|
|
8475
|
-
|
|
8476
|
-
|
|
8477
|
-
|
|
8478
|
-
|
|
8479
|
-
|
|
8480
|
-
|
|
8481
|
-
const setUpdates = [];
|
|
8482
|
-
for (const sp of setParts) {
|
|
8483
|
-
const eqIdx = sp.indexOf('=');
|
|
8484
|
-
const col = sp.slice(0, eqIdx).trim();
|
|
8485
|
-
let valExpr = sp.slice(eqIdx + 1).trim();
|
|
8486
|
-
let val = valExpr === '?' ? rowParams.shift() : (/^['"].*['"]$/.test(valExpr) ? valExpr.slice(1, -1) : (!isNaN(Number(valExpr)) ? Number(valExpr) : valExpr));
|
|
8487
|
-
setUpdates.push([col, val]);
|
|
8488
|
-
}
|
|
8489
|
-
if (!whereClause || this._matchWhere(row, whereClause, rowParams)) {
|
|
8490
|
-
for (const [col, val] of setUpdates) row[col] = val;
|
|
8491
|
-
changes++;
|
|
8492
|
-
}
|
|
8493
|
-
}
|
|
8494
|
-
return { changes, lastInsertRowid: table.autoInc };
|
|
8617
|
+
const BunObj = {
|
|
8618
|
+
version: '1.1.0',
|
|
8619
|
+
serve(opts = {}) {
|
|
8620
|
+
const port = Number(opts.port || 3000);
|
|
8621
|
+
const hostname = opts.hostname || '127.0.0.1';
|
|
8622
|
+
const serverObj = {
|
|
8623
|
+
port,
|
|
8624
|
+
hostname,
|
|
8625
|
+
development: false,
|
|
8626
|
+
stop() {
|
|
8627
|
+
activePortTable.unregisterServer(port);
|
|
8495
8628
|
}
|
|
8496
|
-
}
|
|
8497
|
-
|
|
8498
|
-
|
|
8499
|
-
|
|
8500
|
-
|
|
8501
|
-
|
|
8502
|
-
|
|
8503
|
-
|
|
8504
|
-
|
|
8505
|
-
|
|
8506
|
-
|
|
8507
|
-
|
|
8508
|
-
|
|
8509
|
-
expected = pList.shift();
|
|
8510
|
-
} else if (/^['"].*['"]$/.test(expected)) {
|
|
8511
|
-
expected = expected.slice(1, -1);
|
|
8512
|
-
} else if (!isNaN(Number(expected))) {
|
|
8513
|
-
expected = Number(expected);
|
|
8514
|
-
}
|
|
8515
|
-
const actual = row[col];
|
|
8516
|
-
if (op === '=') return String(actual) === String(expected);
|
|
8517
|
-
if (op === '!=' || op === '<>') return String(actual) !== String(expected);
|
|
8518
|
-
if (op === '>') return Number(actual) > Number(expected);
|
|
8519
|
-
if (op === '<') return Number(actual) < Number(expected);
|
|
8520
|
-
if (op === '>=') return Number(actual) >= Number(expected);
|
|
8521
|
-
if (op === '<=') return Number(actual) <= Number(expected);
|
|
8522
|
-
}
|
|
8523
|
-
return true;
|
|
8524
|
-
}
|
|
8525
|
-
|
|
8526
|
-
exec(sql) {
|
|
8527
|
-
const statements = sql.split(';').map(s => s.trim()).filter(Boolean);
|
|
8528
|
-
for (const s of statements) {
|
|
8529
|
-
this.run(s);
|
|
8530
|
-
}
|
|
8531
|
-
}
|
|
8532
|
-
|
|
8533
|
-
transaction(fn) {
|
|
8534
|
-
return (...args) => fn(...args);
|
|
8535
|
-
}
|
|
8536
|
-
|
|
8537
|
-
close() {}
|
|
8538
|
-
|
|
8539
|
-
query(sql) {
|
|
8540
|
-
const db = this;
|
|
8629
|
+
};
|
|
8630
|
+
activePortTable.registerServer(port, {
|
|
8631
|
+
server: serverObj,
|
|
8632
|
+
name: opts.name || 'bun-server',
|
|
8633
|
+
port,
|
|
8634
|
+
pid: resourceTracker.pid || 1,
|
|
8635
|
+
fetch: opts.fetch ? opts.fetch.bind(serverObj) : undefined,
|
|
8636
|
+
stop: () => serverObj.stop()
|
|
8637
|
+
});
|
|
8638
|
+
return serverObj;
|
|
8639
|
+
},
|
|
8640
|
+
file(p) {
|
|
8641
|
+
const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(p));
|
|
8541
8642
|
return {
|
|
8542
|
-
|
|
8543
|
-
|
|
8544
|
-
|
|
8545
|
-
|
|
8643
|
+
name: VirtualPath.basename(resolved),
|
|
8644
|
+
get size() {
|
|
8645
|
+
try {
|
|
8646
|
+
return vfs.statSync(resolved).size;
|
|
8647
|
+
} catch (_) {
|
|
8648
|
+
return 0;
|
|
8649
|
+
}
|
|
8546
8650
|
},
|
|
8547
|
-
|
|
8548
|
-
|
|
8549
|
-
return rows[0] || null;
|
|
8651
|
+
async exists() {
|
|
8652
|
+
return vfs.existsSync(resolved);
|
|
8550
8653
|
},
|
|
8551
|
-
|
|
8552
|
-
|
|
8553
|
-
return rows.map(r => Object.values(r));
|
|
8654
|
+
async text() {
|
|
8655
|
+
return vfs.readFileSync(resolved, 'utf8');
|
|
8554
8656
|
},
|
|
8555
|
-
|
|
8556
|
-
|
|
8557
|
-
|
|
8558
|
-
|
|
8657
|
+
async json() {
|
|
8658
|
+
return JSON.parse(vfs.readFileSync(resolved, 'utf8'));
|
|
8659
|
+
},
|
|
8660
|
+
async arrayBuffer() {
|
|
8661
|
+
const buf = vfs.readFileSync(resolved);
|
|
8662
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
8559
8663
|
}
|
|
8560
8664
|
};
|
|
8665
|
+
},
|
|
8666
|
+
async write(dest, data) {
|
|
8667
|
+
const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(dest));
|
|
8668
|
+
const dir = VirtualPath.dirname(resolved);
|
|
8669
|
+
if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
|
|
8670
|
+
let buf;
|
|
8671
|
+
if (typeof data === 'string') {
|
|
8672
|
+
buf = VirtualBuffer.from(data, 'utf8');
|
|
8673
|
+
} else if (data && data.arrayBuffer && typeof data.arrayBuffer === 'function') {
|
|
8674
|
+
const ab = await data.arrayBuffer();
|
|
8675
|
+
buf = VirtualBuffer.from(ab);
|
|
8676
|
+
} else if (data instanceof Uint8Array || VirtualBuffer.isBuffer(data)) {
|
|
8677
|
+
buf = VirtualBuffer.from(data);
|
|
8678
|
+
} else {
|
|
8679
|
+
buf = VirtualBuffer.from(String(data), 'utf8');
|
|
8680
|
+
}
|
|
8681
|
+
vfs.writeFileSync(resolved, buf);
|
|
8682
|
+
return buf.length;
|
|
8683
|
+
},
|
|
8684
|
+
sleep(ms) {
|
|
8685
|
+
return new Promise(resolve => sandboxSetTimeout(resolve, Number(ms) || 0));
|
|
8686
|
+
},
|
|
8687
|
+
hash: bunHashFn,
|
|
8688
|
+
deepEquals,
|
|
8689
|
+
inspect(val) {
|
|
8690
|
+
return VirtualUtil.inspect(val);
|
|
8691
|
+
},
|
|
8692
|
+
nanoseconds() {
|
|
8693
|
+
return Math.round(performance.now() * 1e6);
|
|
8561
8694
|
}
|
|
8695
|
+
};
|
|
8562
8696
|
|
|
8563
|
-
|
|
8564
|
-
|
|
8565
|
-
|
|
8566
|
-
|
|
8567
|
-
|
|
8568
|
-
|
|
8569
|
-
|
|
8570
|
-
|
|
8571
|
-
const selectColsRaw = match[1].trim();
|
|
8572
|
-
const tableName = match[2].trim();
|
|
8573
|
-
const whereClause = match[3] ? match[3].trim() : null;
|
|
8574
|
-
const groupByClause = match[4] ? match[4].trim() : null;
|
|
8575
|
-
const orderByClause = match[5] ? match[5].trim() : null;
|
|
8576
|
-
const limitRaw = match[6] ? match[6].trim() : null;
|
|
8577
|
-
const offsetRaw = match[7] ? match[7].trim() : null;
|
|
8578
|
-
|
|
8579
|
-
const table = this.tables.get(tableName);
|
|
8580
|
-
if (!table) return [];
|
|
8581
|
-
|
|
8582
|
-
let pList = Array.isArray(params) ? [...params] : [params];
|
|
8583
|
-
let filteredRows = table.rows.filter(row => {
|
|
8584
|
-
const rowParams = [...pList];
|
|
8585
|
-
return this._matchWhere(row, whereClause, rowParams);
|
|
8586
|
-
});
|
|
8587
|
-
if (whereClause && whereClause.includes('?')) {
|
|
8588
|
-
const qCount = (whereClause.match(/\?/g) || []).length;
|
|
8589
|
-
pList.splice(0, qCount);
|
|
8590
|
-
}
|
|
8591
|
-
|
|
8592
|
-
const colSpecs = [];
|
|
8593
|
-
if (selectColsRaw !== '*') {
|
|
8594
|
-
const parts = selectColsRaw.split(',').map(p => p.trim());
|
|
8595
|
-
for (const p of parts) {
|
|
8596
|
-
const asMatch = p.match(/^(.*?)\s+(?:as\s+)?([a-zA-Z0-9_]+)$/i);
|
|
8597
|
-
if (asMatch) {
|
|
8598
|
-
colSpecs.push({ expr: asMatch[1].trim(), alias: asMatch[2].trim() });
|
|
8599
|
-
} else {
|
|
8600
|
-
colSpecs.push({ expr: p, alias: p });
|
|
8601
|
-
}
|
|
8602
|
-
}
|
|
8603
|
-
}
|
|
8604
|
-
|
|
8605
|
-
let outputRows = [];
|
|
8606
|
-
if (groupByClause) {
|
|
8607
|
-
const groupCol = groupByClause.trim();
|
|
8608
|
-
const groups = new Map();
|
|
8609
|
-
for (const row of filteredRows) {
|
|
8610
|
-
const key = row[groupCol];
|
|
8611
|
-
if (!groups.has(key)) groups.set(key, []);
|
|
8612
|
-
groups.get(key).push(row);
|
|
8613
|
-
}
|
|
8614
|
-
|
|
8615
|
-
for (const [key, rows] of groups.entries()) {
|
|
8616
|
-
const outRow = {};
|
|
8617
|
-
for (const col of colSpecs) {
|
|
8618
|
-
const expr = col.expr;
|
|
8619
|
-
const alias = col.alias;
|
|
8620
|
-
const aggMatch = expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\(([a-zA-Z0-9_*]+)\)$/i);
|
|
8621
|
-
if (aggMatch) {
|
|
8622
|
-
const fn = aggMatch[1].toUpperCase();
|
|
8623
|
-
const aggCol = aggMatch[2];
|
|
8624
|
-
if (fn === 'COUNT') {
|
|
8625
|
-
outRow[alias] = rows.length;
|
|
8626
|
-
} else if (fn === 'AVG') {
|
|
8627
|
-
const sum = rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
|
|
8628
|
-
outRow[alias] = rows.length > 0 ? sum / rows.length : 0;
|
|
8629
|
-
} else if (fn === 'SUM') {
|
|
8630
|
-
outRow[alias] = rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
|
|
8631
|
-
} else if (fn === 'MIN') {
|
|
8632
|
-
outRow[alias] = Math.min(...rows.map(r => Number(r[aggCol]) || 0));
|
|
8633
|
-
} else if (fn === 'MAX') {
|
|
8634
|
-
outRow[alias] = Math.max(...rows.map(r => Number(r[aggCol]) || 0));
|
|
8635
|
-
}
|
|
8636
|
-
} else if (expr === groupCol) {
|
|
8637
|
-
outRow[alias] = key;
|
|
8638
|
-
} else {
|
|
8639
|
-
outRow[alias] = rows[0] ? rows[0][expr] : null;
|
|
8640
|
-
}
|
|
8641
|
-
}
|
|
8642
|
-
outputRows.push(outRow);
|
|
8643
|
-
}
|
|
8644
|
-
} else {
|
|
8645
|
-
for (const row of filteredRows) {
|
|
8646
|
-
if (selectColsRaw === '*') {
|
|
8647
|
-
outputRows.push(Object.assign({}, row));
|
|
8648
|
-
} else {
|
|
8649
|
-
const outRow = {};
|
|
8650
|
-
for (const col of colSpecs) {
|
|
8651
|
-
outRow[col.alias] = row[col.expr];
|
|
8652
|
-
}
|
|
8653
|
-
outputRows.push(outRow);
|
|
8654
|
-
}
|
|
8655
|
-
}
|
|
8656
|
-
}
|
|
8657
|
-
|
|
8658
|
-
if (orderByClause) {
|
|
8659
|
-
const parts = orderByClause.trim().split(/\s+/);
|
|
8660
|
-
const orderCol = parts[0];
|
|
8661
|
-
const desc = parts[1] && parts[1].toUpperCase() === 'DESC';
|
|
8662
|
-
outputRows.sort((a, b) => {
|
|
8663
|
-
const valA = a[orderCol];
|
|
8664
|
-
const valB = b[orderCol];
|
|
8665
|
-
if (valA === valB) return 0;
|
|
8666
|
-
if (valA === undefined) return 1;
|
|
8667
|
-
if (valB === undefined) return -1;
|
|
8668
|
-
const res = valA > valB ? 1 : -1;
|
|
8669
|
-
return desc ? -res : res;
|
|
8670
|
-
});
|
|
8671
|
-
}
|
|
8672
|
-
|
|
8673
|
-
if (limitRaw !== null) {
|
|
8674
|
-
const limitVal = limitRaw === '?' ? Number(pList.shift() || 0) : Number(limitRaw);
|
|
8675
|
-
const offsetVal = offsetRaw !== null ? (offsetRaw === '?' ? Number(pList.shift() || 0) : Number(offsetRaw)) : 0;
|
|
8676
|
-
outputRows = outputRows.slice(offsetVal, offsetVal + limitVal);
|
|
8677
|
-
}
|
|
8678
|
-
|
|
8679
|
-
return outputRows;
|
|
8680
|
-
}
|
|
8681
|
-
}
|
|
8682
|
-
|
|
8683
|
-
function crc32Hash(str) {
|
|
8684
|
-
return VirtualZlib.crc32( typeof str === 'string' || str instanceof Uint8Array ? str : String(str) );
|
|
8685
|
-
}
|
|
8686
|
-
|
|
8687
|
-
const bunHashFn = function hash(val) {
|
|
8688
|
-
return crc32Hash(val);
|
|
8689
|
-
};
|
|
8690
|
-
bunHashFn.crc32 = (val) => crc32Hash(val);
|
|
8691
|
-
bunHashFn.cityHash64 = (val) => {
|
|
8692
|
-
const h1 = crc32Hash(val);
|
|
8693
|
-
const h2 = crc32Hash(String(val) + ':seed64');
|
|
8694
|
-
return (BigInt(h1) << 32n) | BigInt(h2);
|
|
8695
|
-
};
|
|
8696
|
-
|
|
8697
|
-
function deepEquals(a, b) {
|
|
8698
|
-
return isDeepEqual(a, b, true);
|
|
8699
|
-
}
|
|
8700
|
-
|
|
8701
|
-
const BunObj = {
|
|
8702
|
-
version: '1.1.0',
|
|
8703
|
-
serve(opts = {}) {
|
|
8704
|
-
const port = Number(opts.port || 3000);
|
|
8705
|
-
const hostname = opts.hostname || '127.0.0.1';
|
|
8706
|
-
const serverObj = {
|
|
8707
|
-
port,
|
|
8708
|
-
hostname,
|
|
8709
|
-
development: false,
|
|
8710
|
-
stop() {
|
|
8711
|
-
activePortTable.unregisterServer(port);
|
|
8712
|
-
}
|
|
8713
|
-
};
|
|
8714
|
-
activePortTable.registerServer(port, {
|
|
8715
|
-
server: serverObj,
|
|
8716
|
-
name: opts.name || 'bun-server',
|
|
8717
|
-
port,
|
|
8718
|
-
pid: resourceTracker.pid || 1,
|
|
8719
|
-
fetch: opts.fetch ? opts.fetch.bind(serverObj) : undefined,
|
|
8720
|
-
stop: () => serverObj.stop()
|
|
8721
|
-
});
|
|
8722
|
-
return serverObj;
|
|
8723
|
-
},
|
|
8724
|
-
file(p) {
|
|
8725
|
-
const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(p));
|
|
8726
|
-
return {
|
|
8727
|
-
name: VirtualPath.basename(resolved),
|
|
8728
|
-
get size() {
|
|
8729
|
-
try {
|
|
8730
|
-
return vfs.statSync(resolved).size;
|
|
8731
|
-
} catch (_) {
|
|
8732
|
-
return 0;
|
|
8733
|
-
}
|
|
8734
|
-
},
|
|
8735
|
-
async exists() {
|
|
8736
|
-
return vfs.existsSync(resolved);
|
|
8737
|
-
},
|
|
8738
|
-
async text() {
|
|
8739
|
-
return vfs.readFileSync(resolved, 'utf8');
|
|
8740
|
-
},
|
|
8741
|
-
async json() {
|
|
8742
|
-
return JSON.parse(vfs.readFileSync(resolved, 'utf8'));
|
|
8743
|
-
},
|
|
8744
|
-
async arrayBuffer() {
|
|
8745
|
-
const buf = vfs.readFileSync(resolved);
|
|
8746
|
-
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
8747
|
-
}
|
|
8748
|
-
};
|
|
8749
|
-
},
|
|
8750
|
-
async write(dest, data) {
|
|
8751
|
-
const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(dest));
|
|
8752
|
-
const dir = VirtualPath.dirname(resolved);
|
|
8753
|
-
if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
|
|
8754
|
-
let buf;
|
|
8755
|
-
if (typeof data === 'string') {
|
|
8756
|
-
buf = VirtualBuffer.from(data, 'utf8');
|
|
8757
|
-
} else if (data && data.arrayBuffer && typeof data.arrayBuffer === 'function') {
|
|
8758
|
-
const ab = await data.arrayBuffer();
|
|
8759
|
-
buf = VirtualBuffer.from(ab);
|
|
8760
|
-
} else if (data instanceof Uint8Array || VirtualBuffer.isBuffer(data)) {
|
|
8761
|
-
buf = VirtualBuffer.from(data);
|
|
8762
|
-
} else {
|
|
8763
|
-
buf = VirtualBuffer.from(String(data), 'utf8');
|
|
8764
|
-
}
|
|
8765
|
-
vfs.writeFileSync(resolved, buf);
|
|
8766
|
-
return buf.length;
|
|
8767
|
-
},
|
|
8768
|
-
sleep(ms) {
|
|
8769
|
-
return new Promise(resolve => sandboxSetTimeout(resolve, Number(ms) || 0));
|
|
8770
|
-
},
|
|
8771
|
-
hash: bunHashFn,
|
|
8772
|
-
deepEquals,
|
|
8773
|
-
inspect(val) {
|
|
8774
|
-
return VirtualUtil.inspect(val);
|
|
8775
|
-
},
|
|
8776
|
-
nanoseconds() {
|
|
8777
|
-
return Math.round(performance.now() * 1e6);
|
|
8778
|
-
}
|
|
8779
|
-
};
|
|
8780
|
-
|
|
8781
|
-
const bunTestModule = (() => {
|
|
8782
|
-
function makeExpect(actual, isNot = false) {
|
|
8783
|
-
const pass = (condition, msg) => {
|
|
8784
|
-
const ok = isNot ? !condition : condition;
|
|
8785
|
-
if (!ok) {
|
|
8786
|
-
throw new Error(msg || `expect assertion failed: actual=${actual}`);
|
|
8787
|
-
}
|
|
8788
|
-
};
|
|
8697
|
+
const bunTestModule = (() => {
|
|
8698
|
+
function makeExpect(actual, isNot = false) {
|
|
8699
|
+
const pass = (condition, msg) => {
|
|
8700
|
+
const ok = isNot ? !condition : condition;
|
|
8701
|
+
if (!ok) {
|
|
8702
|
+
throw new Error(msg || `expect assertion failed: actual=${actual}`);
|
|
8703
|
+
}
|
|
8704
|
+
};
|
|
8789
8705
|
|
|
8790
8706
|
const matchers = {
|
|
8791
8707
|
toBe(expected) {
|
|
@@ -9432,14 +9348,25 @@ function __initVirtualRuntime(rootScope) {
|
|
|
9432
9348
|
urlStr = String(urlOrReq);
|
|
9433
9349
|
}
|
|
9434
9350
|
|
|
9351
|
+
let parsedLocal = null;
|
|
9435
9352
|
try {
|
|
9436
9353
|
const parsed = new URL(urlStr);
|
|
9437
9354
|
const isLocal = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '0.0.0.0';
|
|
9438
|
-
if (isLocal
|
|
9439
|
-
return await activePortTable.dispatchRequest(urlStr, finalInit);
|
|
9440
|
-
}
|
|
9355
|
+
if (isLocal) parsedLocal = parsed;
|
|
9441
9356
|
} catch (err) {
|
|
9442
|
-
_runtimeLogger.debug('virtualFetch local URL
|
|
9357
|
+
_runtimeLogger.debug('virtualFetch local URL parse skipped', err);
|
|
9358
|
+
}
|
|
9359
|
+
|
|
9360
|
+
if (parsedLocal && activePortTable) {
|
|
9361
|
+
let dispatchInit = finalInit;
|
|
9362
|
+
if (!dispatchInit._fromPort && resourceTracker && resourceTracker.pid && typeof activePortTable.listServers === 'function') {
|
|
9363
|
+
const targetPort = Number(parsedLocal.port || (parsedLocal.protocol === 'https:' ? 443 : 80));
|
|
9364
|
+
const owned = activePortTable.listServers().find((s) => s && s.pid === resourceTracker.pid && Number(s.port) !== targetPort);
|
|
9365
|
+
if (owned) {
|
|
9366
|
+
dispatchInit = Object.assign({}, finalInit, { _fromPort: owned.port });
|
|
9367
|
+
}
|
|
9368
|
+
}
|
|
9369
|
+
return await activePortTable.dispatchRequest(urlStr, dispatchInit);
|
|
9443
9370
|
}
|
|
9444
9371
|
|
|
9445
9372
|
if (typeof globalThis.fetch === 'function') {
|
|
@@ -9867,12 +9794,647 @@ function __initVirtualRuntime(rootScope) {
|
|
|
9867
9794
|
};
|
|
9868
9795
|
}
|
|
9869
9796
|
|
|
9870
|
-
// Transpile a source file so it can run natively in a browser as an ES module:
|
|
9871
|
-
// JSX is compiled to the classic runtime (auto-importing React when needed) and
|
|
9872
|
-
// TypeScript annotations are stripped, but `import`/`export` are preserved so an
|
|
9873
|
-
// import map can resolve bare specifiers to CDN ESM builds.
|
|
9874
|
-
function transpileForBrowser(source, filename = 'module.js') {
|
|
9875
|
-
return transpileTS(source, filename, { keepEsm: true });
|
|
9797
|
+
// Transpile a source file so it can run natively in a browser as an ES module:
|
|
9798
|
+
// JSX is compiled to the classic runtime (auto-importing React when needed) and
|
|
9799
|
+
// TypeScript annotations are stripped, but `import`/`export` are preserved so an
|
|
9800
|
+
// import map can resolve bare specifiers to CDN ESM builds.
|
|
9801
|
+
function transpileForBrowser(source, filename = 'module.js') {
|
|
9802
|
+
return transpileTS(source, filename, { keepEsm: true });
|
|
9803
|
+
}
|
|
9804
|
+
|
|
9805
|
+
function createSqliteDatabase(vfs = null, getCwd = null) {
|
|
9806
|
+
function stripSqlComments(sql) {
|
|
9807
|
+
return String(sql || '')
|
|
9808
|
+
.replace(/\/\*[\s\S]*?\*\//g, ' ')
|
|
9809
|
+
.replace(/--[^\r\n]*/g, ' ')
|
|
9810
|
+
.trim();
|
|
9811
|
+
}
|
|
9812
|
+
|
|
9813
|
+
function splitValueTuples(rawValues) {
|
|
9814
|
+
const tuples = [];
|
|
9815
|
+
let depth = 0;
|
|
9816
|
+
let inQuote = null;
|
|
9817
|
+
let start = -1;
|
|
9818
|
+
for (let i = 0; i < rawValues.length; i++) {
|
|
9819
|
+
const ch = rawValues[i];
|
|
9820
|
+
if (inQuote) {
|
|
9821
|
+
if (ch === inQuote && rawValues[i - 1] !== '\\') inQuote = null;
|
|
9822
|
+
continue;
|
|
9823
|
+
}
|
|
9824
|
+
if (ch === "'" || ch === '"') {
|
|
9825
|
+
inQuote = ch;
|
|
9826
|
+
} else if (ch === '(') {
|
|
9827
|
+
if (depth === 0) start = i + 1;
|
|
9828
|
+
depth++;
|
|
9829
|
+
} else if (ch === ')') {
|
|
9830
|
+
depth--;
|
|
9831
|
+
if (depth === 0 && start !== -1) {
|
|
9832
|
+
tuples.push(rawValues.slice(start, i));
|
|
9833
|
+
start = -1;
|
|
9834
|
+
}
|
|
9835
|
+
}
|
|
9836
|
+
}
|
|
9837
|
+
return tuples;
|
|
9838
|
+
}
|
|
9839
|
+
|
|
9840
|
+
function splitCsvRespectingQuotes(str) {
|
|
9841
|
+
const out = [];
|
|
9842
|
+
let cur = '';
|
|
9843
|
+
let inQuote = null;
|
|
9844
|
+
let depth = 0;
|
|
9845
|
+
for (let i = 0; i < str.length; i++) {
|
|
9846
|
+
const ch = str[i];
|
|
9847
|
+
if (inQuote) {
|
|
9848
|
+
cur += ch;
|
|
9849
|
+
if (ch === inQuote && str[i - 1] !== '\\') inQuote = null;
|
|
9850
|
+
continue;
|
|
9851
|
+
}
|
|
9852
|
+
if (ch === "'" || ch === '"') {
|
|
9853
|
+
inQuote = ch;
|
|
9854
|
+
cur += ch;
|
|
9855
|
+
} else if (ch === '(') {
|
|
9856
|
+
depth++;
|
|
9857
|
+
cur += ch;
|
|
9858
|
+
} else if (ch === ')') {
|
|
9859
|
+
depth = Math.max(0, depth - 1);
|
|
9860
|
+
cur += ch;
|
|
9861
|
+
} else if (ch === ',' && depth === 0) {
|
|
9862
|
+
out.push(cur.trim());
|
|
9863
|
+
cur = '';
|
|
9864
|
+
} else {
|
|
9865
|
+
cur += ch;
|
|
9866
|
+
}
|
|
9867
|
+
}
|
|
9868
|
+
if (cur.trim()) out.push(cur.trim());
|
|
9869
|
+
return out;
|
|
9870
|
+
}
|
|
9871
|
+
|
|
9872
|
+
return class SqliteDatabase {
|
|
9873
|
+
constructor(filename = ':memory:') {
|
|
9874
|
+
this.filename = filename || ':memory:';
|
|
9875
|
+
this.tables = new Map();
|
|
9876
|
+
this.indexes = new Map();
|
|
9877
|
+
this._loadFromVfs();
|
|
9878
|
+
}
|
|
9879
|
+
|
|
9880
|
+
_resolveDbPath() {
|
|
9881
|
+
if (!this.filename || this.filename === ':memory:') return null;
|
|
9882
|
+
const cwd = typeof getCwd === 'function' ? getCwd() : '/workspace';
|
|
9883
|
+
return VirtualPath.resolve(cwd || '/workspace', String(this.filename));
|
|
9884
|
+
}
|
|
9885
|
+
|
|
9886
|
+
_loadFromVfs() {
|
|
9887
|
+
const p = this._resolveDbPath();
|
|
9888
|
+
if (!p || !vfs || typeof vfs.existsSync !== 'function' || !vfs.existsSync(p)) return;
|
|
9889
|
+
try {
|
|
9890
|
+
const raw = vfs.readFileSync(p, 'utf8');
|
|
9891
|
+
const trimmed = String(raw || '').trim();
|
|
9892
|
+
if (!trimmed) return;
|
|
9893
|
+
if (trimmed.startsWith('{')) {
|
|
9894
|
+
const parsed = JSON.parse(trimmed);
|
|
9895
|
+
if (parsed && parsed.__codelab_sqlite__) {
|
|
9896
|
+
if (parsed.tables && typeof parsed.tables === 'object') {
|
|
9897
|
+
for (const [tName, tVal] of Object.entries(parsed.tables)) {
|
|
9898
|
+
this.tables.set(tName, tVal);
|
|
9899
|
+
}
|
|
9900
|
+
}
|
|
9901
|
+
if (parsed.indexes && typeof parsed.indexes === 'object') {
|
|
9902
|
+
for (const [iName, iVal] of Object.entries(parsed.indexes)) {
|
|
9903
|
+
this.indexes.set(iName, iVal);
|
|
9904
|
+
}
|
|
9905
|
+
}
|
|
9906
|
+
return;
|
|
9907
|
+
}
|
|
9908
|
+
}
|
|
9909
|
+
this.exec(trimmed);
|
|
9910
|
+
} catch (err) {
|
|
9911
|
+
_runtimeLogger.debug('SqliteDatabase._loadFromVfs skipped', err);
|
|
9912
|
+
}
|
|
9913
|
+
}
|
|
9914
|
+
|
|
9915
|
+
_persistToVfs() {
|
|
9916
|
+
const p = this._resolveDbPath();
|
|
9917
|
+
if (!p || !vfs || typeof vfs.writeFileSync !== 'function') return;
|
|
9918
|
+
try {
|
|
9919
|
+
const dir = VirtualPath.dirname(p);
|
|
9920
|
+
if (typeof vfs.existsSync === 'function' && !vfs.existsSync(dir) && typeof vfs.mkdirSync === 'function') {
|
|
9921
|
+
vfs.mkdirSync(dir, { recursive: true });
|
|
9922
|
+
}
|
|
9923
|
+
const payload = JSON.stringify({
|
|
9924
|
+
__codelab_sqlite__: 1,
|
|
9925
|
+
tables: Object.fromEntries(this.tables),
|
|
9926
|
+
indexes: Object.fromEntries(this.indexes)
|
|
9927
|
+
});
|
|
9928
|
+
vfs.writeFileSync(p, payload);
|
|
9929
|
+
} catch (err) {
|
|
9930
|
+
_runtimeLogger.debug('SqliteDatabase._persistToVfs failed', err);
|
|
9931
|
+
}
|
|
9932
|
+
}
|
|
9933
|
+
|
|
9934
|
+
run(sql, params = []) {
|
|
9935
|
+
const stmt = stripSqlComments(sql).replace(/;$/, '').trim();
|
|
9936
|
+
if (!stmt) return { changes: 0, lastInsertRowid: 0 };
|
|
9937
|
+
|
|
9938
|
+
if (/^CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TABLE/i.test(stmt)) {
|
|
9939
|
+
const match = stmt.match(/^CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s*\(([\s\S]*)\)/i);
|
|
9940
|
+
if (match) {
|
|
9941
|
+
const tableName = match[1];
|
|
9942
|
+
const colDefs = splitCsvRespectingQuotes(match[2]);
|
|
9943
|
+
const cols = [];
|
|
9944
|
+
for (const c of colDefs) {
|
|
9945
|
+
if (/^(PRIMARY\s+KEY|FOREIGN\s+KEY|CONSTRAINT|UNIQUE|CHECK)\b/i.test(c)) continue;
|
|
9946
|
+
const parts = c.split(/\s+/);
|
|
9947
|
+
const colName = parts[0].replace(/^["'`]|["'`]$/g, '');
|
|
9948
|
+
const isPk = /PRIMARY\s+KEY/i.test(c);
|
|
9949
|
+
const isAuto = /AUTOINCREMENT/i.test(c) || (/INTEGER/i.test(parts[1] || '') && isPk);
|
|
9950
|
+
cols.push({ name: colName, type: parts[1] || 'TEXT', isPk, isAuto, raw: c });
|
|
9951
|
+
}
|
|
9952
|
+
if (!this.tables.has(tableName)) {
|
|
9953
|
+
this.tables.set(tableName, { columns: cols, rows: [], autoInc: 0, sql: stmt });
|
|
9954
|
+
this._persistToVfs();
|
|
9955
|
+
}
|
|
9956
|
+
}
|
|
9957
|
+
return { changes: 0, lastInsertRowid: 0 };
|
|
9958
|
+
}
|
|
9959
|
+
|
|
9960
|
+
if (/^DROP\s+TABLE/i.test(stmt)) {
|
|
9961
|
+
const match = stmt.match(/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);
|
|
9962
|
+
if (match) {
|
|
9963
|
+
this.tables.delete(match[1]);
|
|
9964
|
+
this._persistToVfs();
|
|
9965
|
+
}
|
|
9966
|
+
return { changes: 0, lastInsertRowid: 0 };
|
|
9967
|
+
}
|
|
9968
|
+
|
|
9969
|
+
if (/^CREATE\s+(?:UNIQUE\s+)?INDEX/i.test(stmt)) {
|
|
9970
|
+
const match = stmt.match(/^CREATE\s+(UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s+ON\s+([a-zA-Z0-9_]+)\s*\(([^)]+)\)/i);
|
|
9971
|
+
if (match) {
|
|
9972
|
+
const unique = Boolean(match[1]);
|
|
9973
|
+
const idxName = match[2];
|
|
9974
|
+
const tblName = match[3];
|
|
9975
|
+
const cols = match[4].split(',').map((s) => s.trim().split(/\s+/)[0]);
|
|
9976
|
+
this.indexes.set(idxName, { name: idxName, table: tblName, columns: cols, unique, sql: stmt });
|
|
9977
|
+
this._persistToVfs();
|
|
9978
|
+
}
|
|
9979
|
+
return { changes: 0, lastInsertRowid: 0 };
|
|
9980
|
+
}
|
|
9981
|
+
|
|
9982
|
+
if (/^DROP\s+INDEX/i.test(stmt)) {
|
|
9983
|
+
const match = stmt.match(/^DROP\s+INDEX\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);
|
|
9984
|
+
if (match) {
|
|
9985
|
+
this.indexes.delete(match[1]);
|
|
9986
|
+
this._persistToVfs();
|
|
9987
|
+
}
|
|
9988
|
+
return { changes: 0, lastInsertRowid: 0 };
|
|
9989
|
+
}
|
|
9990
|
+
|
|
9991
|
+
if (/^ALTER\s+TABLE/i.test(stmt)) {
|
|
9992
|
+
const match = stmt.match(/^ALTER\s+TABLE\s+([a-zA-Z0-9_]+)\s+ADD\s+(?:COLUMN\s+)?([a-zA-Z0-9_]+)\s*(.*)$/i);
|
|
9993
|
+
if (match) {
|
|
9994
|
+
const table = this.tables.get(match[1]);
|
|
9995
|
+
if (table) {
|
|
9996
|
+
const colName = match[2];
|
|
9997
|
+
const colType = (match[3] || 'TEXT').split(/\s+/)[0] || 'TEXT';
|
|
9998
|
+
table.columns.push({ name: colName, type: colType, isPk: false, isAuto: false });
|
|
9999
|
+
this._persistToVfs();
|
|
10000
|
+
}
|
|
10001
|
+
}
|
|
10002
|
+
return { changes: 0, lastInsertRowid: 0 };
|
|
10003
|
+
}
|
|
10004
|
+
|
|
10005
|
+
if (/^PRAGMA\s+/i.test(stmt)) {
|
|
10006
|
+
return { changes: 0, lastInsertRowid: 0 };
|
|
10007
|
+
}
|
|
10008
|
+
|
|
10009
|
+
if (/^INSERT\s+(?:OR\s+(?:REPLACE|IGNORE)\s+)?INTO/i.test(stmt)) {
|
|
10010
|
+
const match = stmt.match(/^INSERT\s+(?:OR\s+(REPLACE|IGNORE)\s+)?INTO\s+([a-zA-Z0-9_]+)(?:\s*\(([^)]+)\))?\s*VALUES\s*([\s\S]*)$/i);
|
|
10011
|
+
if (match) {
|
|
10012
|
+
const conflictMode = (match[1] || '').toUpperCase();
|
|
10013
|
+
const tableName = match[2];
|
|
10014
|
+
const table = this.tables.get(tableName);
|
|
10015
|
+
if (!table) throw new Error(`no such table: ${tableName}`);
|
|
10016
|
+
const explicitCols = match[3] ? match[3].split(',').map((s) => s.trim()) : null;
|
|
10017
|
+
const tuples = splitValueTuples(match[4]);
|
|
10018
|
+
const pList = Array.isArray(params) ? [...params] : [params];
|
|
10019
|
+
let insertedCount = 0;
|
|
10020
|
+
|
|
10021
|
+
for (const tupleStr of (tuples.length > 0 ? tuples : [match[4].replace(/^\(|\)$/g, '')])) {
|
|
10022
|
+
const valExprs = splitCsvRespectingQuotes(tupleStr);
|
|
10023
|
+
const colNames = explicitCols
|
|
10024
|
+
? explicitCols
|
|
10025
|
+
: (valExprs.length === table.columns.length
|
|
10026
|
+
? table.columns.map((c) => c.name)
|
|
10027
|
+
: table.columns.filter((c) => !c.isPk).map((c) => c.name));
|
|
10028
|
+
const row = {};
|
|
10029
|
+
const pkCol = table.columns.find((c) => c.isPk);
|
|
10030
|
+
|
|
10031
|
+
for (let i = 0; i < colNames.length; i++) {
|
|
10032
|
+
const cName = colNames[i];
|
|
10033
|
+
const expr = valExprs[i] !== undefined ? valExprs[i] : '?';
|
|
10034
|
+
if (expr === '?') {
|
|
10035
|
+
row[cName] = pList.shift();
|
|
10036
|
+
} else if (/^['"][\s\S]*['"]$/.test(expr)) {
|
|
10037
|
+
row[cName] = expr.slice(1, -1).replace(/''/g, "'");
|
|
10038
|
+
} else if (/^null$/i.test(expr)) {
|
|
10039
|
+
row[cName] = null;
|
|
10040
|
+
} else if (!isNaN(Number(expr))) {
|
|
10041
|
+
row[cName] = Number(expr);
|
|
10042
|
+
} else {
|
|
10043
|
+
row[cName] = expr;
|
|
10044
|
+
}
|
|
10045
|
+
}
|
|
10046
|
+
|
|
10047
|
+
if (pkCol) {
|
|
10048
|
+
if (row[pkCol.name] === undefined || row[pkCol.name] === null) {
|
|
10049
|
+
table.autoInc++;
|
|
10050
|
+
row[pkCol.name] = table.autoInc;
|
|
10051
|
+
} else if (typeof row[pkCol.name] === 'number' && row[pkCol.name] > table.autoInc) {
|
|
10052
|
+
table.autoInc = row[pkCol.name];
|
|
10053
|
+
}
|
|
10054
|
+
const existingIdx = table.rows.findIndex((r) => String(r[pkCol.name]) === String(row[pkCol.name]));
|
|
10055
|
+
if (existingIdx !== -1) {
|
|
10056
|
+
if (conflictMode === 'IGNORE') continue;
|
|
10057
|
+
if (conflictMode === 'REPLACE') {
|
|
10058
|
+
table.rows[existingIdx] = row;
|
|
10059
|
+
insertedCount++;
|
|
10060
|
+
continue;
|
|
10061
|
+
}
|
|
10062
|
+
}
|
|
10063
|
+
} else {
|
|
10064
|
+
table.autoInc++;
|
|
10065
|
+
}
|
|
10066
|
+
|
|
10067
|
+
table.rows.push(row);
|
|
10068
|
+
insertedCount++;
|
|
10069
|
+
}
|
|
10070
|
+
this._persistToVfs();
|
|
10071
|
+
return { changes: insertedCount, lastInsertRowid: table.autoInc };
|
|
10072
|
+
}
|
|
10073
|
+
}
|
|
10074
|
+
|
|
10075
|
+
if (/^DELETE\s+FROM/i.test(stmt)) {
|
|
10076
|
+
const match = stmt.match(/^DELETE\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*))?$/i);
|
|
10077
|
+
if (match) {
|
|
10078
|
+
const table = this.tables.get(match[1]);
|
|
10079
|
+
if (!table) throw new Error(`no such table: ${match[1]}`);
|
|
10080
|
+
const whereClause = match[2] ? match[2].trim() : null;
|
|
10081
|
+
const pList = Array.isArray(params) ? [...params] : [params];
|
|
10082
|
+
const beforeLen = table.rows.length;
|
|
10083
|
+
if (!whereClause) {
|
|
10084
|
+
table.rows = [];
|
|
10085
|
+
} else {
|
|
10086
|
+
table.rows = table.rows.filter((r) => !this._matchWhere(r, whereClause, [...pList]));
|
|
10087
|
+
}
|
|
10088
|
+
this._persistToVfs();
|
|
10089
|
+
return { changes: beforeLen - table.rows.length, lastInsertRowid: table.autoInc };
|
|
10090
|
+
}
|
|
10091
|
+
}
|
|
10092
|
+
|
|
10093
|
+
if (/^UPDATE\s+/i.test(stmt)) {
|
|
10094
|
+
const match = stmt.match(/^UPDATE\s+([a-zA-Z0-9_]+)\s+SET\s+([\s\S]*?)(?:\s+WHERE\s+([\s\S]*))?$/i);
|
|
10095
|
+
if (match) {
|
|
10096
|
+
const table = this.tables.get(match[1]);
|
|
10097
|
+
if (!table) throw new Error(`no such table: ${match[1]}`);
|
|
10098
|
+
const setParts = splitCsvRespectingQuotes(match[2]);
|
|
10099
|
+
const whereClause = match[3] ? match[3].trim() : null;
|
|
10100
|
+
const pList = Array.isArray(params) ? [...params] : [params];
|
|
10101
|
+
let changes = 0;
|
|
10102
|
+
for (const row of table.rows) {
|
|
10103
|
+
const rowParams = [...pList];
|
|
10104
|
+
const setUpdates = [];
|
|
10105
|
+
for (const sp of setParts) {
|
|
10106
|
+
const eqIdx = sp.indexOf('=');
|
|
10107
|
+
const col = sp.slice(0, eqIdx).trim();
|
|
10108
|
+
const valExpr = sp.slice(eqIdx + 1).trim();
|
|
10109
|
+
const val = valExpr === '?'
|
|
10110
|
+
? rowParams.shift()
|
|
10111
|
+
: (/^['"][\s\S]*['"]$/.test(valExpr)
|
|
10112
|
+
? valExpr.slice(1, -1)
|
|
10113
|
+
: (!isNaN(Number(valExpr)) ? Number(valExpr) : valExpr));
|
|
10114
|
+
setUpdates.push([col, val]);
|
|
10115
|
+
}
|
|
10116
|
+
if (!whereClause || this._matchWhere(row, whereClause, rowParams)) {
|
|
10117
|
+
for (const [col, val] of setUpdates) row[col] = val;
|
|
10118
|
+
changes++;
|
|
10119
|
+
}
|
|
10120
|
+
}
|
|
10121
|
+
this._persistToVfs();
|
|
10122
|
+
return { changes, lastInsertRowid: table.autoInc };
|
|
10123
|
+
}
|
|
10124
|
+
}
|
|
10125
|
+
|
|
10126
|
+
return { changes: 0, lastInsertRowid: 0 };
|
|
10127
|
+
}
|
|
10128
|
+
|
|
10129
|
+
_matchWhere(row, whereClause, pList) {
|
|
10130
|
+
if (!whereClause) return true;
|
|
10131
|
+
const andParts = whereClause.split(/\s+AND\s+/i);
|
|
10132
|
+
for (const part of andParts) {
|
|
10133
|
+
const trimmed = part.trim();
|
|
10134
|
+
const isNullMatch = trimmed.match(/^([a-zA-Z0-9_]+)\s+IS\s+(NOT\s+)?NULL$/i);
|
|
10135
|
+
if (isNullMatch) {
|
|
10136
|
+
const col = isNullMatch[1];
|
|
10137
|
+
const isNot = Boolean(isNullMatch[2]);
|
|
10138
|
+
const isNull = row[col] === null || row[col] === undefined;
|
|
10139
|
+
if (isNot ? isNull : !isNull) return false;
|
|
10140
|
+
continue;
|
|
10141
|
+
}
|
|
10142
|
+
const likeMatch = trimmed.match(/^([a-zA-Z0-9_]+)\s+LIKE\s+(.+)$/i);
|
|
10143
|
+
if (likeMatch) {
|
|
10144
|
+
const col = likeMatch[1];
|
|
10145
|
+
let pat = likeMatch[2].trim();
|
|
10146
|
+
if (pat === '?') pat = String(pList.shift() || '');
|
|
10147
|
+
else if (/^['"].*['"]$/.test(pat)) pat = pat.slice(1, -1);
|
|
10148
|
+
const re = new RegExp('^' + pat.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/%/g, '.*').replace(/_/g, '.') + '$', 'i');
|
|
10149
|
+
if (!re.test(String(row[col] ?? ''))) return false;
|
|
10150
|
+
continue;
|
|
10151
|
+
}
|
|
10152
|
+
const eqMatch = trimmed.match(/^([a-zA-Z0-9_]+)\s*(=|!=|<>|>=|<=|>|<)\s*(.*)$/);
|
|
10153
|
+
if (eqMatch) {
|
|
10154
|
+
const col = eqMatch[1].trim();
|
|
10155
|
+
const op = eqMatch[2];
|
|
10156
|
+
let expected = eqMatch[3].trim();
|
|
10157
|
+
if (expected === '?') {
|
|
10158
|
+
expected = pList.shift();
|
|
10159
|
+
} else if (/^['"].*['"]$/.test(expected)) {
|
|
10160
|
+
expected = expected.slice(1, -1);
|
|
10161
|
+
} else if (!isNaN(Number(expected))) {
|
|
10162
|
+
expected = Number(expected);
|
|
10163
|
+
}
|
|
10164
|
+
const actual = row[col];
|
|
10165
|
+
let ok = true;
|
|
10166
|
+
if (op === '=') ok = String(actual) === String(expected);
|
|
10167
|
+
else if (op === '!=' || op === '<>') ok = String(actual) !== String(expected);
|
|
10168
|
+
else if (op === '>') ok = Number(actual) > Number(expected);
|
|
10169
|
+
else if (op === '<') ok = Number(actual) < Number(expected);
|
|
10170
|
+
else if (op === '>=') ok = Number(actual) >= Number(expected);
|
|
10171
|
+
else if (op === '<=') ok = Number(actual) <= Number(expected);
|
|
10172
|
+
if (!ok) return false;
|
|
10173
|
+
}
|
|
10174
|
+
}
|
|
10175
|
+
return true;
|
|
10176
|
+
}
|
|
10177
|
+
|
|
10178
|
+
exec(sql) {
|
|
10179
|
+
const cleaned = stripSqlComments(sql);
|
|
10180
|
+
const statements = cleaned.split(';').map((s) => s.trim()).filter(Boolean);
|
|
10181
|
+
for (const s of statements) {
|
|
10182
|
+
this.run(s);
|
|
10183
|
+
}
|
|
10184
|
+
}
|
|
10185
|
+
|
|
10186
|
+
transaction(fn) {
|
|
10187
|
+
return (...args) => fn(...args);
|
|
10188
|
+
}
|
|
10189
|
+
|
|
10190
|
+
close() {
|
|
10191
|
+
this._persistToVfs();
|
|
10192
|
+
}
|
|
10193
|
+
|
|
10194
|
+
query(sql) {
|
|
10195
|
+
const db = this;
|
|
10196
|
+
return {
|
|
10197
|
+
all(...args) {
|
|
10198
|
+
let params = args;
|
|
10199
|
+
if (args.length === 1 && Array.isArray(args[0])) params = args[0];
|
|
10200
|
+
return db._executeSelect(sql, params);
|
|
10201
|
+
},
|
|
10202
|
+
get(...args) {
|
|
10203
|
+
const rows = this.all(...args);
|
|
10204
|
+
return rows[0] || null;
|
|
10205
|
+
},
|
|
10206
|
+
values(...args) {
|
|
10207
|
+
const rows = this.all(...args);
|
|
10208
|
+
return rows.map((r) => Object.values(r));
|
|
10209
|
+
},
|
|
10210
|
+
run(...args) {
|
|
10211
|
+
let params = args;
|
|
10212
|
+
if (args.length === 1 && Array.isArray(args[0])) params = args[0];
|
|
10213
|
+
return db.run(sql, params);
|
|
10214
|
+
}
|
|
10215
|
+
};
|
|
10216
|
+
}
|
|
10217
|
+
|
|
10218
|
+
prepare(sql) {
|
|
10219
|
+
return this.query(sql);
|
|
10220
|
+
}
|
|
10221
|
+
|
|
10222
|
+
_evalAggregate(fn, aggCol, rows) {
|
|
10223
|
+
if (fn === 'COUNT') {
|
|
10224
|
+
if (aggCol === '*') return rows.length;
|
|
10225
|
+
return rows.filter((r) => r[aggCol] !== null && r[aggCol] !== undefined).length;
|
|
10226
|
+
}
|
|
10227
|
+
if (fn === 'AVG') {
|
|
10228
|
+
const sum = rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
|
|
10229
|
+
return rows.length > 0 ? sum / rows.length : 0;
|
|
10230
|
+
}
|
|
10231
|
+
if (fn === 'SUM') {
|
|
10232
|
+
return rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
|
|
10233
|
+
}
|
|
10234
|
+
if (fn === 'MIN') {
|
|
10235
|
+
return rows.length > 0 ? Math.min(...rows.map((r) => Number(r[aggCol]) || 0)) : null;
|
|
10236
|
+
}
|
|
10237
|
+
if (fn === 'MAX') {
|
|
10238
|
+
return rows.length > 0 ? Math.max(...rows.map((r) => Number(r[aggCol]) || 0)) : null;
|
|
10239
|
+
}
|
|
10240
|
+
return null;
|
|
10241
|
+
}
|
|
10242
|
+
|
|
10243
|
+
_executeSelect(sql, params = []) {
|
|
10244
|
+
const s = stripSqlComments(sql).replace(/;$/, '').trim();
|
|
10245
|
+
if (!s) return [];
|
|
10246
|
+
|
|
10247
|
+
if (/^EXPLAIN\s+QUERY\s+PLAN\s+/i.test(s)) {
|
|
10248
|
+
const inner = s.replace(/^EXPLAIN\s+QUERY\s+PLAN\s+/i, '').trim();
|
|
10249
|
+
const m = inner.match(/^SELECT\s+[\s\S]*?\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*?))?(?:\s+GROUP|\s+ORDER|\s+LIMIT|$)/i);
|
|
10250
|
+
if (m) {
|
|
10251
|
+
const tblName = m[1];
|
|
10252
|
+
const whereRaw = (m[2] || '').replace(/'[^']*'|"[^"]*"/g, '');
|
|
10253
|
+
const table = this.tables.get(tblName);
|
|
10254
|
+
const pkCol = table && table.columns.find((c) => c.isPk);
|
|
10255
|
+
if (pkCol && new RegExp(`\\b${pkCol.name}\\b`, 'i').test(whereRaw)) {
|
|
10256
|
+
return [{ id: 0, parent: 0, notused: 0, detail: `SEARCH ${tblName} USING INTEGER PRIMARY KEY (rowid=?)` }];
|
|
10257
|
+
}
|
|
10258
|
+
for (const idx of this.indexes.values()) {
|
|
10259
|
+
if (idx.table === tblName && idx.columns.some((c) => new RegExp(`\\b${c}\\b`, 'i').test(whereRaw))) {
|
|
10260
|
+
return [{ id: 0, parent: 0, notused: 0, detail: `SEARCH ${tblName} USING INDEX ${idx.name} (${idx.columns.join(',')}=?)` }];
|
|
10261
|
+
}
|
|
10262
|
+
}
|
|
10263
|
+
return [{ id: 0, parent: 0, notused: 0, detail: `SCAN ${tblName}` }];
|
|
10264
|
+
}
|
|
10265
|
+
return [{ id: 0, parent: 0, notused: 0, detail: 'SCAN' }];
|
|
10266
|
+
}
|
|
10267
|
+
|
|
10268
|
+
if (/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(s)) {
|
|
10269
|
+
const m = s.match(/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i);
|
|
10270
|
+
const tbl = m && this.tables.get(m[1]);
|
|
10271
|
+
if (!tbl) return [];
|
|
10272
|
+
return tbl.columns.map((c, idx) => ({
|
|
10273
|
+
cid: idx,
|
|
10274
|
+
name: c.name,
|
|
10275
|
+
type: c.type || 'TEXT',
|
|
10276
|
+
notnull: 0,
|
|
10277
|
+
dflt_value: null,
|
|
10278
|
+
pk: c.isPk ? 1 : 0
|
|
10279
|
+
}));
|
|
10280
|
+
}
|
|
10281
|
+
|
|
10282
|
+
if (/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(s)) {
|
|
10283
|
+
const m = s.match(/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i);
|
|
10284
|
+
const tblName = m ? m[1] : '';
|
|
10285
|
+
const out = [];
|
|
10286
|
+
let seq = 0;
|
|
10287
|
+
for (const idx of this.indexes.values()) {
|
|
10288
|
+
if (idx.table === tblName) {
|
|
10289
|
+
out.push({
|
|
10290
|
+
seq: seq++,
|
|
10291
|
+
name: idx.name,
|
|
10292
|
+
unique: idx.unique ? 1 : 0,
|
|
10293
|
+
origin: 'c',
|
|
10294
|
+
partial: 0
|
|
10295
|
+
});
|
|
10296
|
+
}
|
|
10297
|
+
}
|
|
10298
|
+
return out;
|
|
10299
|
+
}
|
|
10300
|
+
|
|
10301
|
+
if (/^(?:INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|PRAGMA)\b/i.test(s)) {
|
|
10302
|
+
this.run(s, params);
|
|
10303
|
+
return [];
|
|
10304
|
+
}
|
|
10305
|
+
|
|
10306
|
+
const match = s.match(/^SELECT\s+(?:DISTINCT\s+)?([\s\S]*?)\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*?))?(?:\s+GROUP\s+BY\s+([\s\S]*?))?(?:\s+ORDER\s+BY\s+([\s\S]*?))?(?:\s+LIMIT\s+(\d+|\?)(?:\s+OFFSET\s+(\d+|\?))?)?$/i);
|
|
10307
|
+
if (!match) {
|
|
10308
|
+
const noFromMatch = s.match(/^SELECT\s+([\s\S]+)$/i);
|
|
10309
|
+
if (noFromMatch) {
|
|
10310
|
+
const parts = splitCsvRespectingQuotes(noFromMatch[1]);
|
|
10311
|
+
const outRow = {};
|
|
10312
|
+
for (const p of parts) {
|
|
10313
|
+
const asMatch = p.match(/^([\s\S]*?)\s+AS\s+([a-zA-Z0-9_]+)$/i);
|
|
10314
|
+
const expr = (asMatch ? asMatch[1] : p).trim();
|
|
10315
|
+
const alias = (asMatch ? asMatch[2] : p).trim();
|
|
10316
|
+
if (/^sqlite_version\(\)$/i.test(expr)) outRow[alias] = '3.45.0';
|
|
10317
|
+
else if (/^['"].*['"]$/.test(expr)) outRow[alias] = expr.slice(1, -1);
|
|
10318
|
+
else if (!isNaN(Number(expr))) outRow[alias] = Number(expr);
|
|
10319
|
+
else outRow[alias] = expr;
|
|
10320
|
+
}
|
|
10321
|
+
return [outRow];
|
|
10322
|
+
}
|
|
10323
|
+
return [];
|
|
10324
|
+
}
|
|
10325
|
+
const selectColsRaw = match[1].trim();
|
|
10326
|
+
const tableName = match[2].trim();
|
|
10327
|
+
const whereClause = match[3] ? match[3].trim() : null;
|
|
10328
|
+
const groupByClause = match[4] ? match[4].trim() : null;
|
|
10329
|
+
const orderByClause = match[5] ? match[5].trim() : null;
|
|
10330
|
+
const limitRaw = match[6] ? match[6].trim() : null;
|
|
10331
|
+
const offsetRaw = match[7] ? match[7].trim() : null;
|
|
10332
|
+
|
|
10333
|
+
const table = this.tables.get(tableName);
|
|
10334
|
+
if (!table) return [];
|
|
10335
|
+
|
|
10336
|
+
const pList = Array.isArray(params) ? [...params] : [params];
|
|
10337
|
+
const filteredRows = table.rows.filter((row) => {
|
|
10338
|
+
const rowParams = [...pList];
|
|
10339
|
+
return this._matchWhere(row, whereClause, rowParams);
|
|
10340
|
+
});
|
|
10341
|
+
if (whereClause && whereClause.includes('?')) {
|
|
10342
|
+
const qCount = (whereClause.match(/\?/g) || []).length;
|
|
10343
|
+
pList.splice(0, qCount);
|
|
10344
|
+
}
|
|
10345
|
+
|
|
10346
|
+
const colSpecs = [];
|
|
10347
|
+
let hasAggregate = false;
|
|
10348
|
+
if (selectColsRaw !== '*') {
|
|
10349
|
+
const parts = splitCsvRespectingQuotes(selectColsRaw);
|
|
10350
|
+
for (const p of parts) {
|
|
10351
|
+
const asMatch = p.match(/^([\s\S]*?)\s+(?:AS\s+)?([a-zA-Z0-9_]+)$/i);
|
|
10352
|
+
const isFuncWithSpace = /^(AVG|SUM|COUNT|MIN|MAX)\s*\([^)]+\)$/i.test(p.trim());
|
|
10353
|
+
const spec = (asMatch && !isFuncWithSpace)
|
|
10354
|
+
? { expr: asMatch[1].trim(), alias: asMatch[2].trim() }
|
|
10355
|
+
: { expr: p.trim(), alias: p.trim() };
|
|
10356
|
+
if (/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i.test(spec.expr)) {
|
|
10357
|
+
hasAggregate = true;
|
|
10358
|
+
}
|
|
10359
|
+
colSpecs.push(spec);
|
|
10360
|
+
}
|
|
10361
|
+
}
|
|
10362
|
+
|
|
10363
|
+
let outputRows = [];
|
|
10364
|
+
if (groupByClause) {
|
|
10365
|
+
const groupCol = groupByClause.trim();
|
|
10366
|
+
const groups = new Map();
|
|
10367
|
+
for (const row of filteredRows) {
|
|
10368
|
+
const key = row[groupCol];
|
|
10369
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
10370
|
+
groups.get(key).push(row);
|
|
10371
|
+
}
|
|
10372
|
+
|
|
10373
|
+
for (const [key, rows] of groups.entries()) {
|
|
10374
|
+
const outRow = {};
|
|
10375
|
+
for (const col of colSpecs) {
|
|
10376
|
+
const expr = col.expr;
|
|
10377
|
+
const alias = col.alias;
|
|
10378
|
+
const aggMatch = expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i);
|
|
10379
|
+
if (aggMatch) {
|
|
10380
|
+
outRow[alias] = this._evalAggregate(aggMatch[1].toUpperCase(), aggMatch[2].trim(), rows);
|
|
10381
|
+
} else if (expr === groupCol) {
|
|
10382
|
+
outRow[alias] = key;
|
|
10383
|
+
} else {
|
|
10384
|
+
outRow[alias] = rows[0] ? rows[0][expr] : null;
|
|
10385
|
+
}
|
|
10386
|
+
}
|
|
10387
|
+
outputRows.push(outRow);
|
|
10388
|
+
}
|
|
10389
|
+
} else if (hasAggregate) {
|
|
10390
|
+
const outRow = {};
|
|
10391
|
+
for (const col of colSpecs) {
|
|
10392
|
+
const aggMatch = col.expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i);
|
|
10393
|
+
if (aggMatch) {
|
|
10394
|
+
outRow[col.alias] = this._evalAggregate(aggMatch[1].toUpperCase(), aggMatch[2].trim(), filteredRows);
|
|
10395
|
+
} else {
|
|
10396
|
+
outRow[col.alias] = filteredRows[0] ? filteredRows[0][col.expr] : null;
|
|
10397
|
+
}
|
|
10398
|
+
}
|
|
10399
|
+
outputRows.push(outRow);
|
|
10400
|
+
} else {
|
|
10401
|
+
for (const row of filteredRows) {
|
|
10402
|
+
if (selectColsRaw === '*') {
|
|
10403
|
+
outputRows.push(Object.assign({}, row));
|
|
10404
|
+
} else {
|
|
10405
|
+
const outRow = {};
|
|
10406
|
+
for (const col of colSpecs) {
|
|
10407
|
+
outRow[col.alias] = row[col.expr];
|
|
10408
|
+
}
|
|
10409
|
+
outputRows.push(outRow);
|
|
10410
|
+
}
|
|
10411
|
+
}
|
|
10412
|
+
}
|
|
10413
|
+
|
|
10414
|
+
if (orderByClause) {
|
|
10415
|
+
const parts = orderByClause.trim().split(/\s+/);
|
|
10416
|
+
const orderCol = parts[0];
|
|
10417
|
+
const desc = parts[1] && parts[1].toUpperCase() === 'DESC';
|
|
10418
|
+
outputRows.sort((a, b) => {
|
|
10419
|
+
const valA = a[orderCol];
|
|
10420
|
+
const valB = b[orderCol];
|
|
10421
|
+
if (valA === valB) return 0;
|
|
10422
|
+
if (valA === undefined) return 1;
|
|
10423
|
+
if (valB === undefined) return -1;
|
|
10424
|
+
const res = valA > valB ? 1 : -1;
|
|
10425
|
+
return desc ? -res : res;
|
|
10426
|
+
});
|
|
10427
|
+
}
|
|
10428
|
+
|
|
10429
|
+
if (limitRaw !== null) {
|
|
10430
|
+
const limitVal = limitRaw === '?' ? Number(pList.shift() || 0) : Number(limitRaw);
|
|
10431
|
+
const offsetVal = offsetRaw !== null ? (offsetRaw === '?' ? Number(pList.shift() || 0) : Number(offsetRaw)) : 0;
|
|
10432
|
+
outputRows = outputRows.slice(offsetVal, offsetVal + limitVal);
|
|
10433
|
+
}
|
|
10434
|
+
|
|
10435
|
+
return outputRows;
|
|
10436
|
+
}
|
|
10437
|
+
};
|
|
9876
10438
|
}
|
|
9877
10439
|
|
|
9878
10440
|
return {
|
|
@@ -9893,6 +10455,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
9893
10455
|
createVirtualFs,
|
|
9894
10456
|
createVirtualHttp,
|
|
9895
10457
|
createVirtualNet,
|
|
10458
|
+
createSqliteDatabase,
|
|
9896
10459
|
transpileTS,
|
|
9897
10460
|
transpileForBrowser,
|
|
9898
10461
|
preloadNpmPackages,
|
|
@@ -16113,6 +16676,9 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
16113
16676
|
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
16114
16677
|
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
16115
16678
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
16679
|
+
stdout += ' hey, ab, wrk Concurrent HTTP load generator & latency percentiles\n';
|
|
16680
|
+
stdout += ' chaos Network fault injection (delay, drop, error, partition, crash, heal)\n';
|
|
16681
|
+
stdout += ' sqlite3, redis-cli Interactive SQLite SQL engine & in-memory Redis data store CLI\n';
|
|
16116
16682
|
return { code: 0, stdout, stderr: '' };
|
|
16117
16683
|
},
|
|
16118
16684
|
|
|
@@ -16731,6 +17297,7 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
16731
17297
|
}
|
|
16732
17298
|
} catch (err) {
|
|
16733
17299
|
lastErr = err;
|
|
17300
|
+
if (err && err.chaosEffect) break;
|
|
16734
17301
|
await new Promise(r => setTimeout(r, 15));
|
|
16735
17302
|
}
|
|
16736
17303
|
}
|
|
@@ -16764,7 +17331,808 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
16764
17331
|
|
|
16765
17332
|
output += bodyText;
|
|
16766
17333
|
return { code: 0, stdout: output, stderr: '' };
|
|
17334
|
+
},
|
|
17335
|
+
|
|
17336
|
+
async hey(args, ctx) {
|
|
17337
|
+
let totalRequests = 50;
|
|
17338
|
+
let concurrency = 10;
|
|
17339
|
+
let method = 'GET';
|
|
17340
|
+
const headers = {};
|
|
17341
|
+
let body = null;
|
|
17342
|
+
let jsonOut = false;
|
|
17343
|
+
let url = '';
|
|
17344
|
+
|
|
17345
|
+
for (let i = 0; i < args.length; i++) {
|
|
17346
|
+
const a = args[i];
|
|
17347
|
+
if ((a === '-n' || a === '--requests') && i + 1 < args.length) {
|
|
17348
|
+
totalRequests = Math.max(1, Math.min(2000, parseInt(args[++i], 10) || 50));
|
|
17349
|
+
} else if ((a === '-c' || a === '--concurrency') && i + 1 < args.length) {
|
|
17350
|
+
concurrency = Math.max(1, Math.min(200, parseInt(args[++i], 10) || 10));
|
|
17351
|
+
} else if ((a === '-m' || a === '-X' || a === '--method') && i + 1 < args.length) {
|
|
17352
|
+
method = String(args[++i]).toUpperCase();
|
|
17353
|
+
} else if ((a === '-H' || a === '--header') && i + 1 < args.length) {
|
|
17354
|
+
const h = args[++i];
|
|
17355
|
+
const idx = h.indexOf(':');
|
|
17356
|
+
if (idx !== -1) headers[h.slice(0, idx).trim()] = h.slice(idx + 1).trim();
|
|
17357
|
+
} else if ((a === '-d' || a === '--body' || a === '--data') && i + 1 < args.length) {
|
|
17358
|
+
body = args[++i];
|
|
17359
|
+
if (method === 'GET') method = 'POST';
|
|
17360
|
+
} else if (a === '--json') {
|
|
17361
|
+
jsonOut = true;
|
|
17362
|
+
} else if (!a.startsWith('-')) {
|
|
17363
|
+
url = a;
|
|
17364
|
+
}
|
|
17365
|
+
}
|
|
17366
|
+
|
|
17367
|
+
if (!url) {
|
|
17368
|
+
return {
|
|
17369
|
+
code: 1,
|
|
17370
|
+
stdout: '',
|
|
17371
|
+
stderr: 'Usage: hey [-n requests] [-c concurrency] [-m METHOD] [-H "Header: val"] [-d body] [--json] <url>\n'
|
|
17372
|
+
};
|
|
17373
|
+
}
|
|
17374
|
+
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
|
17375
|
+
url = 'http://' + url;
|
|
17376
|
+
}
|
|
17377
|
+
concurrency = Math.min(concurrency, totalRequests);
|
|
17378
|
+
|
|
17379
|
+
const portTable = (ctx.shell && ctx.shell.portTable) || null;
|
|
17380
|
+
const latencies = [];
|
|
17381
|
+
const statusCounts = {};
|
|
17382
|
+
const errorCounts = {};
|
|
17383
|
+
let totalBytes = 0;
|
|
17384
|
+
let issued = 0;
|
|
17385
|
+
|
|
17386
|
+
const tStart = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
|
|
17387
|
+
|
|
17388
|
+
const worker = async () => {
|
|
17389
|
+
while (true) {
|
|
17390
|
+
const idx = issued++;
|
|
17391
|
+
if (idx >= totalRequests) break;
|
|
17392
|
+
const reqStart = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
|
|
17393
|
+
try {
|
|
17394
|
+
let resp;
|
|
17395
|
+
if (portTable) {
|
|
17396
|
+
resp = await portTable.dispatchRequest(url, { method, headers: { ...headers }, body });
|
|
17397
|
+
} else {
|
|
17398
|
+
resp = await fetch(url, { method, headers: { ...headers }, body });
|
|
17399
|
+
}
|
|
17400
|
+
const reqEnd = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
|
|
17401
|
+
const dur = Math.max(0.05, reqEnd - reqStart);
|
|
17402
|
+
latencies.push(dur);
|
|
17403
|
+
const code = (resp && resp.status) || 200;
|
|
17404
|
+
statusCounts[code] = (statusCounts[code] || 0) + 1;
|
|
17405
|
+
const txt = resp && typeof resp.text === 'function' ? await resp.text() : String((resp && resp.body) || '');
|
|
17406
|
+
totalBytes += txt.length;
|
|
17407
|
+
} catch (err) {
|
|
17408
|
+
const reqEnd = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
|
|
17409
|
+
latencies.push(Math.max(0.05, reqEnd - reqStart));
|
|
17410
|
+
const key = (err && (err.chaosEffect || err.code)) || 'ERROR';
|
|
17411
|
+
errorCounts[key] = (errorCounts[key] || 0) + 1;
|
|
17412
|
+
}
|
|
17413
|
+
}
|
|
17414
|
+
};
|
|
17415
|
+
|
|
17416
|
+
const workers = [];
|
|
17417
|
+
for (let w = 0; w < concurrency; w++) {
|
|
17418
|
+
workers.push(worker());
|
|
17419
|
+
}
|
|
17420
|
+
await Promise.all(workers);
|
|
17421
|
+
|
|
17422
|
+
const tEnd = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now();
|
|
17423
|
+
const totalSec = Math.max(0.001, (tEnd - tStart) / 1000);
|
|
17424
|
+
latencies.sort((a, b) => a - b);
|
|
17425
|
+
|
|
17426
|
+
const pct = (p) => {
|
|
17427
|
+
if (latencies.length === 0) return 0;
|
|
17428
|
+
const idx = Math.min(latencies.length - 1, Math.floor((p / 100) * latencies.length));
|
|
17429
|
+
return Number(latencies[idx].toFixed(2));
|
|
17430
|
+
};
|
|
17431
|
+
|
|
17432
|
+
const minLat = latencies.length ? Number(latencies[0].toFixed(2)) : 0;
|
|
17433
|
+
const maxLat = latencies.length ? Number(latencies[latencies.length - 1].toFixed(2)) : 0;
|
|
17434
|
+
const avgLat = latencies.length
|
|
17435
|
+
? Number((latencies.reduce((acc, v) => acc + v, 0) / latencies.length).toFixed(2))
|
|
17436
|
+
: 0;
|
|
17437
|
+
const rps = Number((totalRequests / totalSec).toFixed(2));
|
|
17438
|
+
const p50 = pct(50);
|
|
17439
|
+
const p90 = pct(90);
|
|
17440
|
+
const p95 = pct(95);
|
|
17441
|
+
const p99 = pct(99);
|
|
17442
|
+
|
|
17443
|
+
if (jsonOut) {
|
|
17444
|
+
return {
|
|
17445
|
+
code: 0,
|
|
17446
|
+
stdout: JSON.stringify({
|
|
17447
|
+
url,
|
|
17448
|
+
method,
|
|
17449
|
+
requests: totalRequests,
|
|
17450
|
+
concurrency,
|
|
17451
|
+
durationSec: Number(totalSec.toFixed(4)),
|
|
17452
|
+
rps,
|
|
17453
|
+
totalBytes,
|
|
17454
|
+
latencyMs: { min: minLat, avg: avgLat, p50, p90, p95, p99, max: maxLat },
|
|
17455
|
+
statusCodes: statusCounts,
|
|
17456
|
+
errors: errorCounts
|
|
17457
|
+
}, null, 2) + '\n',
|
|
17458
|
+
stderr: ''
|
|
17459
|
+
};
|
|
17460
|
+
}
|
|
17461
|
+
|
|
17462
|
+
// Build 5-bucket ASCII histogram
|
|
17463
|
+
let histLines = '';
|
|
17464
|
+
if (latencies.length > 0) {
|
|
17465
|
+
const buckets = 5;
|
|
17466
|
+
const span = Math.max(0.5, maxLat - minLat);
|
|
17467
|
+
const step = span / buckets;
|
|
17468
|
+
const counts = new Array(buckets).fill(0);
|
|
17469
|
+
for (const l of latencies) {
|
|
17470
|
+
const b = Math.min(buckets - 1, Math.floor((l - minLat) / step));
|
|
17471
|
+
counts[b]++;
|
|
17472
|
+
}
|
|
17473
|
+
const maxCount = Math.max(1, ...counts);
|
|
17474
|
+
for (let b = 0; b < buckets; b++) {
|
|
17475
|
+
const edge = (minLat + step * (b + 1)).toFixed(2).padStart(7);
|
|
17476
|
+
const countStr = `[${counts[b]}]`.padStart(6);
|
|
17477
|
+
const barLen = Math.round((counts[b] / maxCount) * 28);
|
|
17478
|
+
histLines += ` ${edge} ms ${countStr} |${'■'.repeat(barLen)}\n`;
|
|
17479
|
+
}
|
|
17480
|
+
}
|
|
17481
|
+
|
|
17482
|
+
let statusLines = '';
|
|
17483
|
+
for (const [code, count] of Object.entries(statusCounts)) {
|
|
17484
|
+
statusLines += ` [${code}]\t${count} responses\n`;
|
|
17485
|
+
}
|
|
17486
|
+
for (const [errKey, count] of Object.entries(errorCounts)) {
|
|
17487
|
+
statusLines += ` [${errKey}]\t${count} failed\n`;
|
|
17488
|
+
}
|
|
17489
|
+
|
|
17490
|
+
const out =
|
|
17491
|
+
`\nSummary:\n` +
|
|
17492
|
+
` Total:\t${totalSec.toFixed(4)} secs\n` +
|
|
17493
|
+
` Slowest:\t${maxLat.toFixed(2)} ms\n` +
|
|
17494
|
+
` Fastest:\t${minLat.toFixed(2)} ms\n` +
|
|
17495
|
+
` Average:\t${avgLat.toFixed(2)} ms\n` +
|
|
17496
|
+
` Requests/sec:\t${rps.toFixed(2)}\n` +
|
|
17497
|
+
` Total data:\t${totalBytes} bytes\n` +
|
|
17498
|
+
`\nResponse time histogram:\n` +
|
|
17499
|
+
histLines +
|
|
17500
|
+
`\nLatency distribution:\n` +
|
|
17501
|
+
` 50% in ${p50.toFixed(2)} ms (p50)\n` +
|
|
17502
|
+
` 90% in ${p90.toFixed(2)} ms (p90)\n` +
|
|
17503
|
+
` 95% in ${p95.toFixed(2)} ms (p95)\n` +
|
|
17504
|
+
` 99% in ${p99.toFixed(2)} ms (p99)\n` +
|
|
17505
|
+
`\nStatus code distribution:\n` +
|
|
17506
|
+
statusLines;
|
|
17507
|
+
|
|
17508
|
+
return { code: 0, stdout: out, stderr: '' };
|
|
17509
|
+
},
|
|
17510
|
+
|
|
17511
|
+
async ab(args, ctx) {
|
|
17512
|
+
return COREUTILS.hey(args, ctx);
|
|
17513
|
+
},
|
|
17514
|
+
|
|
17515
|
+
async wrk(args, ctx) {
|
|
17516
|
+
return COREUTILS.hey(args, ctx);
|
|
17517
|
+
},
|
|
17518
|
+
|
|
17519
|
+
async chaos(args, ctx) {
|
|
17520
|
+
const portTable = (ctx.shell && ctx.shell.portTable) || null;
|
|
17521
|
+
if (!portTable || typeof portTable.setChaosRule !== 'function') {
|
|
17522
|
+
return { code: 1, stdout: '', stderr: 'chaos: virtual port table does not support chaos injection\n' };
|
|
17523
|
+
}
|
|
17524
|
+
|
|
17525
|
+
const sub = (args[0] || 'status').toLowerCase();
|
|
17526
|
+
|
|
17527
|
+
if (sub === 'status' || sub === 'list' || sub === 'ls') {
|
|
17528
|
+
const rules = portTable.listChaosRules ? portTable.listChaosRules() : [];
|
|
17529
|
+
if (rules.length === 0) {
|
|
17530
|
+
return { code: 0, stdout: 'No active chaos rules. All virtual ports are healthy.\n', stderr: '' };
|
|
17531
|
+
}
|
|
17532
|
+
const lines = ['PORT\tSTATE\tLATENCY\tJITTER\tDROP%\tERR%\tSTATUS\tPARTITION_FROM'];
|
|
17533
|
+
for (const r of rules) {
|
|
17534
|
+
lines.push(
|
|
17535
|
+
`:${r.port}\t${r.crashed ? 'CRASHED' : 'ACTIVE'}\t${r.latencyMs || 0}ms\t${r.jitterMs || 0}ms\t` +
|
|
17536
|
+
`${Math.round((r.dropRate || 0) * 100)}%\t${Math.round((r.errorRate || 0) * 100)}%\t` +
|
|
17537
|
+
`${r.errorStatus || 503}\t${(r.partitionFromPorts || []).join(',') || '-'}`
|
|
17538
|
+
);
|
|
17539
|
+
}
|
|
17540
|
+
return { code: 0, stdout: lines.join('\n') + '\n', stderr: '' };
|
|
17541
|
+
}
|
|
17542
|
+
|
|
17543
|
+
if (sub === 'reset' || sub === 'clear') {
|
|
17544
|
+
portTable.clearChaosRules();
|
|
17545
|
+
return { code: 0, stdout: 'Cleared all network chaos rules. All nodes healed.\n', stderr: '' };
|
|
17546
|
+
}
|
|
17547
|
+
|
|
17548
|
+
if (sub === 'latency' || sub === 'delay') {
|
|
17549
|
+
const port = parseInt(args[1], 10);
|
|
17550
|
+
const latencyMs = parseInt(args[2], 10) || 0;
|
|
17551
|
+
let jitterMs = 0;
|
|
17552
|
+
for (let i = 3; i < args.length; i++) {
|
|
17553
|
+
if ((args[i] === '--jitter' || args[i] === '-j') && args[i + 1]) {
|
|
17554
|
+
jitterMs = parseInt(args[++i], 10) || 0;
|
|
17555
|
+
}
|
|
17556
|
+
}
|
|
17557
|
+
if (!port) return { code: 1, stdout: '', stderr: 'Usage: chaos latency <port> <ms> [--jitter <ms>]\n' };
|
|
17558
|
+
portTable.setChaosRule(port, { latencyMs, jitterMs });
|
|
17559
|
+
return { code: 0, stdout: `Injected +${latencyMs}ms latency (jitter ±${jitterMs}ms) on port :${port}\n`, stderr: '' };
|
|
17560
|
+
}
|
|
17561
|
+
|
|
17562
|
+
if (sub === 'drop' || sub === 'loss') {
|
|
17563
|
+
const port = parseInt(args[1], 10);
|
|
17564
|
+
const rawRate = parseFloat(args[2]);
|
|
17565
|
+
if (!port || isNaN(rawRate)) return { code: 1, stdout: '', stderr: 'Usage: chaos drop <port> <rate 0..1 or 0..100>\n' };
|
|
17566
|
+
const dropRate = rawRate > 1 ? rawRate / 100 : rawRate;
|
|
17567
|
+
portTable.setChaosRule(port, { dropRate });
|
|
17568
|
+
return { code: 0, stdout: `Injected ${Math.round(dropRate * 100)}% packet drop (ETIMEDOUT) on port :${port}\n`, stderr: '' };
|
|
17569
|
+
}
|
|
17570
|
+
|
|
17571
|
+
if (sub === 'error' || sub === 'fail' || sub === '503') {
|
|
17572
|
+
const port = parseInt(args[1], 10);
|
|
17573
|
+
const rawRate = args[2] !== undefined ? parseFloat(args[2]) : 0.25;
|
|
17574
|
+
let errorStatus = 503;
|
|
17575
|
+
for (let i = 3; i < args.length; i++) {
|
|
17576
|
+
if ((args[i] === '--status' || args[i] === '-s') && args[i + 1]) {
|
|
17577
|
+
errorStatus = parseInt(args[++i], 10) || 503;
|
|
17578
|
+
}
|
|
17579
|
+
}
|
|
17580
|
+
if (!port || isNaN(rawRate)) return { code: 1, stdout: '', stderr: 'Usage: chaos error <port> <rate> [--status 503]\n' };
|
|
17581
|
+
const errorRate = rawRate > 1 ? rawRate / 100 : rawRate;
|
|
17582
|
+
portTable.setChaosRule(port, { errorRate, errorStatus });
|
|
17583
|
+
return { code: 0, stdout: `Injected ${Math.round(errorRate * 100)}% HTTP ${errorStatus} error rate on port :${port}\n`, stderr: '' };
|
|
17584
|
+
}
|
|
17585
|
+
|
|
17586
|
+
if (sub === 'crash' || sub === 'kill' || sub === 'down') {
|
|
17587
|
+
const port = parseInt(args[1], 10);
|
|
17588
|
+
if (!port) return { code: 1, stdout: '', stderr: 'Usage: chaos crash <port>\n' };
|
|
17589
|
+
portTable.setChaosRule(port, { crashed: true });
|
|
17590
|
+
return { code: 0, stdout: `Port :${port} marked CRASHED (all connections will fail with ECONNREFUSED)\n`, stderr: '' };
|
|
17591
|
+
}
|
|
17592
|
+
|
|
17593
|
+
if (sub === 'heal' || sub === 'up' || sub === 'recover') {
|
|
17594
|
+
const port = parseInt(args[1], 10);
|
|
17595
|
+
if (!port) {
|
|
17596
|
+
portTable.clearChaosRules();
|
|
17597
|
+
return { code: 0, stdout: 'Cleared all network chaos rules. All nodes healed.\n', stderr: '' };
|
|
17598
|
+
}
|
|
17599
|
+
portTable.clearChaosRules(port);
|
|
17600
|
+
return { code: 0, stdout: `Port :${port} healed (all fault injections removed)\n`, stderr: '' };
|
|
17601
|
+
}
|
|
17602
|
+
|
|
17603
|
+
if (sub === 'partition' || sub === 'isolate') {
|
|
17604
|
+
const fromPort = parseInt(args[1], 10);
|
|
17605
|
+
const toPort = parseInt(args[2], 10);
|
|
17606
|
+
if (!fromPort || !toPort) return { code: 1, stdout: '', stderr: 'Usage: chaos partition <fromPort> <toPort>\n' };
|
|
17607
|
+
const existing = portTable.getChaosRule(toPort) || { partitionFromPorts: [] };
|
|
17608
|
+
const list = Array.from(new Set([...(existing.partitionFromPorts || []), fromPort]));
|
|
17609
|
+
portTable.setChaosRule(toPort, { partitionFromPorts: list });
|
|
17610
|
+
return { code: 0, stdout: `Network partition active: :${fromPort} -X-> :${toPort} (EHOSTUNREACH)\n`, stderr: '' };
|
|
17611
|
+
}
|
|
17612
|
+
|
|
17613
|
+
return {
|
|
17614
|
+
code: 1,
|
|
17615
|
+
stdout: '',
|
|
17616
|
+
stderr:
|
|
17617
|
+
'Usage: chaos <command> [args]\n' +
|
|
17618
|
+
'Commands:\n' +
|
|
17619
|
+
' chaos status List active fault rules\n' +
|
|
17620
|
+
' chaos latency <port> <ms> [--jitter ms] Add network latency & jitter\n' +
|
|
17621
|
+
' chaos error <port> <rate> [--status N] Inject HTTP 503/429 error rate (e.g. 0.25)\n' +
|
|
17622
|
+
' chaos drop <port> <rate> Inject packet drop / timeout rate\n' +
|
|
17623
|
+
' chaos crash <port> Simulate node crash (ECONNREFUSED)\n' +
|
|
17624
|
+
' chaos partition <fromPort> <toPort> Block traffic between two ports\n' +
|
|
17625
|
+
' chaos heal [port] Heal a port (or all ports)\n' +
|
|
17626
|
+
' chaos reset Remove all chaos rules\n'
|
|
17627
|
+
};
|
|
17628
|
+
},
|
|
17629
|
+
|
|
17630
|
+
async sqlite3(args, ctx) {
|
|
17631
|
+
let format = 'pipe';
|
|
17632
|
+
let showHeader = false;
|
|
17633
|
+
const positional = [];
|
|
17634
|
+
|
|
17635
|
+
for (let i = 0; i < args.length; i++) {
|
|
17636
|
+
const a = args[i];
|
|
17637
|
+
if (a === '-header' || a === '--header') showHeader = true;
|
|
17638
|
+
else if (a === '-column' || a === '--column' || a === '-table' || a === '--table') {
|
|
17639
|
+
format = 'column';
|
|
17640
|
+
showHeader = true;
|
|
17641
|
+
} else if (a === '-json' || a === '--json') format = 'json';
|
|
17642
|
+
else if (a === '-csv' || a === '--csv') format = 'csv';
|
|
17643
|
+
else if (!a.startsWith('-')) positional.push(a);
|
|
17644
|
+
}
|
|
17645
|
+
|
|
17646
|
+
let dbFile = ':memory:';
|
|
17647
|
+
let sqlInput = '';
|
|
17648
|
+
|
|
17649
|
+
if (positional.length === 1) {
|
|
17650
|
+
if (/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|PRAGMA|EXPLAIN|BEGIN|COMMIT|WITH|\.)/i.test(positional[0])) {
|
|
17651
|
+
sqlInput = positional[0];
|
|
17652
|
+
} else {
|
|
17653
|
+
dbFile = positional[0];
|
|
17654
|
+
}
|
|
17655
|
+
} else if (positional.length >= 2) {
|
|
17656
|
+
dbFile = positional[0];
|
|
17657
|
+
sqlInput = positional.slice(1).join(' ');
|
|
17658
|
+
}
|
|
17659
|
+
|
|
17660
|
+
if (!sqlInput && ctx.stdin) {
|
|
17661
|
+
sqlInput = String(ctx.stdin).trim();
|
|
17662
|
+
}
|
|
17663
|
+
|
|
17664
|
+
if (!sqlInput) {
|
|
17665
|
+
return {
|
|
17666
|
+
code: 0,
|
|
17667
|
+
stdout: 'SQLite 3.45.0 (CodeLab VFS Engine)\nUsage: sqlite3 [-column] [-header] [-json] [dbfile] "SQL"\n',
|
|
17668
|
+
stderr: ''
|
|
17669
|
+
};
|
|
17670
|
+
}
|
|
17671
|
+
|
|
17672
|
+
const rm = getRuntimeModule();
|
|
17673
|
+
const createDb =
|
|
17674
|
+
(rm && typeof rm.createSqliteDatabase === 'function' ? rm.createSqliteDatabase : null) ||
|
|
17675
|
+
(typeof _hostRuntime !== 'undefined' && _hostRuntime && _hostRuntime.createSqliteDatabase) ||
|
|
17676
|
+
(typeof globalThis !== 'undefined' && globalThis._codeLabCreateSqliteDatabase);
|
|
17677
|
+
|
|
17678
|
+
if (typeof createDb !== 'function') {
|
|
17679
|
+
return { code: 1, stdout: '', stderr: 'sqlite3: SQLite engine not initialized in runtime\n' };
|
|
17680
|
+
}
|
|
17681
|
+
|
|
17682
|
+
try {
|
|
17683
|
+
const SqliteDatabase = createDb(ctx.vfs, () => ctx.shell.cwd);
|
|
17684
|
+
const db = new SqliteDatabase(dbFile);
|
|
17685
|
+
const trimmed = sqlInput.trim();
|
|
17686
|
+
|
|
17687
|
+
if (trimmed === '.tables') {
|
|
17688
|
+
const names = Array.from(db.tables.keys());
|
|
17689
|
+
return { code: 0, stdout: names.length ? names.join(' ') + '\n' : '', stderr: '' };
|
|
17690
|
+
}
|
|
17691
|
+
if (trimmed.startsWith('.schema')) {
|
|
17692
|
+
const lines = [];
|
|
17693
|
+
for (const [name, t] of db.tables.entries()) {
|
|
17694
|
+
const cols = t.columns.map(c => `${c.name} ${c.type || 'TEXT'}`).join(', ');
|
|
17695
|
+
lines.push(`CREATE TABLE ${name} (${cols});`);
|
|
17696
|
+
}
|
|
17697
|
+
for (const idx of db.indexes.values()) {
|
|
17698
|
+
lines.push(`CREATE ${idx.unique ? 'UNIQUE ' : ''}INDEX ${idx.name} ON ${idx.table} (${idx.columns.join(', ')});`);
|
|
17699
|
+
}
|
|
17700
|
+
return { code: 0, stdout: lines.join('\n') + (lines.length ? '\n' : ''), stderr: '' };
|
|
17701
|
+
}
|
|
17702
|
+
if (trimmed === '.indexes' || trimmed === '.indices') {
|
|
17703
|
+
const names = Array.from(db.indexes.keys());
|
|
17704
|
+
return { code: 0, stdout: names.length ? names.join(' ') + '\n' : '', stderr: '' };
|
|
17705
|
+
}
|
|
17706
|
+
|
|
17707
|
+
const stmts = trimmed.split(';').map(s => s.trim()).filter(Boolean);
|
|
17708
|
+
const outputs = [];
|
|
17709
|
+
for (const stmt of stmts) {
|
|
17710
|
+
const isQuery = /^(SELECT|EXPLAIN|PRAGMA)\b/i.test(stmt);
|
|
17711
|
+
const res = isQuery ? db.query(stmt).all() : (db.run(stmt), []);
|
|
17712
|
+
if (Array.isArray(res) && res.length > 0) {
|
|
17713
|
+
if (format === 'json') {
|
|
17714
|
+
outputs.push(JSON.stringify(res, null, 2));
|
|
17715
|
+
} else if (format === 'column') {
|
|
17716
|
+
const cols = Object.keys(res[0]);
|
|
17717
|
+
const widths = cols.map(c => Math.max(c.length, ...res.map(r => String(r[c] ?? '').length)));
|
|
17718
|
+
if (showHeader) {
|
|
17719
|
+
outputs.push(cols.map((c, i) => c.padEnd(widths[i])).join(' '));
|
|
17720
|
+
outputs.push(widths.map(w => '-'.repeat(w)).join(' '));
|
|
17721
|
+
}
|
|
17722
|
+
for (const row of res) {
|
|
17723
|
+
outputs.push(cols.map((c, i) => String(row[c] ?? '').padEnd(widths[i])).join(' '));
|
|
17724
|
+
}
|
|
17725
|
+
} else {
|
|
17726
|
+
const cols = Object.keys(res[0]);
|
|
17727
|
+
const sep = format === 'csv' ? ',' : '|';
|
|
17728
|
+
if (showHeader) outputs.push(cols.join(sep));
|
|
17729
|
+
for (const row of res) {
|
|
17730
|
+
outputs.push(cols.map(c => String(row[c] ?? '')).join(sep));
|
|
17731
|
+
}
|
|
17732
|
+
}
|
|
17733
|
+
}
|
|
17734
|
+
}
|
|
17735
|
+
return { code: 0, stdout: outputs.length ? outputs.join('\n') + '\n' : '', stderr: '' };
|
|
17736
|
+
} catch (err) {
|
|
17737
|
+
return { code: 1, stdout: '', stderr: `Error: ${err.message || String(err)}\n` };
|
|
17738
|
+
}
|
|
17739
|
+
}
|
|
17740
|
+
};
|
|
17741
|
+
|
|
17742
|
+
COREUTILS['redis-cli'] = async function redisCli(args, ctx) {
|
|
17743
|
+
const storePath = '/workspace/.codelab-redis.json';
|
|
17744
|
+
const loadState = () => {
|
|
17745
|
+
try {
|
|
17746
|
+
if (ctx.vfs.existsSync(storePath)) {
|
|
17747
|
+
const raw = JSON.parse(ctx.vfs.readFileSync(storePath, 'utf8'));
|
|
17748
|
+
if (raw && typeof raw === 'object') return raw;
|
|
17749
|
+
}
|
|
17750
|
+
} catch (err) {
|
|
17751
|
+
_shellLogger.debug('redis-cli state read fallback:', err);
|
|
17752
|
+
}
|
|
17753
|
+
return { kv: {}, hashes: {}, lists: {}, sets: {}, zsets: {}, expires: {} };
|
|
17754
|
+
};
|
|
17755
|
+
const saveState = (state) => {
|
|
17756
|
+
try {
|
|
17757
|
+
ctx.vfs.writeFileSync(storePath, JSON.stringify(state));
|
|
17758
|
+
} catch (err) {
|
|
17759
|
+
_shellLogger.debug('redis-cli state write failed:', err);
|
|
17760
|
+
}
|
|
17761
|
+
};
|
|
17762
|
+
|
|
17763
|
+
const state = loadState();
|
|
17764
|
+
const now = Date.now();
|
|
17765
|
+
// Evict expired keys lazily
|
|
17766
|
+
for (const [k, exp] of Object.entries(state.expires || {})) {
|
|
17767
|
+
if (typeof exp === 'number' && exp <= now) {
|
|
17768
|
+
delete state.kv[k];
|
|
17769
|
+
delete state.hashes[k];
|
|
17770
|
+
delete state.lists[k];
|
|
17771
|
+
delete state.sets[k];
|
|
17772
|
+
delete state.zsets[k];
|
|
17773
|
+
delete state.expires[k];
|
|
17774
|
+
}
|
|
17775
|
+
}
|
|
17776
|
+
|
|
17777
|
+
// Filter out connection flags (-h, -p, -n)
|
|
17778
|
+
const cmdArgs = [];
|
|
17779
|
+
for (let i = 0; i < args.length; i++) {
|
|
17780
|
+
if ((args[i] === '-h' || args[i] === '-p' || args[i] === '-n') && i + 1 < args.length) {
|
|
17781
|
+
i++;
|
|
17782
|
+
continue;
|
|
17783
|
+
}
|
|
17784
|
+
cmdArgs.push(args[i]);
|
|
17785
|
+
}
|
|
17786
|
+
|
|
17787
|
+
if (cmdArgs.length === 0 && ctx.stdin) {
|
|
17788
|
+
const firstLine = String(ctx.stdin).trim().split(/\r?\n/)[0];
|
|
17789
|
+
if (firstLine) cmdArgs.push(...firstLine.split(/\s+/));
|
|
17790
|
+
}
|
|
17791
|
+
|
|
17792
|
+
if (cmdArgs.length === 0) {
|
|
17793
|
+
return { code: 0, stdout: 'redis-cli 7.2.4 (CodeLab VFS Store)\nUsage: redis-cli <COMMAND> [args...]\n', stderr: '' };
|
|
17794
|
+
}
|
|
17795
|
+
|
|
17796
|
+
const cmd = String(cmdArgs[0]).toUpperCase();
|
|
17797
|
+
const rest = cmdArgs.slice(1);
|
|
17798
|
+
|
|
17799
|
+
const outInt = (n) => `(integer) ${n}\n`;
|
|
17800
|
+
const outBulk = (v) => (v === null || v === undefined ? '(nil)\n' : `"${v}"\n`);
|
|
17801
|
+
const outArray = (arr) => {
|
|
17802
|
+
if (!arr || arr.length === 0) return '(empty array)\n';
|
|
17803
|
+
return arr.map((item, i) => `${i + 1}) "${item}"`).join('\n') + '\n';
|
|
17804
|
+
};
|
|
17805
|
+
|
|
17806
|
+
if (cmd === 'PING') {
|
|
17807
|
+
return { code: 0, stdout: rest[0] ? outBulk(rest[0]) : 'PONG\n', stderr: '' };
|
|
17808
|
+
}
|
|
17809
|
+
if (cmd === 'FLUSHALL' || cmd === 'FLUSHDB') {
|
|
17810
|
+
saveState({ kv: {}, hashes: {}, lists: {}, sets: {}, zsets: {}, expires: {} });
|
|
17811
|
+
return { code: 0, stdout: 'OK\n', stderr: '' };
|
|
17812
|
+
}
|
|
17813
|
+
if (cmd === 'DBSIZE') {
|
|
17814
|
+
const allKeys = new Set([
|
|
17815
|
+
...Object.keys(state.kv),
|
|
17816
|
+
...Object.keys(state.hashes),
|
|
17817
|
+
...Object.keys(state.lists),
|
|
17818
|
+
...Object.keys(state.sets),
|
|
17819
|
+
...Object.keys(state.zsets)
|
|
17820
|
+
]);
|
|
17821
|
+
return { code: 0, stdout: outInt(allKeys.size), stderr: '' };
|
|
17822
|
+
}
|
|
17823
|
+
if (cmd === 'INFO') {
|
|
17824
|
+
const allKeys = new Set([
|
|
17825
|
+
...Object.keys(state.kv),
|
|
17826
|
+
...Object.keys(state.hashes),
|
|
17827
|
+
...Object.keys(state.lists),
|
|
17828
|
+
...Object.keys(state.sets),
|
|
17829
|
+
...Object.keys(state.zsets)
|
|
17830
|
+
]);
|
|
17831
|
+
return {
|
|
17832
|
+
code: 0,
|
|
17833
|
+
stdout: `# Server\nredis_version:7.2.4-codelab\n# Keyspace\ndb0:keys=${allKeys.size},expires=${Object.keys(state.expires).length}\n`,
|
|
17834
|
+
stderr: ''
|
|
17835
|
+
};
|
|
17836
|
+
}
|
|
17837
|
+
if (cmd === 'SET') {
|
|
17838
|
+
const [key, val, ...opts] = rest;
|
|
17839
|
+
if (!key || val === undefined) return { code: 1, stdout: '', stderr: 'ERR wrong number of arguments for SET\n' };
|
|
17840
|
+
let nx = false;
|
|
17841
|
+
let xx = false;
|
|
17842
|
+
let ttlMs = null;
|
|
17843
|
+
for (let i = 0; i < opts.length; i++) {
|
|
17844
|
+
const u = String(opts[i]).toUpperCase();
|
|
17845
|
+
if (u === 'NX') nx = true;
|
|
17846
|
+
else if (u === 'XX') xx = true;
|
|
17847
|
+
else if (u === 'EX' && opts[i + 1]) ttlMs = parseInt(opts[++i], 10) * 1000;
|
|
17848
|
+
else if (u === 'PX' && opts[i + 1]) ttlMs = parseInt(opts[++i], 10);
|
|
17849
|
+
}
|
|
17850
|
+
const exists = Object.prototype.hasOwnProperty.call(state.kv, key);
|
|
17851
|
+
if (nx && exists) return { code: 0, stdout: '(nil)\n', stderr: '' };
|
|
17852
|
+
if (xx && !exists) return { code: 0, stdout: '(nil)\n', stderr: '' };
|
|
17853
|
+
state.kv[key] = String(val);
|
|
17854
|
+
if (ttlMs && ttlMs > 0) state.expires[key] = now + ttlMs;
|
|
17855
|
+
else delete state.expires[key];
|
|
17856
|
+
saveState(state);
|
|
17857
|
+
return { code: 0, stdout: 'OK\n', stderr: '' };
|
|
17858
|
+
}
|
|
17859
|
+
if (cmd === 'GET') {
|
|
17860
|
+
const key = rest[0];
|
|
17861
|
+
const val = Object.prototype.hasOwnProperty.call(state.kv, key) ? state.kv[key] : null;
|
|
17862
|
+
saveState(state);
|
|
17863
|
+
return { code: 0, stdout: outBulk(val), stderr: '' };
|
|
17864
|
+
}
|
|
17865
|
+
if (cmd === 'MSET') {
|
|
17866
|
+
for (let i = 0; i + 1 < rest.length; i += 2) {
|
|
17867
|
+
state.kv[rest[i]] = String(rest[i + 1]);
|
|
17868
|
+
}
|
|
17869
|
+
saveState(state);
|
|
17870
|
+
return { code: 0, stdout: 'OK\n', stderr: '' };
|
|
17871
|
+
}
|
|
17872
|
+
if (cmd === 'MGET') {
|
|
17873
|
+
const lines = rest.map((k, i) => `${i + 1}) ${Object.prototype.hasOwnProperty.call(state.kv, k) ? `"${state.kv[k]}"` : '(nil)'}`);
|
|
17874
|
+
return { code: 0, stdout: lines.join('\n') + '\n', stderr: '' };
|
|
17875
|
+
}
|
|
17876
|
+
if (cmd === 'DEL') {
|
|
17877
|
+
let count = 0;
|
|
17878
|
+
for (const k of rest) {
|
|
17879
|
+
if (
|
|
17880
|
+
Object.prototype.hasOwnProperty.call(state.kv, k) ||
|
|
17881
|
+
Object.prototype.hasOwnProperty.call(state.hashes, k) ||
|
|
17882
|
+
Object.prototype.hasOwnProperty.call(state.lists, k) ||
|
|
17883
|
+
Object.prototype.hasOwnProperty.call(state.sets, k) ||
|
|
17884
|
+
Object.prototype.hasOwnProperty.call(state.zsets, k)
|
|
17885
|
+
) {
|
|
17886
|
+
delete state.kv[k];
|
|
17887
|
+
delete state.hashes[k];
|
|
17888
|
+
delete state.lists[k];
|
|
17889
|
+
delete state.sets[k];
|
|
17890
|
+
delete state.zsets[k];
|
|
17891
|
+
delete state.expires[k];
|
|
17892
|
+
count++;
|
|
17893
|
+
}
|
|
17894
|
+
}
|
|
17895
|
+
saveState(state);
|
|
17896
|
+
return { code: 0, stdout: outInt(count), stderr: '' };
|
|
17897
|
+
}
|
|
17898
|
+
if (cmd === 'EXISTS') {
|
|
17899
|
+
let count = 0;
|
|
17900
|
+
for (const k of rest) {
|
|
17901
|
+
if (
|
|
17902
|
+
Object.prototype.hasOwnProperty.call(state.kv, k) ||
|
|
17903
|
+
Object.prototype.hasOwnProperty.call(state.hashes, k) ||
|
|
17904
|
+
Object.prototype.hasOwnProperty.call(state.lists, k) ||
|
|
17905
|
+
Object.prototype.hasOwnProperty.call(state.sets, k) ||
|
|
17906
|
+
Object.prototype.hasOwnProperty.call(state.zsets, k)
|
|
17907
|
+
) count++;
|
|
17908
|
+
}
|
|
17909
|
+
return { code: 0, stdout: outInt(count), stderr: '' };
|
|
17910
|
+
}
|
|
17911
|
+
if (cmd === 'INCR' || cmd === 'DECR' || cmd === 'INCRBY' || cmd === 'DECRBY') {
|
|
17912
|
+
const key = rest[0];
|
|
17913
|
+
const delta = cmd === 'INCR' ? 1 : cmd === 'DECR' ? -1 : (parseInt(rest[1], 10) || 0) * (cmd === 'DECRBY' ? -1 : 1);
|
|
17914
|
+
const cur = parseInt(state.kv[key] || '0', 10) || 0;
|
|
17915
|
+
const next = cur + delta;
|
|
17916
|
+
state.kv[key] = String(next);
|
|
17917
|
+
saveState(state);
|
|
17918
|
+
return { code: 0, stdout: outInt(next), stderr: '' };
|
|
17919
|
+
}
|
|
17920
|
+
if (cmd === 'EXPIRE') {
|
|
17921
|
+
const [key, secs] = rest;
|
|
17922
|
+
const hasKey =
|
|
17923
|
+
Object.prototype.hasOwnProperty.call(state.kv, key) ||
|
|
17924
|
+
Object.prototype.hasOwnProperty.call(state.hashes, key) ||
|
|
17925
|
+
Object.prototype.hasOwnProperty.call(state.lists, key) ||
|
|
17926
|
+
Object.prototype.hasOwnProperty.call(state.sets, key) ||
|
|
17927
|
+
Object.prototype.hasOwnProperty.call(state.zsets, key);
|
|
17928
|
+
if (!hasKey) return { code: 0, stdout: outInt(0), stderr: '' };
|
|
17929
|
+
state.expires[key] = now + (parseInt(secs, 10) || 0) * 1000;
|
|
17930
|
+
saveState(state);
|
|
17931
|
+
return { code: 0, stdout: outInt(1), stderr: '' };
|
|
17932
|
+
}
|
|
17933
|
+
if (cmd === 'TTL') {
|
|
17934
|
+
const key = rest[0];
|
|
17935
|
+
const hasKey =
|
|
17936
|
+
Object.prototype.hasOwnProperty.call(state.kv, key) ||
|
|
17937
|
+
Object.prototype.hasOwnProperty.call(state.hashes, key) ||
|
|
17938
|
+
Object.prototype.hasOwnProperty.call(state.lists, key) ||
|
|
17939
|
+
Object.prototype.hasOwnProperty.call(state.sets, key) ||
|
|
17940
|
+
Object.prototype.hasOwnProperty.call(state.zsets, key);
|
|
17941
|
+
if (!hasKey) return { code: 0, stdout: outInt(-2), stderr: '' };
|
|
17942
|
+
if (!state.expires[key]) return { code: 0, stdout: outInt(-1), stderr: '' };
|
|
17943
|
+
const rem = Math.max(0, Math.ceil((state.expires[key] - now) / 1000));
|
|
17944
|
+
return { code: 0, stdout: outInt(rem), stderr: '' };
|
|
17945
|
+
}
|
|
17946
|
+
if (cmd === 'KEYS') {
|
|
17947
|
+
const pat = rest[0] || '*';
|
|
17948
|
+
const re = new RegExp('^' + pat.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$');
|
|
17949
|
+
const allKeys = Array.from(new Set([
|
|
17950
|
+
...Object.keys(state.kv),
|
|
17951
|
+
...Object.keys(state.hashes),
|
|
17952
|
+
...Object.keys(state.lists),
|
|
17953
|
+
...Object.keys(state.sets),
|
|
17954
|
+
...Object.keys(state.zsets)
|
|
17955
|
+
])).filter(k => re.test(k));
|
|
17956
|
+
return { code: 0, stdout: outArray(allKeys), stderr: '' };
|
|
17957
|
+
}
|
|
17958
|
+
if (cmd === 'HSET') {
|
|
17959
|
+
const key = rest[0];
|
|
17960
|
+
state.hashes[key] = state.hashes[key] || {};
|
|
17961
|
+
let added = 0;
|
|
17962
|
+
for (let i = 1; i + 1 < rest.length; i += 2) {
|
|
17963
|
+
if (!Object.prototype.hasOwnProperty.call(state.hashes[key], rest[i])) added++;
|
|
17964
|
+
state.hashes[key][rest[i]] = String(rest[i + 1]);
|
|
17965
|
+
}
|
|
17966
|
+
saveState(state);
|
|
17967
|
+
return { code: 0, stdout: outInt(added), stderr: '' };
|
|
17968
|
+
}
|
|
17969
|
+
if (cmd === 'HGET') {
|
|
17970
|
+
const [key, field] = rest;
|
|
17971
|
+
const val = state.hashes[key] && Object.prototype.hasOwnProperty.call(state.hashes[key], field) ? state.hashes[key][field] : null;
|
|
17972
|
+
return { code: 0, stdout: outBulk(val), stderr: '' };
|
|
17973
|
+
}
|
|
17974
|
+
if (cmd === 'HGETALL') {
|
|
17975
|
+
const key = rest[0];
|
|
17976
|
+
const h = state.hashes[key] || {};
|
|
17977
|
+
const flat = [];
|
|
17978
|
+
for (const [f, v] of Object.entries(h)) flat.push(f, v);
|
|
17979
|
+
return { code: 0, stdout: outArray(flat), stderr: '' };
|
|
17980
|
+
}
|
|
17981
|
+
if (cmd === 'HDEL') {
|
|
17982
|
+
const [key, ...fields] = rest;
|
|
17983
|
+
const h = state.hashes[key] || {};
|
|
17984
|
+
let count = 0;
|
|
17985
|
+
for (const f of fields) {
|
|
17986
|
+
if (Object.prototype.hasOwnProperty.call(h, f)) {
|
|
17987
|
+
delete h[f];
|
|
17988
|
+
count++;
|
|
17989
|
+
}
|
|
17990
|
+
}
|
|
17991
|
+
saveState(state);
|
|
17992
|
+
return { code: 0, stdout: outInt(count), stderr: '' };
|
|
17993
|
+
}
|
|
17994
|
+
if (cmd === 'LPUSH' || cmd === 'RPUSH') {
|
|
17995
|
+
const [key, ...vals] = rest;
|
|
17996
|
+
state.lists[key] = state.lists[key] || [];
|
|
17997
|
+
for (const v of vals) {
|
|
17998
|
+
if (cmd === 'LPUSH') state.lists[key].unshift(String(v));
|
|
17999
|
+
else state.lists[key].push(String(v));
|
|
18000
|
+
}
|
|
18001
|
+
saveState(state);
|
|
18002
|
+
return { code: 0, stdout: outInt(state.lists[key].length), stderr: '' };
|
|
18003
|
+
}
|
|
18004
|
+
if (cmd === 'LPOP' || cmd === 'RPOP') {
|
|
18005
|
+
const key = rest[0];
|
|
18006
|
+
const list = state.lists[key] || [];
|
|
18007
|
+
const val = list.length === 0 ? null : (cmd === 'LPOP' ? list.shift() : list.pop());
|
|
18008
|
+
saveState(state);
|
|
18009
|
+
return { code: 0, stdout: outBulk(val), stderr: '' };
|
|
18010
|
+
}
|
|
18011
|
+
if (cmd === 'LRANGE') {
|
|
18012
|
+
const [key, sRaw, eRaw] = rest;
|
|
18013
|
+
const list = state.lists[key] || [];
|
|
18014
|
+
let s = parseInt(sRaw, 10) || 0;
|
|
18015
|
+
let e = parseInt(eRaw, 10);
|
|
18016
|
+
if (isNaN(e)) e = -1;
|
|
18017
|
+
if (s < 0) s = Math.max(0, list.length + s);
|
|
18018
|
+
if (e < 0) e = list.length + e;
|
|
18019
|
+
return { code: 0, stdout: outArray(list.slice(s, e + 1)), stderr: '' };
|
|
18020
|
+
}
|
|
18021
|
+
if (cmd === 'LLEN') {
|
|
18022
|
+
const list = state.lists[rest[0]] || [];
|
|
18023
|
+
return { code: 0, stdout: outInt(list.length), stderr: '' };
|
|
18024
|
+
}
|
|
18025
|
+
if (cmd === 'SADD') {
|
|
18026
|
+
const [key, ...members] = rest;
|
|
18027
|
+
const set = new Set(state.sets[key] || []);
|
|
18028
|
+
let added = 0;
|
|
18029
|
+
for (const m of members) {
|
|
18030
|
+
if (!set.has(String(m))) {
|
|
18031
|
+
set.add(String(m));
|
|
18032
|
+
added++;
|
|
18033
|
+
}
|
|
18034
|
+
}
|
|
18035
|
+
state.sets[key] = Array.from(set);
|
|
18036
|
+
saveState(state);
|
|
18037
|
+
return { code: 0, stdout: outInt(added), stderr: '' };
|
|
18038
|
+
}
|
|
18039
|
+
if (cmd === 'SMEMBERS') {
|
|
18040
|
+
return { code: 0, stdout: outArray(state.sets[rest[0]] || []), stderr: '' };
|
|
18041
|
+
}
|
|
18042
|
+
if (cmd === 'SISMEMBER') {
|
|
18043
|
+
const [key, member] = rest;
|
|
18044
|
+
const set = new Set(state.sets[key] || []);
|
|
18045
|
+
return { code: 0, stdout: outInt(set.has(String(member)) ? 1 : 0), stderr: '' };
|
|
18046
|
+
}
|
|
18047
|
+
if (cmd === 'SREM') {
|
|
18048
|
+
const [key, ...members] = rest;
|
|
18049
|
+
const set = new Set(state.sets[key] || []);
|
|
18050
|
+
let removed = 0;
|
|
18051
|
+
for (const m of members) {
|
|
18052
|
+
if (set.delete(String(m))) removed++;
|
|
18053
|
+
}
|
|
18054
|
+
state.sets[key] = Array.from(set);
|
|
18055
|
+
saveState(state);
|
|
18056
|
+
return { code: 0, stdout: outInt(removed), stderr: '' };
|
|
18057
|
+
}
|
|
18058
|
+
if (cmd === 'ZADD') {
|
|
18059
|
+
const [key, ...pairs] = rest;
|
|
18060
|
+
state.zsets[key] = state.zsets[key] || {};
|
|
18061
|
+
let added = 0;
|
|
18062
|
+
for (let i = 0; i + 1 < pairs.length; i += 2) {
|
|
18063
|
+
const score = parseFloat(pairs[i]);
|
|
18064
|
+
const member = String(pairs[i + 1]);
|
|
18065
|
+
if (!Object.prototype.hasOwnProperty.call(state.zsets[key], member)) added++;
|
|
18066
|
+
state.zsets[key][member] = isNaN(score) ? 0 : score;
|
|
18067
|
+
}
|
|
18068
|
+
saveState(state);
|
|
18069
|
+
return { code: 0, stdout: outInt(added), stderr: '' };
|
|
18070
|
+
}
|
|
18071
|
+
if (cmd === 'ZSCORE') {
|
|
18072
|
+
const [key, member] = rest;
|
|
18073
|
+
const z = state.zsets[key] || {};
|
|
18074
|
+
return { code: 0, stdout: Object.prototype.hasOwnProperty.call(z, member) ? outBulk(String(z[member])) : '(nil)\n', stderr: '' };
|
|
18075
|
+
}
|
|
18076
|
+
if (cmd === 'ZRANGE' || cmd === 'ZREVRANGE') {
|
|
18077
|
+
const [key, sRaw, eRaw, flag] = rest;
|
|
18078
|
+
const z = state.zsets[key] || {};
|
|
18079
|
+
const entries = Object.entries(z).sort((a, b) =>
|
|
18080
|
+
cmd === 'ZREVRANGE'
|
|
18081
|
+
? (b[1] - a[1] || b[0].localeCompare(a[0]))
|
|
18082
|
+
: (a[1] - b[1] || a[0].localeCompare(b[0]))
|
|
18083
|
+
);
|
|
18084
|
+
let s = parseInt(sRaw, 10) || 0;
|
|
18085
|
+
let e = parseInt(eRaw, 10);
|
|
18086
|
+
if (isNaN(e)) e = -1;
|
|
18087
|
+
if (s < 0) s = Math.max(0, entries.length + s);
|
|
18088
|
+
if (e < 0) e = entries.length + e;
|
|
18089
|
+
const slice = entries.slice(s, e + 1);
|
|
18090
|
+
const withScores = flag && String(flag).toUpperCase() === 'WITHSCORES';
|
|
18091
|
+
const out = [];
|
|
18092
|
+
for (const [m, sc] of slice) {
|
|
18093
|
+
out.push(m);
|
|
18094
|
+
if (withScores) out.push(String(sc));
|
|
18095
|
+
}
|
|
18096
|
+
return { code: 0, stdout: outArray(out), stderr: '' };
|
|
16767
18097
|
}
|
|
18098
|
+
if (cmd === 'ZCARD') {
|
|
18099
|
+
const z = state.zsets[rest[0]] || {};
|
|
18100
|
+
return { code: 0, stdout: outInt(Object.keys(z).length), stderr: '' };
|
|
18101
|
+
}
|
|
18102
|
+
if (cmd === 'ZREM') {
|
|
18103
|
+
const [key, ...members] = rest;
|
|
18104
|
+
const z = state.zsets[key] || {};
|
|
18105
|
+
let removed = 0;
|
|
18106
|
+
for (const m of members) {
|
|
18107
|
+
if (Object.prototype.hasOwnProperty.call(z, m)) {
|
|
18108
|
+
delete z[m];
|
|
18109
|
+
removed++;
|
|
18110
|
+
}
|
|
18111
|
+
}
|
|
18112
|
+
saveState(state);
|
|
18113
|
+
return { code: 0, stdout: outInt(removed), stderr: '' };
|
|
18114
|
+
}
|
|
18115
|
+
if (cmd === 'EVAL') {
|
|
18116
|
+
const script = String(rest[0] || '');
|
|
18117
|
+
const numKeys = Math.max(0, parseInt(rest[1], 10) || 0);
|
|
18118
|
+
const keys = rest.slice(2, 2 + numKeys);
|
|
18119
|
+
const argv = rest.slice(2 + numKeys);
|
|
18120
|
+
const k0 = keys[0] || 'bucket:default';
|
|
18121
|
+
if (/token_bucket|tokens/i.test(script)) {
|
|
18122
|
+
const capacity = Math.max(1, parseInt(argv[0], 10) || 10);
|
|
18123
|
+
const current = state.kv[k0] !== undefined ? parseInt(state.kv[k0], 10) : capacity;
|
|
18124
|
+
if (current > 0) {
|
|
18125
|
+
const rem = current - 1;
|
|
18126
|
+
state.kv[k0] = String(rem);
|
|
18127
|
+
saveState(state);
|
|
18128
|
+
return { code: 0, stdout: `1) (integer) 1\n2) (integer) ${rem}\n`, stderr: '' };
|
|
18129
|
+
}
|
|
18130
|
+
return { code: 0, stdout: `1) (integer) 0\n2) (integer) 0\n`, stderr: '' };
|
|
18131
|
+
}
|
|
18132
|
+
return { code: 0, stdout: outBulk('OK'), stderr: '' };
|
|
18133
|
+
}
|
|
18134
|
+
|
|
18135
|
+
return { code: 1, stdout: '', stderr: `ERR unknown command '${cmd}'\n` };
|
|
16768
18136
|
};
|
|
16769
18137
|
|
|
16770
18138
|
// =========================================================================
|
|
@@ -18915,7 +20283,7 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
18915
20283
|
|
|
18916
20284
|
// The bundler rewrites this literal from package.json at build time. Keeping
|
|
18917
20285
|
// the fallback in sync lets tests require src/workbench.js directly.
|
|
18918
|
-
const CODELAB_VERSION = '0.1.
|
|
20286
|
+
const CODELAB_VERSION = '0.1.13';
|
|
18919
20287
|
|
|
18920
20288
|
// Ambient TypeScript declarations for Node.js built-ins inside Monaco
|
|
18921
20289
|
const NODE_AMBIENT_DTS = `
|
|
@@ -20439,6 +21807,7 @@ declare module 'bun:sqlite' {
|
|
|
20439
21807
|
this.logger.debug('Could not parse portTable dispatch URL.', err);
|
|
20440
21808
|
}
|
|
20441
21809
|
const method = String((init && init.method) || 'GET').toUpperCase();
|
|
21810
|
+
const fromPort = (init && init._fromPort) ? Number(init._fromPort) : null;
|
|
20442
21811
|
try {
|
|
20443
21812
|
const res = await origDispatch(url, init);
|
|
20444
21813
|
const durationMs = Math.max(0.1, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0);
|
|
@@ -20464,8 +21833,9 @@ declare module 'bun:sqlite' {
|
|
|
20464
21833
|
try {
|
|
20465
21834
|
formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
|
|
20466
21835
|
} catch (err) {
|
|
20467
|
-
|
|
21836
|
+
this.logger.debug('Response body is not JSON.', err);
|
|
20468
21837
|
}
|
|
21838
|
+
const chaosEffect = (res && res._chaosEffect) || responseHeaders['x-codelab-chaos'] || null;
|
|
20469
21839
|
if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
|
|
20470
21840
|
this.lastHttpTrace.push({
|
|
20471
21841
|
id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
|
|
@@ -20474,6 +21844,8 @@ declare module 'bun:sqlite' {
|
|
|
20474
21844
|
url: reqPath,
|
|
20475
21845
|
fullUrl,
|
|
20476
21846
|
port: parsedPort,
|
|
21847
|
+
fromPort,
|
|
21848
|
+
chaosEffect,
|
|
20477
21849
|
status: (res && res.status) || 200,
|
|
20478
21850
|
statusText: (res && res.statusText) || 'OK',
|
|
20479
21851
|
durationMs,
|
|
@@ -20484,8 +21856,34 @@ declare module 'bun:sqlite' {
|
|
|
20484
21856
|
responseBody: bodyText,
|
|
20485
21857
|
formattedBody
|
|
20486
21858
|
});
|
|
21859
|
+
const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
|
|
21860
|
+
if (netPill) netPill.textContent = `${this.lastHttpTrace.length} reqs`;
|
|
20487
21861
|
return res;
|
|
20488
21862
|
} catch (err) {
|
|
21863
|
+
const durationMs = Math.max(0.1, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0);
|
|
21864
|
+
if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
|
|
21865
|
+
const errMsg = String((err && err.message) || err);
|
|
21866
|
+
this.lastHttpTrace.push({
|
|
21867
|
+
id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
|
|
21868
|
+
timestamp: new Date().toLocaleTimeString(),
|
|
21869
|
+
method,
|
|
21870
|
+
url: reqPath,
|
|
21871
|
+
fullUrl,
|
|
21872
|
+
port: parsedPort,
|
|
21873
|
+
fromPort,
|
|
21874
|
+
chaosEffect: (err && err.chaosEffect) || (err && err.code) || 'ERROR',
|
|
21875
|
+
status: 0,
|
|
21876
|
+
statusText: (err && (err.chaosEffect || err.code)) || 'ERROR',
|
|
21877
|
+
durationMs,
|
|
21878
|
+
size: 0,
|
|
21879
|
+
requestHeaders: (init && init.headers) || {},
|
|
21880
|
+
requestBody: (init && init.body) || '',
|
|
21881
|
+
responseHeaders: {},
|
|
21882
|
+
responseBody: errMsg,
|
|
21883
|
+
formattedBody: errMsg
|
|
21884
|
+
});
|
|
21885
|
+
const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
|
|
21886
|
+
if (netPill) netPill.textContent = `${this.lastHttpTrace.length} reqs`;
|
|
20489
21887
|
throw err;
|
|
20490
21888
|
}
|
|
20491
21889
|
};
|
|
@@ -22583,10 +23981,10 @@ declare module 'bun:sqlite' {
|
|
|
22583
23981
|
|
|
22584
23982
|
if (isFirstToken) {
|
|
22585
23983
|
const commands = [
|
|
22586
|
-
'
|
|
22587
|
-
'
|
|
22588
|
-
'
|
|
22589
|
-
'uniq', 'unset', 'wc', 'which', '
|
|
23984
|
+
'ab', 'bun', 'cat', 'cd', 'chaos', 'clear', 'cp', 'curl', 'echo', 'env',
|
|
23985
|
+
'export', 'find', 'grep', 'head', 'help', 'hey', 'history', 'jobs', 'kill',
|
|
23986
|
+
'ls', 'mkdir', 'mv', 'node', 'npm', 'npx', 'ps', 'pwd', 'redis-cli', 'rm',
|
|
23987
|
+
'sed', 'sort', 'sqlite3', 'tail', 'touch', 'uniq', 'unset', 'wc', 'which', 'wrk'
|
|
22590
23988
|
];
|
|
22591
23989
|
return commands.filter(c => c.startsWith(token));
|
|
22592
23990
|
} else {
|
|
@@ -22647,25 +24045,53 @@ declare module 'bun:sqlite' {
|
|
|
22647
24045
|
<th>Host / URL</th>
|
|
22648
24046
|
<th>Protocol</th>
|
|
22649
24047
|
<th>Process / Service</th>
|
|
22650
|
-
<th>Status</th>
|
|
22651
|
-
<th style="text-align:right;">Actions</th>
|
|
24048
|
+
<th>Status & Chaos</th>
|
|
24049
|
+
<th style="text-align:right;">Chaos Injection & Actions</th>
|
|
22652
24050
|
</tr>
|
|
22653
24051
|
</thead>
|
|
22654
24052
|
<tbody>
|
|
22655
|
-
${servers.map(s =>
|
|
24053
|
+
${servers.map(s => {
|
|
24054
|
+
const rule = (this.portTable && typeof this.portTable.getChaosRule === 'function')
|
|
24055
|
+
? this.portTable.getChaosRule(s.port)
|
|
24056
|
+
: null;
|
|
24057
|
+
const isCrashed = Boolean(rule && rule.crashed);
|
|
24058
|
+
const hasLat = Boolean(rule && rule.latencyMs > 0);
|
|
24059
|
+
const hasErr = Boolean(rule && rule.errorRate > 0);
|
|
24060
|
+
const hasDrop = Boolean(rule && rule.dropRate > 0);
|
|
24061
|
+
const hasAnyChaos = isCrashed || hasLat || hasErr || hasDrop || Boolean(rule && rule.partitionFromPorts && rule.partitionFromPorts.length);
|
|
24062
|
+
const chaosPills = [];
|
|
24063
|
+
if (isCrashed) chaosPills.push(`<span class="codelab-chaos-badge codelab-chaos-badge--danger">CRASHED</span>`);
|
|
24064
|
+
if (hasLat) chaosPills.push(`<span class="codelab-chaos-badge codelab-chaos-badge--warn">+${rule.latencyMs}ms</span>`);
|
|
24065
|
+
if (hasErr) chaosPills.push(`<span class="codelab-chaos-badge codelab-chaos-badge--danger">${Math.round(rule.errorRate * 100)}% HTTP ${rule.errorStatus || 503}</span>`);
|
|
24066
|
+
if (hasDrop) chaosPills.push(`<span class="codelab-chaos-badge codelab-chaos-badge--danger">${Math.round(rule.dropRate * 100)}% DROP</span>`);
|
|
24067
|
+
return `
|
|
22656
24068
|
<tr>
|
|
22657
24069
|
<td><span class="codelab-port-tag">${s.port}</span></td>
|
|
22658
24070
|
<td><a href="http://127.0.0.1:${s.port}/" target="_blank" class="codelab-port-link">http://127.0.0.1:${s.port}/</a></td>
|
|
22659
24071
|
<td><span class="codelab-badge">${escapeHtml(s.protocol || 'HTTP/1.1')}</span></td>
|
|
22660
24072
|
<td><code>${escapeHtml(s.service || (s.pid ? `PID ${s.pid}` : 'node'))}</code></td>
|
|
22661
|
-
<td
|
|
24073
|
+
<td>
|
|
24074
|
+
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
|
|
24075
|
+
<span class="codelab-port-status ${isCrashed ? 'codelab-port-status--crashed' : 'codelab-port-status--listening'}">
|
|
24076
|
+
<span class="codelab-port-status-dot"></span>${isCrashed ? 'CRASHED' : 'LISTENING'}
|
|
24077
|
+
</span>
|
|
24078
|
+
${chaosPills.join('')}
|
|
24079
|
+
</div>
|
|
24080
|
+
</td>
|
|
22662
24081
|
<td style="text-align:right;white-space:nowrap;">
|
|
24082
|
+
<span class="codelab-chaos-btn-group" title="Inject network faults on port :${s.port}">
|
|
24083
|
+
<button type="button" class="codelab-btn codelab-btn--sm ${hasLat ? 'codelab-btn--chaos-active' : ''}" data-cl-action="chaos-latency" data-port="${s.port}" title="Toggle +200ms network latency on :${s.port}">+200ms</button>
|
|
24084
|
+
<button type="button" class="codelab-btn codelab-btn--sm ${hasErr ? 'codelab-btn--chaos-active' : ''}" data-cl-action="chaos-error" data-port="${s.port}" title="Toggle 25% HTTP 503 error rate on :${s.port}">25% 503</button>
|
|
24085
|
+
<button type="button" class="codelab-btn codelab-btn--sm ${isCrashed ? 'codelab-btn--danger' : ''}" data-cl-action="chaos-crash" data-port="${s.port}" title="Simulate node crash (ECONNREFUSED) on :${s.port}">${isCrashed ? 'Recover' : 'Crash'}</button>
|
|
24086
|
+
${hasAnyChaos ? `<button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="chaos-heal" data-port="${s.port}" title="Heal all chaos rules on :${s.port}">Heal</button>` : ''}
|
|
24087
|
+
</span>
|
|
22663
24088
|
<button type="button" class="codelab-btn codelab-btn--sm codelab-btn--primary" data-cl-action="open-web-preview" data-port="${s.port}" data-cl-port="${s.port}">Preview</button>
|
|
22664
24089
|
<button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="open-port-client" data-port="${s.port}" data-cl-port="${s.port}">Open in Client</button>
|
|
22665
24090
|
<button type="button" class="codelab-btn codelab-btn--sm codelab-btn--danger" data-cl-action="stop-port" data-port="${s.port}" data-cl-port="${s.port}">Stop</button>
|
|
22666
24091
|
</td>
|
|
22667
24092
|
</tr>
|
|
22668
|
-
|
|
24093
|
+
`;
|
|
24094
|
+
}).join('')}
|
|
22669
24095
|
</tbody>
|
|
22670
24096
|
</table>
|
|
22671
24097
|
</div>
|
|
@@ -22718,7 +24144,7 @@ declare module 'bun:sqlite' {
|
|
|
22718
24144
|
<div class="codelab-ports-panel">
|
|
22719
24145
|
<div class="codelab-panel-section">
|
|
22720
24146
|
<div class="codelab-section-title">
|
|
22721
|
-
<span>${CL_ICONS.radio || ''} Active Port Listeners</span>
|
|
24147
|
+
<span>${CL_ICONS.radio || ''} Active Port Listeners & Chaos Controls</span>
|
|
22722
24148
|
<span class="codelab-badge">${servers.length} listening</span>
|
|
22723
24149
|
</div>
|
|
22724
24150
|
${serversHtml}
|
|
@@ -22803,6 +24229,85 @@ declare module 'bun:sqlite' {
|
|
|
22803
24229
|
const traces = Array.isArray(this.lastHttpTrace) ? this.lastHttpTrace : [];
|
|
22804
24230
|
const filter = this.networkFilter;
|
|
22805
24231
|
|
|
24232
|
+
// Compute SLO & Latency Percentiles across all captured traces
|
|
24233
|
+
const totalReqs = traces.length;
|
|
24234
|
+
let count2xx = 0;
|
|
24235
|
+
let count429 = 0;
|
|
24236
|
+
let count5xxOrErr = 0;
|
|
24237
|
+
const sortedDurations = traces.map(t => Number(t.durationMs || 0)).sort((a, b) => a - b);
|
|
24238
|
+
for (const t of traces) {
|
|
24239
|
+
const st = Number(t.status || 0);
|
|
24240
|
+
if (st >= 200 && st < 300) count2xx++;
|
|
24241
|
+
else if (st === 429) count429++;
|
|
24242
|
+
else if (st >= 500 || st === 0) count5xxOrErr++;
|
|
24243
|
+
}
|
|
24244
|
+
const pctLat = (p) => {
|
|
24245
|
+
if (!sortedDurations.length) return '0.0';
|
|
24246
|
+
const idx = Math.min(sortedDurations.length - 1, Math.floor((p / 100) * sortedDurations.length));
|
|
24247
|
+
return sortedDurations[idx].toFixed(1);
|
|
24248
|
+
};
|
|
24249
|
+
const okPct = totalReqs > 0 ? ((count2xx / totalReqs) * 100).toFixed(1) : '100.0';
|
|
24250
|
+
const p50Ms = pctLat(50);
|
|
24251
|
+
const p95Ms = pctLat(95);
|
|
24252
|
+
const p99Ms = pctLat(99);
|
|
24253
|
+
|
|
24254
|
+
// Build Live Service Topology & Chaos Map
|
|
24255
|
+
const servers = (this.portTable && typeof this.portTable.listServers === 'function')
|
|
24256
|
+
? this.portTable.listServers()
|
|
24257
|
+
: [];
|
|
24258
|
+
const edgeMap = new Map();
|
|
24259
|
+
for (const t of traces) {
|
|
24260
|
+
const src = t.fromPort ? `:${t.fromPort}` : 'Client';
|
|
24261
|
+
const dst = `:${t.port || 3000}`;
|
|
24262
|
+
const key = `${src}→${dst}`;
|
|
24263
|
+
const cur = edgeMap.get(key) || { src, dst, targetPort: Number(t.port || 3000), count: 0, errCount: 0, totalMs: 0 };
|
|
24264
|
+
cur.count++;
|
|
24265
|
+
if (Number(t.status || 0) >= 500 || Number(t.status || 0) === 0) cur.errCount++;
|
|
24266
|
+
cur.totalMs += Number(t.durationMs || 0);
|
|
24267
|
+
edgeMap.set(key, cur);
|
|
24268
|
+
}
|
|
24269
|
+
|
|
24270
|
+
let topologyHtml = '';
|
|
24271
|
+
if (servers.length > 0 || edgeMap.size > 0) {
|
|
24272
|
+
const edgePills = Array.from(edgeMap.values()).map(e => {
|
|
24273
|
+
const avg = (e.totalMs / Math.max(1, e.count)).toFixed(1);
|
|
24274
|
+
const hasErrors = e.errCount > 0;
|
|
24275
|
+
return `
|
|
24276
|
+
<span class="codelab-topo-edge ${hasErrors ? 'codelab-topo-edge--err' : ''}">
|
|
24277
|
+
<strong>${escapeHtml(e.src)}</strong>
|
|
24278
|
+
<span class="codelab-topo-arrow">──(${e.count} req · ${avg}ms${hasErrors ? ` · ${e.errCount} err` : ''})──▶</span>
|
|
24279
|
+
<strong>${escapeHtml(e.dst)}</strong>
|
|
24280
|
+
</span>
|
|
24281
|
+
`;
|
|
24282
|
+
}).join('');
|
|
24283
|
+
|
|
24284
|
+
const nodePills = servers.map(s => {
|
|
24285
|
+
const rule = (this.portTable && typeof this.portTable.getChaosRule === 'function')
|
|
24286
|
+
? this.portTable.getChaosRule(s.port)
|
|
24287
|
+
: null;
|
|
24288
|
+
const isCrashed = Boolean(rule && rule.crashed);
|
|
24289
|
+
const hasLat = Boolean(rule && rule.latencyMs > 0);
|
|
24290
|
+
const hasErr = Boolean(rule && rule.errorRate > 0);
|
|
24291
|
+
return `
|
|
24292
|
+
<span class="codelab-topo-node ${isCrashed ? 'is-crashed' : (hasLat || hasErr ? 'is-degraded' : 'is-healthy')}">
|
|
24293
|
+
<span class="codelab-port-status-dot"></span>
|
|
24294
|
+
<code>:${s.port}</code>
|
|
24295
|
+
<span>${escapeHtml(s.service || 'node')}</span>
|
|
24296
|
+
${isCrashed ? '<span class="codelab-chaos-badge codelab-chaos-badge--danger">CRASHED</span>' : ''}
|
|
24297
|
+
${hasLat ? `<span class="codelab-chaos-badge codelab-chaos-badge--warn">+${rule.latencyMs}ms</span>` : ''}
|
|
24298
|
+
${hasErr ? `<span class="codelab-chaos-badge codelab-chaos-badge--danger">${Math.round(rule.errorRate * 100)}% ${rule.errorStatus || 503}</span>` : ''}
|
|
24299
|
+
</span>
|
|
24300
|
+
`;
|
|
24301
|
+
}).join('');
|
|
24302
|
+
|
|
24303
|
+
topologyHtml = `
|
|
24304
|
+
<div class="codelab-topo-bar">
|
|
24305
|
+
<div class="codelab-topo-nodes">${nodePills || '<span style="font-size:11px;color:var(--cl-fg-muted);">No listening servers</span>'}</div>
|
|
24306
|
+
${edgePills ? `<div class="codelab-topo-edges">${edgePills}</div>` : ''}
|
|
24307
|
+
</div>
|
|
24308
|
+
`;
|
|
24309
|
+
}
|
|
24310
|
+
|
|
22806
24311
|
const filtered = traces.filter(t => {
|
|
22807
24312
|
if (filter.method && filter.method !== 'ALL' && (t.method || 'GET').toUpperCase() !== filter.method) return false;
|
|
22808
24313
|
if (filter.status && filter.status !== 'ALL') {
|
|
@@ -22810,7 +24315,7 @@ declare module 'bun:sqlite' {
|
|
|
22810
24315
|
if (filter.status === '2xx' && (s < 200 || s >= 300)) return false;
|
|
22811
24316
|
if (filter.status === '3xx' && (s < 300 || s >= 400)) return false;
|
|
22812
24317
|
if (filter.status === '4xx' && (s < 400 || s >= 500)) return false;
|
|
22813
|
-
if (filter.status === '5xx' && (s < 500
|
|
24318
|
+
if (filter.status === '5xx' && (s < 500 && s !== 0)) return false;
|
|
22814
24319
|
}
|
|
22815
24320
|
if (filter.search) {
|
|
22816
24321
|
const query = filter.search.toLowerCase();
|
|
@@ -22829,23 +24334,26 @@ declare module 'bun:sqlite' {
|
|
|
22829
24334
|
rowsHtml = `
|
|
22830
24335
|
<tr>
|
|
22831
24336
|
<td colspan="7" style="text-align:center;padding:32px;color:var(--cl-fg-muted);">
|
|
22832
|
-
${traces.length === 0 ? 'No network requests recorded yet. Run a demo,
|
|
24337
|
+
${traces.length === 0 ? 'No network requests recorded yet. Run a demo, click "⚡ Load Test", or run `hey -n 50 http://localhost:3000` in the terminal.' : 'No network requests match the active filters.'}
|
|
22833
24338
|
</td>
|
|
22834
24339
|
</tr>
|
|
22835
24340
|
`;
|
|
22836
24341
|
} else {
|
|
22837
24342
|
const maxDuration = Math.max(1, ...filtered.map(t => t.durationMs || 1));
|
|
22838
24343
|
rowsHtml = filtered.map(t => {
|
|
22839
|
-
const status = Number(t.status ||
|
|
22840
|
-
const
|
|
24344
|
+
const status = Number(t.status || 0);
|
|
24345
|
+
const statusLabel = status === 0 ? (t.statusText || 'ERR') : String(status);
|
|
24346
|
+
const statusClass = status === 0 ? 'status-5xx' : (status < 300 ? 'status-2xx' : (status < 400 ? 'status-3xx' : (status < 500 ? 'status-4xx' : 'status-5xx')));
|
|
22841
24347
|
const widthPct = Math.min(100, Math.max(8, Math.round(((t.durationMs || 1) / maxDuration) * 100)));
|
|
22842
24348
|
const isSelected = selectedTrace && String(selectedTrace.id) === String(t.id);
|
|
24349
|
+
const hopLabel = t.fromPort ? `:${t.fromPort}→:${t.port || 3000}` : `:${t.port || 3000}`;
|
|
24350
|
+
const chaosChip = t.chaosEffect ? `<span class="codelab-chaos-badge codelab-chaos-badge--warn" style="margin-left:4px;">${escapeHtml(String(t.chaosEffect))}</span>` : '';
|
|
22843
24351
|
return `
|
|
22844
24352
|
<tr class="codelab-net-row ${isSelected ? 'selected' : ''}" data-cl-action="select-net-trace" data-trace-id="${escapeHtml(t.id || '')}" data-cl-trace-id="${escapeHtml(t.id || '')}">
|
|
22845
|
-
<td><span class="codelab-status-badge ${statusClass}">${
|
|
24353
|
+
<td><span class="codelab-status-badge ${statusClass}">${escapeHtml(statusLabel)}</span>${chaosChip}</td>
|
|
22846
24354
|
<td><span class="codelab-method-badge codelab-method-${(t.method || 'GET').toLowerCase()}">${escapeHtml(t.method || 'GET')}</span></td>
|
|
22847
24355
|
<td class="codelab-net-path" title="${escapeHtml(t.url || '/')}">${escapeHtml(t.url || '/')}</td>
|
|
22848
|
-
<td><code>${
|
|
24356
|
+
<td><code>${escapeHtml(hopLabel)}</code></td>
|
|
22849
24357
|
<td style="white-space:nowrap;font-family:var(--cl-font-mono);font-size:11.5px;">${(t.durationMs || 0).toFixed(1)} ms</td>
|
|
22850
24358
|
<td style="white-space:nowrap;font-family:var(--cl-font-mono);font-size:11.5px;">${t.size != null ? t.size : 0} B</td>
|
|
22851
24359
|
<td class="codelab-waterfall-cell">
|
|
@@ -22879,6 +24387,8 @@ declare module 'bun:sqlite' {
|
|
|
22879
24387
|
<div class="codelab-net-detail__section">
|
|
22880
24388
|
<div class="codelab-detail-label">General</div>
|
|
22881
24389
|
<div class="codelab-detail-kv"><strong>URL:</strong> 127.0.0.1:${selectedTrace.port}${escapeHtml(selectedTrace.url || '/')}</div>
|
|
24390
|
+
${selectedTrace.fromPort ? `<div class="codelab-detail-kv"><strong>Caller Port:</strong> :${selectedTrace.fromPort}</div>` : ''}
|
|
24391
|
+
${selectedTrace.chaosEffect ? `<div class="codelab-detail-kv"><strong>Chaos Fault:</strong> ${escapeHtml(String(selectedTrace.chaosEffect))}</div>` : ''}
|
|
22882
24392
|
<div class="codelab-detail-kv"><strong>Status:</strong> ${selectedTrace.status} ${escapeHtml(selectedTrace.statusText || '')}</div>
|
|
22883
24393
|
<div class="codelab-detail-kv"><strong>Duration:</strong> ${(selectedTrace.durationMs || 0).toFixed(2)} ms</div>
|
|
22884
24394
|
<div class="codelab-detail-kv"><strong>Size:</strong> ${selectedTrace.size || 0} bytes</div>
|
|
@@ -22908,8 +24418,42 @@ declare module 'bun:sqlite' {
|
|
|
22908
24418
|
|
|
22909
24419
|
bodyEl.innerHTML = `
|
|
22910
24420
|
<div class="codelab-network-panel ${selectedTrace ? 'has-detail' : ''}">
|
|
24421
|
+
<div class="codelab-slo-bar" role="region" aria-label="SLO and Latency Telemetry">
|
|
24422
|
+
<div class="codelab-slo-metric">
|
|
24423
|
+
<span class="codelab-slo-label">Requests</span>
|
|
24424
|
+
<span class="codelab-slo-val">${totalReqs}</span>
|
|
24425
|
+
</div>
|
|
24426
|
+
<div class="codelab-slo-metric">
|
|
24427
|
+
<span class="codelab-slo-label">2xx SLO</span>
|
|
24428
|
+
<span class="codelab-slo-val ${Number(okPct) < 95 && totalReqs > 0 ? 'is-warn' : 'is-ok'}">${okPct}%</span>
|
|
24429
|
+
</div>
|
|
24430
|
+
<div class="codelab-slo-metric">
|
|
24431
|
+
<span class="codelab-slo-label">429 Throttled</span>
|
|
24432
|
+
<span class="codelab-slo-val ${count429 > 0 ? 'is-warn' : ''}">${count429}</span>
|
|
24433
|
+
</div>
|
|
24434
|
+
<div class="codelab-slo-metric">
|
|
24435
|
+
<span class="codelab-slo-label">5xx / Faults</span>
|
|
24436
|
+
<span class="codelab-slo-val ${count5xxOrErr > 0 ? 'is-err' : ''}">${count5xxOrErr}</span>
|
|
24437
|
+
</div>
|
|
24438
|
+
<div class="codelab-slo-metric">
|
|
24439
|
+
<span class="codelab-slo-label">p50</span>
|
|
24440
|
+
<span class="codelab-slo-val">${p50Ms} ms</span>
|
|
24441
|
+
</div>
|
|
24442
|
+
<div class="codelab-slo-metric">
|
|
24443
|
+
<span class="codelab-slo-label">p95</span>
|
|
24444
|
+
<span class="codelab-slo-val">${p95Ms} ms</span>
|
|
24445
|
+
</div>
|
|
24446
|
+
<div class="codelab-slo-metric">
|
|
24447
|
+
<span class="codelab-slo-label">p99</span>
|
|
24448
|
+
<span class="codelab-slo-val">${p99Ms} ms</span>
|
|
24449
|
+
</div>
|
|
24450
|
+
<div style="margin-left:auto;display:flex;align-items:center;gap:6px;">
|
|
24451
|
+
<button type="button" class="codelab-btn codelab-btn--sm codelab-btn--primary" data-cl-action="run-quick-loadtest" title="Run 50 concurrent requests (hey -n 50 -c 10) against active server">⚡ Load Test (50 reqs)</button>
|
|
24452
|
+
</div>
|
|
24453
|
+
</div>
|
|
24454
|
+
${topologyHtml}
|
|
22911
24455
|
<div class="codelab-net-toolbar">
|
|
22912
|
-
<input type="text" class="codelab-input" id="cl-net-search" placeholder="Filter URL or method..." value="${escapeHtml(filter.search)}" aria-label="Filter network traces">
|
|
24456
|
+
<input type="text" class="codelab-input" id="cl-net-search" placeholder="Filter URL, port, or method..." value="${escapeHtml(filter.search)}" aria-label="Filter network traces">
|
|
22913
24457
|
<select class="codelab-select" id="cl-net-method" aria-label="Filter by method">
|
|
22914
24458
|
<option value="ALL" ${filter.method === 'ALL' ? 'selected' : ''}>All Methods</option>
|
|
22915
24459
|
<option value="GET" ${filter.method === 'GET' ? 'selected' : ''}>GET</option>
|
|
@@ -22923,7 +24467,7 @@ declare module 'bun:sqlite' {
|
|
|
22923
24467
|
<option value="2xx" ${filter.status === '2xx' ? 'selected' : ''}>2xx Success</option>
|
|
22924
24468
|
<option value="3xx" ${filter.status === '3xx' ? 'selected' : ''}>3xx Redirect</option>
|
|
22925
24469
|
<option value="4xx" ${filter.status === '4xx' ? 'selected' : ''}>4xx Client Error</option>
|
|
22926
|
-
<option value="5xx" ${filter.status === '5xx' ? 'selected' : ''}>5xx
|
|
24470
|
+
<option value="5xx" ${filter.status === '5xx' ? 'selected' : ''}>5xx / Network Fault</option>
|
|
22927
24471
|
</select>
|
|
22928
24472
|
<button type="button" class="codelab-btn" data-cl-action="clear-net-traces">Clear</button>
|
|
22929
24473
|
<span style="margin-left:auto;font-size:11.5px;color:var(--cl-fg-muted);">${filtered.length} of ${traces.length} requests</span>
|
|
@@ -22933,10 +24477,10 @@ declare module 'bun:sqlite' {
|
|
|
22933
24477
|
<table class="codelab-net-table">
|
|
22934
24478
|
<thead>
|
|
22935
24479
|
<tr>
|
|
22936
|
-
<th style="width:
|
|
24480
|
+
<th style="width:85px;">Status</th>
|
|
22937
24481
|
<th style="width:65px;">Method</th>
|
|
22938
24482
|
<th>Path</th>
|
|
22939
|
-
<th style="width:
|
|
24483
|
+
<th style="width:95px;">Route</th>
|
|
22940
24484
|
<th style="width:75px;">Time</th>
|
|
22941
24485
|
<th style="width:70px;">Size</th>
|
|
22942
24486
|
<th style="width:140px;">Waterfall</th>
|
|
@@ -23134,6 +24678,9 @@ declare module 'bun:sqlite' {
|
|
|
23134
24678
|
if (this.drawerTab === 'ports') this._renderDrawerBody();
|
|
23135
24679
|
this._dismissPortToast(port);
|
|
23136
24680
|
}));
|
|
24681
|
+
this._portListenerUnsubs.push(this.portTable.on('chaos', () => {
|
|
24682
|
+
if (this.drawerTab === 'ports' || this.drawerTab === 'network') this._renderDrawerBody();
|
|
24683
|
+
}));
|
|
23137
24684
|
} catch (err) {
|
|
23138
24685
|
this.logger.warn('Failed to attach portTable event listeners.', err);
|
|
23139
24686
|
}
|
|
@@ -25076,6 +26623,43 @@ declare module 'bun:sqlite' {
|
|
|
25076
26623
|
this.networkFilter.selectedTraceId = null;
|
|
25077
26624
|
}
|
|
25078
26625
|
this._renderDrawerBody();
|
|
26626
|
+
} else if (action === 'chaos-latency' || action === 'chaos-error' || action === 'chaos-crash' || action === 'chaos-heal') {
|
|
26627
|
+
const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
|
|
26628
|
+
if (port && this.portTable && typeof this.portTable.setChaosRule === 'function') {
|
|
26629
|
+
const cur = (typeof this.portTable.getChaosRule === 'function' ? this.portTable.getChaosRule(port) : null) || {};
|
|
26630
|
+
if (action === 'chaos-latency') {
|
|
26631
|
+
const nextLat = cur.latencyMs > 0 ? 0 : 200;
|
|
26632
|
+
this.portTable.setChaosRule(port, { latencyMs: nextLat, jitterMs: nextLat ? 40 : 0 });
|
|
26633
|
+
this._showToast(nextLat ? `Injected +200ms latency (±40ms jitter) on :${port}` : `Removed latency injection on :${port}`, 'info');
|
|
26634
|
+
} else if (action === 'chaos-error') {
|
|
26635
|
+
const nextErr = cur.errorRate > 0 ? 0 : 0.25;
|
|
26636
|
+
this.portTable.setChaosRule(port, { errorRate: nextErr, errorStatus: 503 });
|
|
26637
|
+
this._showToast(nextErr ? `Injected 25% HTTP 503 error rate on :${port}` : `Removed HTTP 503 fault injection on :${port}`, nextErr ? 'error' : 'info');
|
|
26638
|
+
} else if (action === 'chaos-crash') {
|
|
26639
|
+
const nextCrash = !cur.crashed;
|
|
26640
|
+
this.portTable.setChaosRule(port, { crashed: nextCrash });
|
|
26641
|
+
this._showToast(nextCrash ? `Port :${port} marked CRASHED (ECONNREFUSED)` : `Port :${port} recovered`, nextCrash ? 'error' : 'info');
|
|
26642
|
+
} else if (action === 'chaos-heal') {
|
|
26643
|
+
this.portTable.clearChaosRules(port);
|
|
26644
|
+
this._showToast(`Port :${port} healed (all fault rules cleared)`, 'info');
|
|
26645
|
+
}
|
|
26646
|
+
this._renderDrawerBody();
|
|
26647
|
+
}
|
|
26648
|
+
} else if (action === 'run-quick-loadtest') {
|
|
26649
|
+
const targetPort = this._firstListeningPort() || 3000;
|
|
26650
|
+
const targetUrl = `http://127.0.0.1:${targetPort}/`;
|
|
26651
|
+
if (this.shell && typeof this.shell.execute === 'function') {
|
|
26652
|
+
this._showToast(`Running load test: hey -n 50 -c 10 ${targetUrl}`, 'info');
|
|
26653
|
+
this.shell.execute(`hey -n 50 -c 10 ${targetUrl}`, {}).then((res) => {
|
|
26654
|
+
if (res && res.stdout) {
|
|
26655
|
+
this.terminalLogs.push({ type: 'system', text: `\n$ hey -n 50 -c 10 ${targetUrl}` });
|
|
26656
|
+
this.terminalLogs.push({ type: 'stdout', text: res.stdout.replace(/\n$/, '') });
|
|
26657
|
+
}
|
|
26658
|
+
this._renderDrawerBody();
|
|
26659
|
+
}).catch((err) => {
|
|
26660
|
+
this.logger.debug('Quick load test failed.', err);
|
|
26661
|
+
});
|
|
26662
|
+
}
|
|
25079
26663
|
}
|
|
25080
26664
|
return;
|
|
25081
26665
|
}
|
|
@@ -27417,6 +29001,7 @@ const createVirtualFs = CodeLabRuntime.createVirtualFs;
|
|
|
27417
29001
|
const createVirtualHttp = CodeLabRuntime.createVirtualHttp;
|
|
27418
29002
|
const createVirtualNet = CodeLabRuntime.createVirtualNet;
|
|
27419
29003
|
const createVirtualPortTable = CodeLabRuntime.createVirtualPortTable;
|
|
29004
|
+
const createSqliteDatabase = CodeLabRuntime.createSqliteDatabase;
|
|
27420
29005
|
const createWorkerRuntimeSource = CodeLabRuntime.createWorkerRuntimeSource;
|
|
27421
29006
|
const createPosixShell = CodeLabShell ? CodeLabShell.createPosixShell : null;
|
|
27422
29007
|
const cloneGitHubRepository = CodeLabShell ? CodeLabShell.cloneGitHubRepository : null;
|
|
@@ -27428,7 +29013,7 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
|
|
|
27428
29013
|
const mount = CodeLab ? CodeLab.mount : null;
|
|
27429
29014
|
const create = CodeLab ? CodeLab.create : null;
|
|
27430
29015
|
const unmount = CodeLab ? CodeLab.unmount : null;
|
|
27431
|
-
const version = CodeLab ? CodeLab.version : '0.1.
|
|
29016
|
+
const version = CodeLab ? CodeLab.version : '0.1.13';
|
|
27432
29017
|
const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
|
|
27433
29018
|
const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
|
|
27434
29019
|
const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;
|
|
@@ -27547,6 +29132,7 @@ export {
|
|
|
27547
29132
|
createVirtualHttp,
|
|
27548
29133
|
createVirtualNet,
|
|
27549
29134
|
createVirtualPortTable,
|
|
29135
|
+
createSqliteDatabase,
|
|
27550
29136
|
createWorkerRuntimeSource
|
|
27551
29137
|
};
|
|
27552
29138
|
export default CodeLab;
|