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