@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/src/runtime.ts CHANGED
@@ -2492,6 +2492,7 @@ function __initVirtualRuntime(rootScope) {
2492
2492
  function createVirtualPortTable() {
2493
2493
  const table = new Map();
2494
2494
  const listeners = new Map(); // event name -> Set<Function>
2495
+ const chaosRules = new Map(); // port -> ChaosRule
2495
2496
 
2496
2497
  function emit(event, ...args) {
2497
2498
  const set = listeners.get(event);
@@ -2507,6 +2508,43 @@ function __initVirtualRuntime(rootScope) {
2507
2508
  }
2508
2509
  }
2509
2510
 
2511
+ function normalizeChaosRule(port, partial = {}, existing = null) {
2512
+ const p = Number(port);
2513
+ const base = existing || {
2514
+ port: p,
2515
+ latencyMs: 0,
2516
+ jitterMs: 0,
2517
+ dropRate: 0,
2518
+ errorRate: 0,
2519
+ statusCode: 503,
2520
+ partitionFromPorts: [],
2521
+ crashed: false
2522
+ };
2523
+ const merged = Object.assign({}, base, partial, { port: p });
2524
+ merged.latencyMs = Math.max(0, Number(merged.latencyMs) || 0);
2525
+ merged.jitterMs = Math.max(0, Number(merged.jitterMs) || 0);
2526
+ merged.dropRate = Math.max(0, Math.min(1, Number(merged.dropRate) || 0));
2527
+ merged.errorRate = Math.max(0, Math.min(1, Number(merged.errorRate) || 0));
2528
+ merged.statusCode = Number(merged.statusCode) || 503;
2529
+ merged.partitionFromPorts = Array.isArray(merged.partitionFromPorts)
2530
+ ? Array.from(new Set(merged.partitionFromPorts.map(Number).filter((n) => Number.isFinite(n) && n > 0)))
2531
+ : [];
2532
+ merged.crashed = Boolean(merged.crashed);
2533
+ return merged;
2534
+ }
2535
+
2536
+ function isRuleActive(rule) {
2537
+ if (!rule) return false;
2538
+ return Boolean(
2539
+ rule.crashed ||
2540
+ rule.latencyMs > 0 ||
2541
+ rule.jitterMs > 0 ||
2542
+ rule.dropRate > 0 ||
2543
+ rule.errorRate > 0 ||
2544
+ (Array.isArray(rule.partitionFromPorts) && rule.partitionFromPorts.length > 0)
2545
+ );
2546
+ }
2547
+
2510
2548
  return {
2511
2549
  on(event, fn) {
2512
2550
  if (typeof fn !== 'function') return () => {};
@@ -2572,22 +2610,125 @@ function __initVirtualRuntime(rootScope) {
2572
2610
  listServers() {
2573
2611
  return Array.from(table.values());
2574
2612
  },
2613
+ setChaosRule(port, partial = {}) {
2614
+ const p = Number(port);
2615
+ const updated = normalizeChaosRule(p, partial, chaosRules.get(p) || null);
2616
+ if (isRuleActive(updated)) {
2617
+ chaosRules.set(p, updated);
2618
+ } else {
2619
+ chaosRules.delete(p);
2620
+ }
2621
+ emit('chaos', p, updated);
2622
+ return updated;
2623
+ },
2624
+ getChaosRule(port) {
2625
+ return chaosRules.get(Number(port)) || null;
2626
+ },
2627
+ listChaosRules() {
2628
+ return Array.from(chaosRules.values());
2629
+ },
2630
+ clearChaosRules(port) {
2631
+ if (port !== undefined && port !== null && port !== '') {
2632
+ const p = Number(port);
2633
+ const deleted = chaosRules.delete(p);
2634
+ emit('chaos', p, null);
2635
+ return deleted;
2636
+ }
2637
+ chaosRules.clear();
2638
+ emit('chaos', null, null);
2639
+ return true;
2640
+ },
2575
2641
  async dispatchRequest(url, init = {}) {
2576
2642
  const parsed = new URL(url);
2577
2643
  const port = Number(parsed.port || (parsed.protocol === 'https:' ? 443 : 80));
2644
+ const rawHdrs = (init && init.headers) || {};
2645
+ const hdrFromPort = typeof rawHdrs.get === 'function'
2646
+ ? rawHdrs.get('x-codelab-from-port')
2647
+ : (rawHdrs['x-codelab-from-port'] || rawHdrs['X-CodeLab-From-Port']);
2648
+ const fromPort = Number((init && init._fromPort) || hdrFromPort || 0) || null;
2649
+ const rule = chaosRules.get(port);
2650
+ let appliedDelayMs = 0;
2651
+
2652
+ if (rule) {
2653
+ let delay = Number(rule.latencyMs) || 0;
2654
+ if (rule.jitterMs > 0) {
2655
+ delay += Math.round((Math.random() * 2 - 1) * Number(rule.jitterMs));
2656
+ }
2657
+ delay = Math.max(0, delay);
2658
+ if (delay > 0) {
2659
+ appliedDelayMs = delay;
2660
+ await new Promise((r) => setTimeout(r, delay));
2661
+ }
2662
+
2663
+ if (rule.crashed) {
2664
+ const err = new Error(`connect ECONNREFUSED 127.0.0.1:${port} (chaos: node crashed)`);
2665
+ err.code = 'ECONNREFUSED';
2666
+ err.chaosEffect = 'CRASHED';
2667
+ err.fromPort = fromPort;
2668
+ throw err;
2669
+ }
2670
+
2671
+ if (fromPort && Array.isArray(rule.partitionFromPorts) && rule.partitionFromPorts.includes(fromPort)) {
2672
+ const err = new Error(`connect EHOSTUNREACH 127.0.0.1:${port} (chaos: network partition from :${fromPort})`);
2673
+ err.code = 'EHOSTUNREACH';
2674
+ err.chaosEffect = `PARTITION(:${fromPort}-x->:${port})`;
2675
+ err.fromPort = fromPort;
2676
+ throw err;
2677
+ }
2678
+
2679
+ if (rule.dropRate > 0 && Math.random() < rule.dropRate) {
2680
+ const err = new Error(`socket hang up 127.0.0.1:${port} (chaos: packet dropped)`);
2681
+ err.code = 'ETIMEDOUT';
2682
+ err.chaosEffect = 'DROPPED';
2683
+ err.fromPort = fromPort;
2684
+ throw err;
2685
+ }
2686
+
2687
+ if (rule.errorRate > 0 && Math.random() < rule.errorRate) {
2688
+ const status = Number(rule.statusCode) || 503;
2689
+ const statusText = status === 429
2690
+ ? 'Too Many Requests'
2691
+ : (status === 504 ? 'Gateway Timeout' : 'Service Unavailable');
2692
+ const chaosTag = appliedDelayMs > 0 ? `ERROR_${status}+${appliedDelayMs}ms` : `ERROR_${status}`;
2693
+ const res = new Response(
2694
+ JSON.stringify({ error: `${statusText} (Chaos Injected)`, chaos: true, port, status }),
2695
+ {
2696
+ status,
2697
+ statusText,
2698
+ headers: {
2699
+ 'content-type': 'application/json',
2700
+ 'x-codelab-chaos': chaosTag
2701
+ }
2702
+ }
2703
+ );
2704
+ res._chaosEffect = chaosTag;
2705
+ res._fromPort = fromPort;
2706
+ return res;
2707
+ }
2708
+ }
2709
+
2578
2710
  const entry = table.get(port);
2579
2711
  if (!entry) {
2580
2712
  const err = new Error(`connect ECONNREFUSED 127.0.0.1:${port}`);
2581
2713
  err.code = 'ECONNREFUSED';
2714
+ err.fromPort = fromPort;
2582
2715
  throw err;
2583
2716
  }
2717
+ let res;
2584
2718
  if (entry.fetch) {
2585
- return entry.fetch(new Request(url, init));
2719
+ res = await entry.fetch(new Request(url, init));
2720
+ } else if (entry.server && typeof entry.server.dispatchRequest === 'function') {
2721
+ res = await entry.server.dispatchRequest(url, init);
2722
+ } else {
2723
+ res = new Response('OK', { status: 200 });
2586
2724
  }
2587
- if (entry.server && typeof entry.server.dispatchRequest === 'function') {
2588
- return entry.server.dispatchRequest(url, init);
2725
+ if (res && typeof res === 'object') {
2726
+ res._fromPort = fromPort;
2727
+ if (appliedDelayMs > 0 && !res._chaosEffect) {
2728
+ res._chaosEffect = `DELAY_+${appliedDelayMs}ms`;
2729
+ }
2589
2730
  }
2590
- return new Response('OK', { status: 200 });
2731
+ return res;
2591
2732
  }
2592
2733
  };
2593
2734
  }
@@ -2919,6 +3060,78 @@ function __initVirtualRuntime(rootScope) {
2919
3060
  return;
2920
3061
  }
2921
3062
  const server = activeServers.get(this.port);
3063
+ const hasChaosRule = Boolean(
3064
+ activePortTable &&
3065
+ typeof activePortTable.getChaosRule === 'function' &&
3066
+ activePortTable.getChaosRule(this.port)
3067
+ );
3068
+ const hasPortTableServer = Boolean(
3069
+ activePortTable &&
3070
+ typeof activePortTable.getServer === 'function' &&
3071
+ activePortTable.getServer(this.port)
3072
+ );
3073
+ if ((!server || !server._listening || hasChaosRule) && activePortTable && (hasPortTableServer || hasChaosRule) && typeof activePortTable.dispatchRequest === 'function') {
3074
+ let inferredFromPort = null;
3075
+ if (activeServers.size > 0) {
3076
+ const firstLocalPort = Array.from(activeServers.keys()).find((p) => Number(p) !== Number(this.port));
3077
+ if (firstLocalPort) inferredFromPort = firstLocalPort;
3078
+ } else if (resourceTracker && resourceTracker.pid && typeof activePortTable.listServers === 'function') {
3079
+ const owned = activePortTable.listServers().find((s) => s && s.pid === resourceTracker.pid && Number(s.port) !== Number(this.port));
3080
+ if (owned) inferredFromPort = owned.port;
3081
+ }
3082
+ const reqBody = this._bodyChunks.length > 0 ? VirtualBuffer.concat(this._bodyChunks) : undefined;
3083
+ const fullUrl = `http://${this.host}:${this.port}${this.path.startsWith('/') ? '' : '/'}${this.path}`;
3084
+ activePortTable.dispatchRequest(fullUrl, {
3085
+ method: this.method,
3086
+ headers: { ...this.headers },
3087
+ body: reqBody,
3088
+ _fromPort: inferredFromPort
3089
+ }).then(async (res) => {
3090
+ if (this.destroyed) {
3091
+ this._finishInFlight();
3092
+ return;
3093
+ }
3094
+ const resHeaders = {};
3095
+ if (res && res.headers && typeof res.headers.forEach === 'function') {
3096
+ res.headers.forEach((v, k) => { resHeaders[String(k).toLowerCase()] = String(v); });
3097
+ }
3098
+ let buf = VirtualBuffer.alloc(0);
3099
+ if (res && typeof res.arrayBuffer === 'function') {
3100
+ const ab = await res.arrayBuffer();
3101
+ buf = VirtualBuffer.from(ab);
3102
+ }
3103
+ traceEntry.status = (res && res.status) || 200;
3104
+ traceEntry.durationMs = Math.max(0, performance.now() - traceEntry._t0);
3105
+ traceEntry.responseBytes = buf.length;
3106
+ traceEntry.responseHeaders = resHeaders;
3107
+ if (inferredFromPort) traceEntry.fromPort = inferredFromPort;
3108
+ if (res && res._chaosEffect) traceEntry.chaosEffect = res._chaosEffect;
3109
+ const clientRes = new IncomingMessage({
3110
+ statusCode: (res && res.status) || 200,
3111
+ headers: resHeaders
3112
+ });
3113
+ this._onResponseHeaders(clientRes);
3114
+ if (buf.length > 0) clientRes._pushData(buf);
3115
+ clientRes._pushEnd();
3116
+ this._finishInFlight();
3117
+ }).catch((err) => {
3118
+ if (this.destroyed) {
3119
+ this._finishInFlight();
3120
+ return;
3121
+ }
3122
+ err.errno = err.errno || -61;
3123
+ err.syscall = err.syscall || 'connect';
3124
+ err.address = this.host;
3125
+ err.port = this.port;
3126
+ traceEntry.status = err.code || 'ECONNREFUSED';
3127
+ traceEntry.durationMs = Math.max(0, performance.now() - traceEntry._t0);
3128
+ if (inferredFromPort) traceEntry.fromPort = inferredFromPort;
3129
+ if (err && err.chaosEffect) traceEntry.chaosEffect = err.chaosEffect;
3130
+ this._finishInFlight();
3131
+ this.emit('error', err);
3132
+ });
3133
+ return;
3134
+ }
2922
3135
  if (!server || !server._listening) {
2923
3136
  const err = new Error(`connect ECONNREFUSED ${this.host}:${this.port}`);
2924
3137
  err.code = 'ECONNREFUSED';
@@ -6497,411 +6710,114 @@ function __initVirtualRuntime(rootScope) {
6497
6710
  });
6498
6711
  });
6499
6712
 
6500
- class SqliteDatabase {
6501
- constructor(filename = ':memory:') {
6502
- this.filename = filename;
6503
- this.tables = new Map();
6504
- }
6505
-
6506
- run(sql, params = []) {
6507
- const stmt = sql.trim();
6508
- if (/^CREATE\s+TABLE/i.test(stmt)) {
6509
- const match = stmt.match(/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s*\((.*)\)/is);
6510
- if (match) {
6511
- const tableName = match[1];
6512
- const colDefs = match[2].split(',').map(c => c.trim());
6513
- const cols = [];
6514
- for (const c of colDefs) {
6515
- const parts = c.split(/\s+/);
6516
- const colName = parts[0];
6517
- const isPk = /PRIMARY\s+KEY/i.test(c);
6518
- const isAuto = /AUTOINCREMENT/i.test(c) || (/INTEGER/i.test(parts[1]) && isPk);
6519
- cols.push({ name: colName, type: parts[1] || 'TEXT', isPk, isAuto });
6520
- }
6521
- if (!this.tables.has(tableName)) {
6522
- this.tables.set(tableName, { columns: cols, rows: [], autoInc: 0 });
6523
- }
6524
- }
6525
- return { changes: 0, lastInsertRowid: 0 };
6526
- }
6527
-
6528
- if (/^DROP\s+TABLE/i.test(stmt)) {
6529
- const match = stmt.match(/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);
6530
- if (match) this.tables.delete(match[1]);
6531
- return { changes: 0, lastInsertRowid: 0 };
6532
- }
6533
-
6534
- if (/^INSERT\s+INTO/i.test(stmt)) {
6535
- const match = stmt.match(/^INSERT\s+INTO\s+([a-zA-Z0-9_]+)(?:\s*\(([^)]+)\))?\s*VALUES\s*\((.*)\)/is);
6536
- if (match) {
6537
- const tableName = match[1];
6538
- const table = this.tables.get(tableName);
6539
- if (!table) throw new Error(`no such table: ${tableName}`);
6540
- const colNames = match[2] ? match[2].split(',').map(s => s.trim()) : table.columns.filter(c => !c.isPk).map(c => c.name);
6541
- const valExprs = match[3].split(',').map(s => s.trim());
6542
- const pList = Array.isArray(params) ? [...params] : [params];
6543
- const row = {};
6713
+ const SqliteDatabase = createSqliteDatabase(vfs, () => sandboxProcess.cwd());
6544
6714
 
6545
- table.autoInc++;
6546
- const pkCol = table.columns.find(c => c.isPk);
6547
- if (pkCol) {
6548
- row[pkCol.name] = table.autoInc;
6549
- }
6715
+ function crc32Hash(str) {
6716
+ return VirtualZlib.crc32( typeof str === 'string' || str instanceof Uint8Array ? str : String(str) );
6717
+ }
6550
6718
 
6551
- for (let i = 0; i < colNames.length; i++) {
6552
- const cName = colNames[i];
6553
- const expr = valExprs[i] !== undefined ? valExprs[i] : '?';
6554
- if (expr === '?') {
6555
- row[cName] = pList.shift();
6556
- } else if (/^['"].*['"]$/.test(expr)) {
6557
- row[cName] = expr.slice(1, -1);
6558
- } else if (!isNaN(Number(expr))) {
6559
- row[cName] = Number(expr);
6560
- } else {
6561
- row[cName] = expr;
6562
- }
6563
- }
6564
- table.rows.push(row);
6565
- return { changes: 1, lastInsertRowid: table.autoInc };
6566
- }
6567
- }
6719
+ const bunHashFn = function hash(val) {
6720
+ return crc32Hash(val);
6721
+ };
6722
+ bunHashFn.crc32 = (val) => crc32Hash(val);
6723
+ bunHashFn.cityHash64 = (val) => {
6724
+ const h1 = crc32Hash(val);
6725
+ const h2 = crc32Hash(String(val) + ':seed64');
6726
+ return (BigInt(h1) << 32n) | BigInt(h2);
6727
+ };
6568
6728
 
6569
- if (/^DELETE\s+FROM/i.test(stmt)) {
6570
- const match = stmt.match(/^DELETE\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+(.*))?$/is);
6571
- if (match) {
6572
- const table = this.tables.get(match[1]);
6573
- if (!table) throw new Error(`no such table: ${match[1]}`);
6574
- const whereClause = match[2] ? match[2].trim() : null;
6575
- const pList = Array.isArray(params) ? [...params] : [params];
6576
- const beforeLen = table.rows.length;
6577
- if (!whereClause) {
6578
- table.rows = [];
6579
- } else {
6580
- table.rows = table.rows.filter(r => !this._matchWhere(r, whereClause, pList));
6581
- }
6582
- return { changes: beforeLen - table.rows.length, lastInsertRowid: table.autoInc };
6583
- }
6584
- }
6729
+ function deepEquals(a, b) {
6730
+ return isDeepEqual(a, b, true);
6731
+ }
6585
6732
 
6586
- if (/^UPDATE\s+/i.test(stmt)) {
6587
- const match = stmt.match(/^UPDATE\s+([a-zA-Z0-9_]+)\s+SET\s+(.*?)(?:\s+WHERE\s+(.*))?$/is);
6588
- if (match) {
6589
- const table = this.tables.get(match[1]);
6590
- if (!table) throw new Error(`no such table: ${match[1]}`);
6591
- const setParts = match[2].split(',').map(s => s.trim());
6592
- const whereClause = match[3] ? match[3].trim() : null;
6593
- const pList = Array.isArray(params) ? [...params] : [params];
6594
- let changes = 0;
6595
- for (const row of table.rows) {
6596
- const rowParams = [...pList];
6597
- const setUpdates = [];
6598
- for (const sp of setParts) {
6599
- const eqIdx = sp.indexOf('=');
6600
- const col = sp.slice(0, eqIdx).trim();
6601
- let valExpr = sp.slice(eqIdx + 1).trim();
6602
- let val = valExpr === '?' ? rowParams.shift() : (/^['"].*['"]$/.test(valExpr) ? valExpr.slice(1, -1) : (!isNaN(Number(valExpr)) ? Number(valExpr) : valExpr));
6603
- setUpdates.push([col, val]);
6604
- }
6605
- if (!whereClause || this._matchWhere(row, whereClause, rowParams)) {
6606
- for (const [col, val] of setUpdates) row[col] = val;
6607
- changes++;
6608
- }
6609
- }
6610
- return { changes, lastInsertRowid: table.autoInc };
6733
+ const BunObj = {
6734
+ version: '1.1.0',
6735
+ serve(opts = {}) {
6736
+ const port = Number(opts.port || 3000);
6737
+ const hostname = opts.hostname || '127.0.0.1';
6738
+ const serverObj = {
6739
+ port,
6740
+ hostname,
6741
+ development: false,
6742
+ stop() {
6743
+ activePortTable.unregisterServer(port);
6611
6744
  }
6612
- }
6613
-
6614
- return { changes: 0, lastInsertRowid: 0 };
6615
- }
6616
-
6617
- _matchWhere(row, whereClause, pList) {
6618
- if (!whereClause) return true;
6619
- const eqMatch = whereClause.match(/^([a-zA-Z0-9_]+)\s*(=|!=|<>|>=|<=|>|<)\s*(.*)$/);
6620
- if (eqMatch) {
6621
- const col = eqMatch[1].trim();
6622
- const op = eqMatch[2];
6623
- let expected = eqMatch[3].trim();
6624
- if (expected === '?') {
6625
- expected = pList.shift();
6626
- } else if (/^['"].*['"]$/.test(expected)) {
6627
- expected = expected.slice(1, -1);
6628
- } else if (!isNaN(Number(expected))) {
6629
- expected = Number(expected);
6630
- }
6631
- const actual = row[col];
6632
- if (op === '=') return String(actual) === String(expected);
6633
- if (op === '!=' || op === '<>') return String(actual) !== String(expected);
6634
- if (op === '>') return Number(actual) > Number(expected);
6635
- if (op === '<') return Number(actual) < Number(expected);
6636
- if (op === '>=') return Number(actual) >= Number(expected);
6637
- if (op === '<=') return Number(actual) <= Number(expected);
6638
- }
6639
- return true;
6640
- }
6641
-
6642
- exec(sql) {
6643
- const statements = sql.split(';').map(s => s.trim()).filter(Boolean);
6644
- for (const s of statements) {
6645
- this.run(s);
6646
- }
6647
- }
6648
-
6649
- transaction(fn) {
6650
- return (...args) => fn(...args);
6651
- }
6652
-
6653
- close() {}
6654
-
6655
- query(sql) {
6656
- const db = this;
6745
+ };
6746
+ activePortTable.registerServer(port, {
6747
+ server: serverObj,
6748
+ name: opts.name || 'bun-server',
6749
+ port,
6750
+ pid: resourceTracker.pid || 1,
6751
+ fetch: opts.fetch ? opts.fetch.bind(serverObj) : undefined,
6752
+ stop: () => serverObj.stop()
6753
+ });
6754
+ return serverObj;
6755
+ },
6756
+ file(p) {
6757
+ const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(p));
6657
6758
  return {
6658
- all(...args) {
6659
- let params = args;
6660
- if (args.length === 1 && Array.isArray(args[0])) params = args[0];
6661
- return db._executeSelect(sql, params);
6759
+ name: VirtualPath.basename(resolved),
6760
+ get size() {
6761
+ try {
6762
+ return vfs.statSync(resolved).size;
6763
+ } catch (_) {
6764
+ return 0;
6765
+ }
6662
6766
  },
6663
- get(...args) {
6664
- const rows = this.all(...args);
6665
- return rows[0] || null;
6767
+ async exists() {
6768
+ return vfs.existsSync(resolved);
6666
6769
  },
6667
- values(...args) {
6668
- const rows = this.all(...args);
6669
- return rows.map(r => Object.values(r));
6770
+ async text() {
6771
+ return vfs.readFileSync(resolved, 'utf8');
6670
6772
  },
6671
- run(...args) {
6672
- let params = args;
6673
- if (args.length === 1 && Array.isArray(args[0])) params = args[0];
6674
- return db.run(sql, params);
6773
+ async json() {
6774
+ return JSON.parse(vfs.readFileSync(resolved, 'utf8'));
6775
+ },
6776
+ async arrayBuffer() {
6777
+ const buf = vfs.readFileSync(resolved);
6778
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
6675
6779
  }
6676
6780
  };
6781
+ },
6782
+ async write(dest, data) {
6783
+ const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(dest));
6784
+ const dir = VirtualPath.dirname(resolved);
6785
+ if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
6786
+ let buf;
6787
+ if (typeof data === 'string') {
6788
+ buf = VirtualBuffer.from(data, 'utf8');
6789
+ } else if (data && data.arrayBuffer && typeof data.arrayBuffer === 'function') {
6790
+ const ab = await data.arrayBuffer();
6791
+ buf = VirtualBuffer.from(ab);
6792
+ } else if (data instanceof Uint8Array || VirtualBuffer.isBuffer(data)) {
6793
+ buf = VirtualBuffer.from(data);
6794
+ } else {
6795
+ buf = VirtualBuffer.from(String(data), 'utf8');
6796
+ }
6797
+ vfs.writeFileSync(resolved, buf);
6798
+ return buf.length;
6799
+ },
6800
+ sleep(ms) {
6801
+ return new Promise(resolve => sandboxSetTimeout(resolve, Number(ms) || 0));
6802
+ },
6803
+ hash: bunHashFn,
6804
+ deepEquals,
6805
+ inspect(val) {
6806
+ return VirtualUtil.inspect(val);
6807
+ },
6808
+ nanoseconds() {
6809
+ return Math.round(performance.now() * 1e6);
6677
6810
  }
6811
+ };
6678
6812
 
6679
- prepare(sql) {
6680
- return this.query(sql);
6681
- }
6682
-
6683
- _executeSelect(sql, params = []) {
6684
- const s = sql.trim().replace(/;$/, '');
6685
- 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);
6686
- if (!match) return [];
6687
- const selectColsRaw = match[1].trim();
6688
- const tableName = match[2].trim();
6689
- const whereClause = match[3] ? match[3].trim() : null;
6690
- const groupByClause = match[4] ? match[4].trim() : null;
6691
- const orderByClause = match[5] ? match[5].trim() : null;
6692
- const limitRaw = match[6] ? match[6].trim() : null;
6693
- const offsetRaw = match[7] ? match[7].trim() : null;
6694
-
6695
- const table = this.tables.get(tableName);
6696
- if (!table) return [];
6697
-
6698
- let pList = Array.isArray(params) ? [...params] : [params];
6699
- let filteredRows = table.rows.filter(row => {
6700
- const rowParams = [...pList];
6701
- return this._matchWhere(row, whereClause, rowParams);
6702
- });
6703
- if (whereClause && whereClause.includes('?')) {
6704
- const qCount = (whereClause.match(/\?/g) || []).length;
6705
- pList.splice(0, qCount);
6706
- }
6707
-
6708
- const colSpecs = [];
6709
- if (selectColsRaw !== '*') {
6710
- const parts = selectColsRaw.split(',').map(p => p.trim());
6711
- for (const p of parts) {
6712
- const asMatch = p.match(/^(.*?)\s+(?:as\s+)?([a-zA-Z0-9_]+)$/i);
6713
- if (asMatch) {
6714
- colSpecs.push({ expr: asMatch[1].trim(), alias: asMatch[2].trim() });
6715
- } else {
6716
- colSpecs.push({ expr: p, alias: p });
6717
- }
6718
- }
6719
- }
6720
-
6721
- let outputRows = [];
6722
- if (groupByClause) {
6723
- const groupCol = groupByClause.trim();
6724
- const groups = new Map();
6725
- for (const row of filteredRows) {
6726
- const key = row[groupCol];
6727
- if (!groups.has(key)) groups.set(key, []);
6728
- groups.get(key).push(row);
6729
- }
6730
-
6731
- for (const [key, rows] of groups.entries()) {
6732
- const outRow = {};
6733
- for (const col of colSpecs) {
6734
- const expr = col.expr;
6735
- const alias = col.alias;
6736
- const aggMatch = expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\(([a-zA-Z0-9_*]+)\)$/i);
6737
- if (aggMatch) {
6738
- const fn = aggMatch[1].toUpperCase();
6739
- const aggCol = aggMatch[2];
6740
- if (fn === 'COUNT') {
6741
- outRow[alias] = rows.length;
6742
- } else if (fn === 'AVG') {
6743
- const sum = rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
6744
- outRow[alias] = rows.length > 0 ? sum / rows.length : 0;
6745
- } else if (fn === 'SUM') {
6746
- outRow[alias] = rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
6747
- } else if (fn === 'MIN') {
6748
- outRow[alias] = Math.min(...rows.map(r => Number(r[aggCol]) || 0));
6749
- } else if (fn === 'MAX') {
6750
- outRow[alias] = Math.max(...rows.map(r => Number(r[aggCol]) || 0));
6751
- }
6752
- } else if (expr === groupCol) {
6753
- outRow[alias] = key;
6754
- } else {
6755
- outRow[alias] = rows[0] ? rows[0][expr] : null;
6756
- }
6757
- }
6758
- outputRows.push(outRow);
6759
- }
6760
- } else {
6761
- for (const row of filteredRows) {
6762
- if (selectColsRaw === '*') {
6763
- outputRows.push(Object.assign({}, row));
6764
- } else {
6765
- const outRow = {};
6766
- for (const col of colSpecs) {
6767
- outRow[col.alias] = row[col.expr];
6768
- }
6769
- outputRows.push(outRow);
6770
- }
6771
- }
6772
- }
6773
-
6774
- if (orderByClause) {
6775
- const parts = orderByClause.trim().split(/\s+/);
6776
- const orderCol = parts[0];
6777
- const desc = parts[1] && parts[1].toUpperCase() === 'DESC';
6778
- outputRows.sort((a, b) => {
6779
- const valA = a[orderCol];
6780
- const valB = b[orderCol];
6781
- if (valA === valB) return 0;
6782
- if (valA === undefined) return 1;
6783
- if (valB === undefined) return -1;
6784
- const res = valA > valB ? 1 : -1;
6785
- return desc ? -res : res;
6786
- });
6787
- }
6788
-
6789
- if (limitRaw !== null) {
6790
- const limitVal = limitRaw === '?' ? Number(pList.shift() || 0) : Number(limitRaw);
6791
- const offsetVal = offsetRaw !== null ? (offsetRaw === '?' ? Number(pList.shift() || 0) : Number(offsetRaw)) : 0;
6792
- outputRows = outputRows.slice(offsetVal, offsetVal + limitVal);
6793
- }
6794
-
6795
- return outputRows;
6796
- }
6797
- }
6798
-
6799
- function crc32Hash(str) {
6800
- return VirtualZlib.crc32( typeof str === 'string' || str instanceof Uint8Array ? str : String(str) );
6801
- }
6802
-
6803
- const bunHashFn = function hash(val) {
6804
- return crc32Hash(val);
6805
- };
6806
- bunHashFn.crc32 = (val) => crc32Hash(val);
6807
- bunHashFn.cityHash64 = (val) => {
6808
- const h1 = crc32Hash(val);
6809
- const h2 = crc32Hash(String(val) + ':seed64');
6810
- return (BigInt(h1) << 32n) | BigInt(h2);
6811
- };
6812
-
6813
- function deepEquals(a, b) {
6814
- return isDeepEqual(a, b, true);
6815
- }
6816
-
6817
- const BunObj = {
6818
- version: '1.1.0',
6819
- serve(opts = {}) {
6820
- const port = Number(opts.port || 3000);
6821
- const hostname = opts.hostname || '127.0.0.1';
6822
- const serverObj = {
6823
- port,
6824
- hostname,
6825
- development: false,
6826
- stop() {
6827
- activePortTable.unregisterServer(port);
6828
- }
6829
- };
6830
- activePortTable.registerServer(port, {
6831
- server: serverObj,
6832
- name: opts.name || 'bun-server',
6833
- port,
6834
- pid: resourceTracker.pid || 1,
6835
- fetch: opts.fetch ? opts.fetch.bind(serverObj) : undefined,
6836
- stop: () => serverObj.stop()
6837
- });
6838
- return serverObj;
6839
- },
6840
- file(p) {
6841
- const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(p));
6842
- return {
6843
- name: VirtualPath.basename(resolved),
6844
- get size() {
6845
- try {
6846
- return vfs.statSync(resolved).size;
6847
- } catch (_) {
6848
- return 0;
6849
- }
6850
- },
6851
- async exists() {
6852
- return vfs.existsSync(resolved);
6853
- },
6854
- async text() {
6855
- return vfs.readFileSync(resolved, 'utf8');
6856
- },
6857
- async json() {
6858
- return JSON.parse(vfs.readFileSync(resolved, 'utf8'));
6859
- },
6860
- async arrayBuffer() {
6861
- const buf = vfs.readFileSync(resolved);
6862
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
6863
- }
6864
- };
6865
- },
6866
- async write(dest, data) {
6867
- const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(dest));
6868
- const dir = VirtualPath.dirname(resolved);
6869
- if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
6870
- let buf;
6871
- if (typeof data === 'string') {
6872
- buf = VirtualBuffer.from(data, 'utf8');
6873
- } else if (data && data.arrayBuffer && typeof data.arrayBuffer === 'function') {
6874
- const ab = await data.arrayBuffer();
6875
- buf = VirtualBuffer.from(ab);
6876
- } else if (data instanceof Uint8Array || VirtualBuffer.isBuffer(data)) {
6877
- buf = VirtualBuffer.from(data);
6878
- } else {
6879
- buf = VirtualBuffer.from(String(data), 'utf8');
6880
- }
6881
- vfs.writeFileSync(resolved, buf);
6882
- return buf.length;
6883
- },
6884
- sleep(ms) {
6885
- return new Promise(resolve => sandboxSetTimeout(resolve, Number(ms) || 0));
6886
- },
6887
- hash: bunHashFn,
6888
- deepEquals,
6889
- inspect(val) {
6890
- return VirtualUtil.inspect(val);
6891
- },
6892
- nanoseconds() {
6893
- return Math.round(performance.now() * 1e6);
6894
- }
6895
- };
6896
-
6897
- const bunTestModule = (() => {
6898
- function makeExpect(actual, isNot = false) {
6899
- const pass = (condition, msg) => {
6900
- const ok = isNot ? !condition : condition;
6901
- if (!ok) {
6902
- throw new Error(msg || `expect assertion failed: actual=${actual}`);
6903
- }
6904
- };
6813
+ const bunTestModule = (() => {
6814
+ function makeExpect(actual, isNot = false) {
6815
+ const pass = (condition, msg) => {
6816
+ const ok = isNot ? !condition : condition;
6817
+ if (!ok) {
6818
+ throw new Error(msg || `expect assertion failed: actual=${actual}`);
6819
+ }
6820
+ };
6905
6821
 
6906
6822
  const matchers = {
6907
6823
  toBe(expected) {
@@ -7548,14 +7464,25 @@ function __initVirtualRuntime(rootScope) {
7548
7464
  urlStr = String(urlOrReq);
7549
7465
  }
7550
7466
 
7467
+ let parsedLocal = null;
7551
7468
  try {
7552
7469
  const parsed = new URL(urlStr);
7553
7470
  const isLocal = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '0.0.0.0';
7554
- if (isLocal && activePortTable) {
7555
- return await activePortTable.dispatchRequest(urlStr, finalInit);
7556
- }
7471
+ if (isLocal) parsedLocal = parsed;
7557
7472
  } catch (err) {
7558
- _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
7473
+ _runtimeLogger.debug('virtualFetch local URL parse skipped', err);
7474
+ }
7475
+
7476
+ if (parsedLocal && activePortTable) {
7477
+ let dispatchInit = finalInit;
7478
+ if (!dispatchInit._fromPort && resourceTracker && resourceTracker.pid && typeof activePortTable.listServers === 'function') {
7479
+ const targetPort = Number(parsedLocal.port || (parsedLocal.protocol === 'https:' ? 443 : 80));
7480
+ const owned = activePortTable.listServers().find((s) => s && s.pid === resourceTracker.pid && Number(s.port) !== targetPort);
7481
+ if (owned) {
7482
+ dispatchInit = Object.assign({}, finalInit, { _fromPort: owned.port });
7483
+ }
7484
+ }
7485
+ return await activePortTable.dispatchRequest(urlStr, dispatchInit);
7559
7486
  }
7560
7487
 
7561
7488
  if (typeof globalThis.fetch === 'function') {
@@ -7991,6 +7918,641 @@ function __initVirtualRuntime(rootScope) {
7991
7918
  return transpileTS(source, filename, { keepEsm: true });
7992
7919
  }
7993
7920
 
7921
+ function createSqliteDatabase(vfs = null, getCwd = null) {
7922
+ function stripSqlComments(sql) {
7923
+ return String(sql || '')
7924
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
7925
+ .replace(/--[^\r\n]*/g, ' ')
7926
+ .trim();
7927
+ }
7928
+
7929
+ function splitValueTuples(rawValues) {
7930
+ const tuples = [];
7931
+ let depth = 0;
7932
+ let inQuote = null;
7933
+ let start = -1;
7934
+ for (let i = 0; i < rawValues.length; i++) {
7935
+ const ch = rawValues[i];
7936
+ if (inQuote) {
7937
+ if (ch === inQuote && rawValues[i - 1] !== '\\') inQuote = null;
7938
+ continue;
7939
+ }
7940
+ if (ch === "'" || ch === '"') {
7941
+ inQuote = ch;
7942
+ } else if (ch === '(') {
7943
+ if (depth === 0) start = i + 1;
7944
+ depth++;
7945
+ } else if (ch === ')') {
7946
+ depth--;
7947
+ if (depth === 0 && start !== -1) {
7948
+ tuples.push(rawValues.slice(start, i));
7949
+ start = -1;
7950
+ }
7951
+ }
7952
+ }
7953
+ return tuples;
7954
+ }
7955
+
7956
+ function splitCsvRespectingQuotes(str) {
7957
+ const out = [];
7958
+ let cur = '';
7959
+ let inQuote = null;
7960
+ let depth = 0;
7961
+ for (let i = 0; i < str.length; i++) {
7962
+ const ch = str[i];
7963
+ if (inQuote) {
7964
+ cur += ch;
7965
+ if (ch === inQuote && str[i - 1] !== '\\') inQuote = null;
7966
+ continue;
7967
+ }
7968
+ if (ch === "'" || ch === '"') {
7969
+ inQuote = ch;
7970
+ cur += ch;
7971
+ } else if (ch === '(') {
7972
+ depth++;
7973
+ cur += ch;
7974
+ } else if (ch === ')') {
7975
+ depth = Math.max(0, depth - 1);
7976
+ cur += ch;
7977
+ } else if (ch === ',' && depth === 0) {
7978
+ out.push(cur.trim());
7979
+ cur = '';
7980
+ } else {
7981
+ cur += ch;
7982
+ }
7983
+ }
7984
+ if (cur.trim()) out.push(cur.trim());
7985
+ return out;
7986
+ }
7987
+
7988
+ return class SqliteDatabase {
7989
+ constructor(filename = ':memory:') {
7990
+ this.filename = filename || ':memory:';
7991
+ this.tables = new Map();
7992
+ this.indexes = new Map();
7993
+ this._loadFromVfs();
7994
+ }
7995
+
7996
+ _resolveDbPath() {
7997
+ if (!this.filename || this.filename === ':memory:') return null;
7998
+ const cwd = typeof getCwd === 'function' ? getCwd() : '/workspace';
7999
+ return VirtualPath.resolve(cwd || '/workspace', String(this.filename));
8000
+ }
8001
+
8002
+ _loadFromVfs() {
8003
+ const p = this._resolveDbPath();
8004
+ if (!p || !vfs || typeof vfs.existsSync !== 'function' || !vfs.existsSync(p)) return;
8005
+ try {
8006
+ const raw = vfs.readFileSync(p, 'utf8');
8007
+ const trimmed = String(raw || '').trim();
8008
+ if (!trimmed) return;
8009
+ if (trimmed.startsWith('{')) {
8010
+ const parsed = JSON.parse(trimmed);
8011
+ if (parsed && parsed.__codelab_sqlite__) {
8012
+ if (parsed.tables && typeof parsed.tables === 'object') {
8013
+ for (const [tName, tVal] of Object.entries(parsed.tables)) {
8014
+ this.tables.set(tName, tVal);
8015
+ }
8016
+ }
8017
+ if (parsed.indexes && typeof parsed.indexes === 'object') {
8018
+ for (const [iName, iVal] of Object.entries(parsed.indexes)) {
8019
+ this.indexes.set(iName, iVal);
8020
+ }
8021
+ }
8022
+ return;
8023
+ }
8024
+ }
8025
+ this.exec(trimmed);
8026
+ } catch (err) {
8027
+ _runtimeLogger.debug('SqliteDatabase._loadFromVfs skipped', err);
8028
+ }
8029
+ }
8030
+
8031
+ _persistToVfs() {
8032
+ const p = this._resolveDbPath();
8033
+ if (!p || !vfs || typeof vfs.writeFileSync !== 'function') return;
8034
+ try {
8035
+ const dir = VirtualPath.dirname(p);
8036
+ if (typeof vfs.existsSync === 'function' && !vfs.existsSync(dir) && typeof vfs.mkdirSync === 'function') {
8037
+ vfs.mkdirSync(dir, { recursive: true });
8038
+ }
8039
+ const payload = JSON.stringify({
8040
+ __codelab_sqlite__: 1,
8041
+ tables: Object.fromEntries(this.tables),
8042
+ indexes: Object.fromEntries(this.indexes)
8043
+ });
8044
+ vfs.writeFileSync(p, payload);
8045
+ } catch (err) {
8046
+ _runtimeLogger.debug('SqliteDatabase._persistToVfs failed', err);
8047
+ }
8048
+ }
8049
+
8050
+ run(sql, params = []) {
8051
+ const stmt = stripSqlComments(sql).replace(/;$/, '').trim();
8052
+ if (!stmt) return { changes: 0, lastInsertRowid: 0 };
8053
+
8054
+ if (/^CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TABLE/i.test(stmt)) {
8055
+ 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);
8056
+ if (match) {
8057
+ const tableName = match[1];
8058
+ const colDefs = splitCsvRespectingQuotes(match[2]);
8059
+ const cols = [];
8060
+ for (const c of colDefs) {
8061
+ if (/^(PRIMARY\s+KEY|FOREIGN\s+KEY|CONSTRAINT|UNIQUE|CHECK)\b/i.test(c)) continue;
8062
+ const parts = c.split(/\s+/);
8063
+ const colName = parts[0].replace(/^["'`]|["'`]$/g, '');
8064
+ const isPk = /PRIMARY\s+KEY/i.test(c);
8065
+ const isAuto = /AUTOINCREMENT/i.test(c) || (/INTEGER/i.test(parts[1] || '') && isPk);
8066
+ cols.push({ name: colName, type: parts[1] || 'TEXT', isPk, isAuto, raw: c });
8067
+ }
8068
+ if (!this.tables.has(tableName)) {
8069
+ this.tables.set(tableName, { columns: cols, rows: [], autoInc: 0, sql: stmt });
8070
+ this._persistToVfs();
8071
+ }
8072
+ }
8073
+ return { changes: 0, lastInsertRowid: 0 };
8074
+ }
8075
+
8076
+ if (/^DROP\s+TABLE/i.test(stmt)) {
8077
+ const match = stmt.match(/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);
8078
+ if (match) {
8079
+ this.tables.delete(match[1]);
8080
+ this._persistToVfs();
8081
+ }
8082
+ return { changes: 0, lastInsertRowid: 0 };
8083
+ }
8084
+
8085
+ if (/^CREATE\s+(?:UNIQUE\s+)?INDEX/i.test(stmt)) {
8086
+ 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);
8087
+ if (match) {
8088
+ const unique = Boolean(match[1]);
8089
+ const idxName = match[2];
8090
+ const tblName = match[3];
8091
+ const cols = match[4].split(',').map((s) => s.trim().split(/\s+/)[0]);
8092
+ this.indexes.set(idxName, { name: idxName, table: tblName, columns: cols, unique, sql: stmt });
8093
+ this._persistToVfs();
8094
+ }
8095
+ return { changes: 0, lastInsertRowid: 0 };
8096
+ }
8097
+
8098
+ if (/^DROP\s+INDEX/i.test(stmt)) {
8099
+ const match = stmt.match(/^DROP\s+INDEX\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);
8100
+ if (match) {
8101
+ this.indexes.delete(match[1]);
8102
+ this._persistToVfs();
8103
+ }
8104
+ return { changes: 0, lastInsertRowid: 0 };
8105
+ }
8106
+
8107
+ if (/^ALTER\s+TABLE/i.test(stmt)) {
8108
+ const match = stmt.match(/^ALTER\s+TABLE\s+([a-zA-Z0-9_]+)\s+ADD\s+(?:COLUMN\s+)?([a-zA-Z0-9_]+)\s*(.*)$/i);
8109
+ if (match) {
8110
+ const table = this.tables.get(match[1]);
8111
+ if (table) {
8112
+ const colName = match[2];
8113
+ const colType = (match[3] || 'TEXT').split(/\s+/)[0] || 'TEXT';
8114
+ table.columns.push({ name: colName, type: colType, isPk: false, isAuto: false });
8115
+ this._persistToVfs();
8116
+ }
8117
+ }
8118
+ return { changes: 0, lastInsertRowid: 0 };
8119
+ }
8120
+
8121
+ if (/^PRAGMA\s+/i.test(stmt)) {
8122
+ return { changes: 0, lastInsertRowid: 0 };
8123
+ }
8124
+
8125
+ if (/^INSERT\s+(?:OR\s+(?:REPLACE|IGNORE)\s+)?INTO/i.test(stmt)) {
8126
+ const match = stmt.match(/^INSERT\s+(?:OR\s+(REPLACE|IGNORE)\s+)?INTO\s+([a-zA-Z0-9_]+)(?:\s*\(([^)]+)\))?\s*VALUES\s*([\s\S]*)$/i);
8127
+ if (match) {
8128
+ const conflictMode = (match[1] || '').toUpperCase();
8129
+ const tableName = match[2];
8130
+ const table = this.tables.get(tableName);
8131
+ if (!table) throw new Error(`no such table: ${tableName}`);
8132
+ const explicitCols = match[3] ? match[3].split(',').map((s) => s.trim()) : null;
8133
+ const tuples = splitValueTuples(match[4]);
8134
+ const pList = Array.isArray(params) ? [...params] : [params];
8135
+ let insertedCount = 0;
8136
+
8137
+ for (const tupleStr of (tuples.length > 0 ? tuples : [match[4].replace(/^\(|\)$/g, '')])) {
8138
+ const valExprs = splitCsvRespectingQuotes(tupleStr);
8139
+ const colNames = explicitCols
8140
+ ? explicitCols
8141
+ : (valExprs.length === table.columns.length
8142
+ ? table.columns.map((c) => c.name)
8143
+ : table.columns.filter((c) => !c.isPk).map((c) => c.name));
8144
+ const row = {};
8145
+ const pkCol = table.columns.find((c) => c.isPk);
8146
+
8147
+ for (let i = 0; i < colNames.length; i++) {
8148
+ const cName = colNames[i];
8149
+ const expr = valExprs[i] !== undefined ? valExprs[i] : '?';
8150
+ if (expr === '?') {
8151
+ row[cName] = pList.shift();
8152
+ } else if (/^['"][\s\S]*['"]$/.test(expr)) {
8153
+ row[cName] = expr.slice(1, -1).replace(/''/g, "'");
8154
+ } else if (/^null$/i.test(expr)) {
8155
+ row[cName] = null;
8156
+ } else if (!isNaN(Number(expr))) {
8157
+ row[cName] = Number(expr);
8158
+ } else {
8159
+ row[cName] = expr;
8160
+ }
8161
+ }
8162
+
8163
+ if (pkCol) {
8164
+ if (row[pkCol.name] === undefined || row[pkCol.name] === null) {
8165
+ table.autoInc++;
8166
+ row[pkCol.name] = table.autoInc;
8167
+ } else if (typeof row[pkCol.name] === 'number' && row[pkCol.name] > table.autoInc) {
8168
+ table.autoInc = row[pkCol.name];
8169
+ }
8170
+ const existingIdx = table.rows.findIndex((r) => String(r[pkCol.name]) === String(row[pkCol.name]));
8171
+ if (existingIdx !== -1) {
8172
+ if (conflictMode === 'IGNORE') continue;
8173
+ if (conflictMode === 'REPLACE') {
8174
+ table.rows[existingIdx] = row;
8175
+ insertedCount++;
8176
+ continue;
8177
+ }
8178
+ }
8179
+ } else {
8180
+ table.autoInc++;
8181
+ }
8182
+
8183
+ table.rows.push(row);
8184
+ insertedCount++;
8185
+ }
8186
+ this._persistToVfs();
8187
+ return { changes: insertedCount, lastInsertRowid: table.autoInc };
8188
+ }
8189
+ }
8190
+
8191
+ if (/^DELETE\s+FROM/i.test(stmt)) {
8192
+ const match = stmt.match(/^DELETE\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*))?$/i);
8193
+ if (match) {
8194
+ const table = this.tables.get(match[1]);
8195
+ if (!table) throw new Error(`no such table: ${match[1]}`);
8196
+ const whereClause = match[2] ? match[2].trim() : null;
8197
+ const pList = Array.isArray(params) ? [...params] : [params];
8198
+ const beforeLen = table.rows.length;
8199
+ if (!whereClause) {
8200
+ table.rows = [];
8201
+ } else {
8202
+ table.rows = table.rows.filter((r) => !this._matchWhere(r, whereClause, [...pList]));
8203
+ }
8204
+ this._persistToVfs();
8205
+ return { changes: beforeLen - table.rows.length, lastInsertRowid: table.autoInc };
8206
+ }
8207
+ }
8208
+
8209
+ if (/^UPDATE\s+/i.test(stmt)) {
8210
+ const match = stmt.match(/^UPDATE\s+([a-zA-Z0-9_]+)\s+SET\s+([\s\S]*?)(?:\s+WHERE\s+([\s\S]*))?$/i);
8211
+ if (match) {
8212
+ const table = this.tables.get(match[1]);
8213
+ if (!table) throw new Error(`no such table: ${match[1]}`);
8214
+ const setParts = splitCsvRespectingQuotes(match[2]);
8215
+ const whereClause = match[3] ? match[3].trim() : null;
8216
+ const pList = Array.isArray(params) ? [...params] : [params];
8217
+ let changes = 0;
8218
+ for (const row of table.rows) {
8219
+ const rowParams = [...pList];
8220
+ const setUpdates = [];
8221
+ for (const sp of setParts) {
8222
+ const eqIdx = sp.indexOf('=');
8223
+ const col = sp.slice(0, eqIdx).trim();
8224
+ const valExpr = sp.slice(eqIdx + 1).trim();
8225
+ const val = valExpr === '?'
8226
+ ? rowParams.shift()
8227
+ : (/^['"][\s\S]*['"]$/.test(valExpr)
8228
+ ? valExpr.slice(1, -1)
8229
+ : (!isNaN(Number(valExpr)) ? Number(valExpr) : valExpr));
8230
+ setUpdates.push([col, val]);
8231
+ }
8232
+ if (!whereClause || this._matchWhere(row, whereClause, rowParams)) {
8233
+ for (const [col, val] of setUpdates) row[col] = val;
8234
+ changes++;
8235
+ }
8236
+ }
8237
+ this._persistToVfs();
8238
+ return { changes, lastInsertRowid: table.autoInc };
8239
+ }
8240
+ }
8241
+
8242
+ return { changes: 0, lastInsertRowid: 0 };
8243
+ }
8244
+
8245
+ _matchWhere(row, whereClause, pList) {
8246
+ if (!whereClause) return true;
8247
+ const andParts = whereClause.split(/\s+AND\s+/i);
8248
+ for (const part of andParts) {
8249
+ const trimmed = part.trim();
8250
+ const isNullMatch = trimmed.match(/^([a-zA-Z0-9_]+)\s+IS\s+(NOT\s+)?NULL$/i);
8251
+ if (isNullMatch) {
8252
+ const col = isNullMatch[1];
8253
+ const isNot = Boolean(isNullMatch[2]);
8254
+ const isNull = row[col] === null || row[col] === undefined;
8255
+ if (isNot ? isNull : !isNull) return false;
8256
+ continue;
8257
+ }
8258
+ const likeMatch = trimmed.match(/^([a-zA-Z0-9_]+)\s+LIKE\s+(.+)$/i);
8259
+ if (likeMatch) {
8260
+ const col = likeMatch[1];
8261
+ let pat = likeMatch[2].trim();
8262
+ if (pat === '?') pat = String(pList.shift() || '');
8263
+ else if (/^['"].*['"]$/.test(pat)) pat = pat.slice(1, -1);
8264
+ const re = new RegExp('^' + pat.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/%/g, '.*').replace(/_/g, '.') + '$', 'i');
8265
+ if (!re.test(String(row[col] ?? ''))) return false;
8266
+ continue;
8267
+ }
8268
+ const eqMatch = trimmed.match(/^([a-zA-Z0-9_]+)\s*(=|!=|<>|>=|<=|>|<)\s*(.*)$/);
8269
+ if (eqMatch) {
8270
+ const col = eqMatch[1].trim();
8271
+ const op = eqMatch[2];
8272
+ let expected = eqMatch[3].trim();
8273
+ if (expected === '?') {
8274
+ expected = pList.shift();
8275
+ } else if (/^['"].*['"]$/.test(expected)) {
8276
+ expected = expected.slice(1, -1);
8277
+ } else if (!isNaN(Number(expected))) {
8278
+ expected = Number(expected);
8279
+ }
8280
+ const actual = row[col];
8281
+ let ok = true;
8282
+ if (op === '=') ok = String(actual) === String(expected);
8283
+ else if (op === '!=' || op === '<>') ok = String(actual) !== String(expected);
8284
+ else if (op === '>') ok = Number(actual) > Number(expected);
8285
+ else if (op === '<') ok = Number(actual) < Number(expected);
8286
+ else if (op === '>=') ok = Number(actual) >= Number(expected);
8287
+ else if (op === '<=') ok = Number(actual) <= Number(expected);
8288
+ if (!ok) return false;
8289
+ }
8290
+ }
8291
+ return true;
8292
+ }
8293
+
8294
+ exec(sql) {
8295
+ const cleaned = stripSqlComments(sql);
8296
+ const statements = cleaned.split(';').map((s) => s.trim()).filter(Boolean);
8297
+ for (const s of statements) {
8298
+ this.run(s);
8299
+ }
8300
+ }
8301
+
8302
+ transaction(fn) {
8303
+ return (...args) => fn(...args);
8304
+ }
8305
+
8306
+ close() {
8307
+ this._persistToVfs();
8308
+ }
8309
+
8310
+ query(sql) {
8311
+ const db = this;
8312
+ return {
8313
+ all(...args) {
8314
+ let params = args;
8315
+ if (args.length === 1 && Array.isArray(args[0])) params = args[0];
8316
+ return db._executeSelect(sql, params);
8317
+ },
8318
+ get(...args) {
8319
+ const rows = this.all(...args);
8320
+ return rows[0] || null;
8321
+ },
8322
+ values(...args) {
8323
+ const rows = this.all(...args);
8324
+ return rows.map((r) => Object.values(r));
8325
+ },
8326
+ run(...args) {
8327
+ let params = args;
8328
+ if (args.length === 1 && Array.isArray(args[0])) params = args[0];
8329
+ return db.run(sql, params);
8330
+ }
8331
+ };
8332
+ }
8333
+
8334
+ prepare(sql) {
8335
+ return this.query(sql);
8336
+ }
8337
+
8338
+ _evalAggregate(fn, aggCol, rows) {
8339
+ if (fn === 'COUNT') {
8340
+ if (aggCol === '*') return rows.length;
8341
+ return rows.filter((r) => r[aggCol] !== null && r[aggCol] !== undefined).length;
8342
+ }
8343
+ if (fn === 'AVG') {
8344
+ const sum = rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
8345
+ return rows.length > 0 ? sum / rows.length : 0;
8346
+ }
8347
+ if (fn === 'SUM') {
8348
+ return rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
8349
+ }
8350
+ if (fn === 'MIN') {
8351
+ return rows.length > 0 ? Math.min(...rows.map((r) => Number(r[aggCol]) || 0)) : null;
8352
+ }
8353
+ if (fn === 'MAX') {
8354
+ return rows.length > 0 ? Math.max(...rows.map((r) => Number(r[aggCol]) || 0)) : null;
8355
+ }
8356
+ return null;
8357
+ }
8358
+
8359
+ _executeSelect(sql, params = []) {
8360
+ const s = stripSqlComments(sql).replace(/;$/, '').trim();
8361
+ if (!s) return [];
8362
+
8363
+ if (/^EXPLAIN\s+QUERY\s+PLAN\s+/i.test(s)) {
8364
+ const inner = s.replace(/^EXPLAIN\s+QUERY\s+PLAN\s+/i, '').trim();
8365
+ 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);
8366
+ if (m) {
8367
+ const tblName = m[1];
8368
+ const whereRaw = (m[2] || '').replace(/'[^']*'|"[^"]*"/g, '');
8369
+ const table = this.tables.get(tblName);
8370
+ const pkCol = table && table.columns.find((c) => c.isPk);
8371
+ if (pkCol && new RegExp(`\\b${pkCol.name}\\b`, 'i').test(whereRaw)) {
8372
+ return [{ id: 0, parent: 0, notused: 0, detail: `SEARCH ${tblName} USING INTEGER PRIMARY KEY (rowid=?)` }];
8373
+ }
8374
+ for (const idx of this.indexes.values()) {
8375
+ if (idx.table === tblName && idx.columns.some((c) => new RegExp(`\\b${c}\\b`, 'i').test(whereRaw))) {
8376
+ return [{ id: 0, parent: 0, notused: 0, detail: `SEARCH ${tblName} USING INDEX ${idx.name} (${idx.columns.join(',')}=?)` }];
8377
+ }
8378
+ }
8379
+ return [{ id: 0, parent: 0, notused: 0, detail: `SCAN ${tblName}` }];
8380
+ }
8381
+ return [{ id: 0, parent: 0, notused: 0, detail: 'SCAN' }];
8382
+ }
8383
+
8384
+ if (/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(s)) {
8385
+ const m = s.match(/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i);
8386
+ const tbl = m && this.tables.get(m[1]);
8387
+ if (!tbl) return [];
8388
+ return tbl.columns.map((c, idx) => ({
8389
+ cid: idx,
8390
+ name: c.name,
8391
+ type: c.type || 'TEXT',
8392
+ notnull: 0,
8393
+ dflt_value: null,
8394
+ pk: c.isPk ? 1 : 0
8395
+ }));
8396
+ }
8397
+
8398
+ if (/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(s)) {
8399
+ const m = s.match(/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i);
8400
+ const tblName = m ? m[1] : '';
8401
+ const out = [];
8402
+ let seq = 0;
8403
+ for (const idx of this.indexes.values()) {
8404
+ if (idx.table === tblName) {
8405
+ out.push({
8406
+ seq: seq++,
8407
+ name: idx.name,
8408
+ unique: idx.unique ? 1 : 0,
8409
+ origin: 'c',
8410
+ partial: 0
8411
+ });
8412
+ }
8413
+ }
8414
+ return out;
8415
+ }
8416
+
8417
+ if (/^(?:INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|PRAGMA)\b/i.test(s)) {
8418
+ this.run(s, params);
8419
+ return [];
8420
+ }
8421
+
8422
+ 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);
8423
+ if (!match) {
8424
+ const noFromMatch = s.match(/^SELECT\s+([\s\S]+)$/i);
8425
+ if (noFromMatch) {
8426
+ const parts = splitCsvRespectingQuotes(noFromMatch[1]);
8427
+ const outRow = {};
8428
+ for (const p of parts) {
8429
+ const asMatch = p.match(/^([\s\S]*?)\s+AS\s+([a-zA-Z0-9_]+)$/i);
8430
+ const expr = (asMatch ? asMatch[1] : p).trim();
8431
+ const alias = (asMatch ? asMatch[2] : p).trim();
8432
+ if (/^sqlite_version\(\)$/i.test(expr)) outRow[alias] = '3.45.0';
8433
+ else if (/^['"].*['"]$/.test(expr)) outRow[alias] = expr.slice(1, -1);
8434
+ else if (!isNaN(Number(expr))) outRow[alias] = Number(expr);
8435
+ else outRow[alias] = expr;
8436
+ }
8437
+ return [outRow];
8438
+ }
8439
+ return [];
8440
+ }
8441
+ const selectColsRaw = match[1].trim();
8442
+ const tableName = match[2].trim();
8443
+ const whereClause = match[3] ? match[3].trim() : null;
8444
+ const groupByClause = match[4] ? match[4].trim() : null;
8445
+ const orderByClause = match[5] ? match[5].trim() : null;
8446
+ const limitRaw = match[6] ? match[6].trim() : null;
8447
+ const offsetRaw = match[7] ? match[7].trim() : null;
8448
+
8449
+ const table = this.tables.get(tableName);
8450
+ if (!table) return [];
8451
+
8452
+ const pList = Array.isArray(params) ? [...params] : [params];
8453
+ const filteredRows = table.rows.filter((row) => {
8454
+ const rowParams = [...pList];
8455
+ return this._matchWhere(row, whereClause, rowParams);
8456
+ });
8457
+ if (whereClause && whereClause.includes('?')) {
8458
+ const qCount = (whereClause.match(/\?/g) || []).length;
8459
+ pList.splice(0, qCount);
8460
+ }
8461
+
8462
+ const colSpecs = [];
8463
+ let hasAggregate = false;
8464
+ if (selectColsRaw !== '*') {
8465
+ const parts = splitCsvRespectingQuotes(selectColsRaw);
8466
+ for (const p of parts) {
8467
+ const asMatch = p.match(/^([\s\S]*?)\s+(?:AS\s+)?([a-zA-Z0-9_]+)$/i);
8468
+ const isFuncWithSpace = /^(AVG|SUM|COUNT|MIN|MAX)\s*\([^)]+\)$/i.test(p.trim());
8469
+ const spec = (asMatch && !isFuncWithSpace)
8470
+ ? { expr: asMatch[1].trim(), alias: asMatch[2].trim() }
8471
+ : { expr: p.trim(), alias: p.trim() };
8472
+ if (/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i.test(spec.expr)) {
8473
+ hasAggregate = true;
8474
+ }
8475
+ colSpecs.push(spec);
8476
+ }
8477
+ }
8478
+
8479
+ let outputRows = [];
8480
+ if (groupByClause) {
8481
+ const groupCol = groupByClause.trim();
8482
+ const groups = new Map();
8483
+ for (const row of filteredRows) {
8484
+ const key = row[groupCol];
8485
+ if (!groups.has(key)) groups.set(key, []);
8486
+ groups.get(key).push(row);
8487
+ }
8488
+
8489
+ for (const [key, rows] of groups.entries()) {
8490
+ const outRow = {};
8491
+ for (const col of colSpecs) {
8492
+ const expr = col.expr;
8493
+ const alias = col.alias;
8494
+ const aggMatch = expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i);
8495
+ if (aggMatch) {
8496
+ outRow[alias] = this._evalAggregate(aggMatch[1].toUpperCase(), aggMatch[2].trim(), rows);
8497
+ } else if (expr === groupCol) {
8498
+ outRow[alias] = key;
8499
+ } else {
8500
+ outRow[alias] = rows[0] ? rows[0][expr] : null;
8501
+ }
8502
+ }
8503
+ outputRows.push(outRow);
8504
+ }
8505
+ } else if (hasAggregate) {
8506
+ const outRow = {};
8507
+ for (const col of colSpecs) {
8508
+ const aggMatch = col.expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i);
8509
+ if (aggMatch) {
8510
+ outRow[col.alias] = this._evalAggregate(aggMatch[1].toUpperCase(), aggMatch[2].trim(), filteredRows);
8511
+ } else {
8512
+ outRow[col.alias] = filteredRows[0] ? filteredRows[0][col.expr] : null;
8513
+ }
8514
+ }
8515
+ outputRows.push(outRow);
8516
+ } else {
8517
+ for (const row of filteredRows) {
8518
+ if (selectColsRaw === '*') {
8519
+ outputRows.push(Object.assign({}, row));
8520
+ } else {
8521
+ const outRow = {};
8522
+ for (const col of colSpecs) {
8523
+ outRow[col.alias] = row[col.expr];
8524
+ }
8525
+ outputRows.push(outRow);
8526
+ }
8527
+ }
8528
+ }
8529
+
8530
+ if (orderByClause) {
8531
+ const parts = orderByClause.trim().split(/\s+/);
8532
+ const orderCol = parts[0];
8533
+ const desc = parts[1] && parts[1].toUpperCase() === 'DESC';
8534
+ outputRows.sort((a, b) => {
8535
+ const valA = a[orderCol];
8536
+ const valB = b[orderCol];
8537
+ if (valA === valB) return 0;
8538
+ if (valA === undefined) return 1;
8539
+ if (valB === undefined) return -1;
8540
+ const res = valA > valB ? 1 : -1;
8541
+ return desc ? -res : res;
8542
+ });
8543
+ }
8544
+
8545
+ if (limitRaw !== null) {
8546
+ const limitVal = limitRaw === '?' ? Number(pList.shift() || 0) : Number(limitRaw);
8547
+ const offsetVal = offsetRaw !== null ? (offsetRaw === '?' ? Number(pList.shift() || 0) : Number(offsetRaw)) : 0;
8548
+ outputRows = outputRows.slice(offsetVal, offsetVal + limitVal);
8549
+ }
8550
+
8551
+ return outputRows;
8552
+ }
8553
+ };
8554
+ }
8555
+
7994
8556
  return {
7995
8557
  VirtualBuffer,
7996
8558
  VirtualCrypto,
@@ -8009,6 +8571,7 @@ function __initVirtualRuntime(rootScope) {
8009
8571
  createVirtualFs,
8010
8572
  createVirtualHttp,
8011
8573
  createVirtualNet,
8574
+ createSqliteDatabase,
8012
8575
  transpileTS,
8013
8576
  transpileForBrowser,
8014
8577
  preloadNpmPackages,
@@ -8316,6 +8879,7 @@ export const VirtualDns: any = _runtimeApi.VirtualDns;
8316
8879
  export const createVirtualFs: (options?: any) => any = _runtimeApi.createVirtualFs;
8317
8880
  export const createVirtualHttp: (portTable?: any, vfs?: any) => any = _runtimeApi.createVirtualHttp;
8318
8881
  export const createVirtualNet: (portTable?: any) => any = _runtimeApi.createVirtualNet;
8882
+ export const createSqliteDatabase: (vfs?: any, getCwd?: () => string) => any = _runtimeApi.createSqliteDatabase;
8319
8883
  export const transpileTS: (code: string, filename?: string) => string = _runtimeApi.transpileTS;
8320
8884
  export const transpileForBrowser: (source: string, filename?: string) => string = _runtimeApi.transpileForBrowser;
8321
8885
  export const preloadNpmPackages: (