@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/runtime.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
@@ -2612,6 +2612,7 @@ function __initVirtualRuntime(rootScope) {
2612
2612
  function createVirtualPortTable() {
2613
2613
  const table = new Map();
2614
2614
  const listeners = new Map(); // event name -> Set<Function>
2615
+ const chaosRules = new Map(); // port -> ChaosRule
2615
2616
 
2616
2617
  function emit(event, ...args) {
2617
2618
  const set = listeners.get(event);
@@ -2627,6 +2628,43 @@ function __initVirtualRuntime(rootScope) {
2627
2628
  }
2628
2629
  }
2629
2630
 
2631
+ function normalizeChaosRule(port, partial = {}, existing = null) {
2632
+ const p = Number(port);
2633
+ const base = existing || {
2634
+ port: p,
2635
+ latencyMs: 0,
2636
+ jitterMs: 0,
2637
+ dropRate: 0,
2638
+ errorRate: 0,
2639
+ statusCode: 503,
2640
+ partitionFromPorts: [],
2641
+ crashed: false
2642
+ };
2643
+ const merged = Object.assign({}, base, partial, { port: p });
2644
+ merged.latencyMs = Math.max(0, Number(merged.latencyMs) || 0);
2645
+ merged.jitterMs = Math.max(0, Number(merged.jitterMs) || 0);
2646
+ merged.dropRate = Math.max(0, Math.min(1, Number(merged.dropRate) || 0));
2647
+ merged.errorRate = Math.max(0, Math.min(1, Number(merged.errorRate) || 0));
2648
+ merged.statusCode = Number(merged.statusCode) || 503;
2649
+ merged.partitionFromPorts = Array.isArray(merged.partitionFromPorts)
2650
+ ? Array.from(new Set(merged.partitionFromPorts.map(Number).filter((n) => Number.isFinite(n) && n > 0)))
2651
+ : [];
2652
+ merged.crashed = Boolean(merged.crashed);
2653
+ return merged;
2654
+ }
2655
+
2656
+ function isRuleActive(rule) {
2657
+ if (!rule) return false;
2658
+ return Boolean(
2659
+ rule.crashed ||
2660
+ rule.latencyMs > 0 ||
2661
+ rule.jitterMs > 0 ||
2662
+ rule.dropRate > 0 ||
2663
+ rule.errorRate > 0 ||
2664
+ (Array.isArray(rule.partitionFromPorts) && rule.partitionFromPorts.length > 0)
2665
+ );
2666
+ }
2667
+
2630
2668
  return {
2631
2669
  on(event, fn) {
2632
2670
  if (typeof fn !== 'function') return () => {};
@@ -2692,22 +2730,125 @@ function __initVirtualRuntime(rootScope) {
2692
2730
  listServers() {
2693
2731
  return Array.from(table.values());
2694
2732
  },
2733
+ setChaosRule(port, partial = {}) {
2734
+ const p = Number(port);
2735
+ const updated = normalizeChaosRule(p, partial, chaosRules.get(p) || null);
2736
+ if (isRuleActive(updated)) {
2737
+ chaosRules.set(p, updated);
2738
+ } else {
2739
+ chaosRules.delete(p);
2740
+ }
2741
+ emit('chaos', p, updated);
2742
+ return updated;
2743
+ },
2744
+ getChaosRule(port) {
2745
+ return chaosRules.get(Number(port)) || null;
2746
+ },
2747
+ listChaosRules() {
2748
+ return Array.from(chaosRules.values());
2749
+ },
2750
+ clearChaosRules(port) {
2751
+ if (port !== undefined && port !== null && port !== '') {
2752
+ const p = Number(port);
2753
+ const deleted = chaosRules.delete(p);
2754
+ emit('chaos', p, null);
2755
+ return deleted;
2756
+ }
2757
+ chaosRules.clear();
2758
+ emit('chaos', null, null);
2759
+ return true;
2760
+ },
2695
2761
  async dispatchRequest(url, init = {}) {
2696
2762
  const parsed = new URL(url);
2697
2763
  const port = Number(parsed.port || (parsed.protocol === 'https:' ? 443 : 80));
2764
+ const rawHdrs = (init && init.headers) || {};
2765
+ const hdrFromPort = typeof rawHdrs.get === 'function'
2766
+ ? rawHdrs.get('x-codelab-from-port')
2767
+ : (rawHdrs['x-codelab-from-port'] || rawHdrs['X-CodeLab-From-Port']);
2768
+ const fromPort = Number((init && init._fromPort) || hdrFromPort || 0) || null;
2769
+ const rule = chaosRules.get(port);
2770
+ let appliedDelayMs = 0;
2771
+
2772
+ if (rule) {
2773
+ let delay = Number(rule.latencyMs) || 0;
2774
+ if (rule.jitterMs > 0) {
2775
+ delay += Math.round((Math.random() * 2 - 1) * Number(rule.jitterMs));
2776
+ }
2777
+ delay = Math.max(0, delay);
2778
+ if (delay > 0) {
2779
+ appliedDelayMs = delay;
2780
+ await new Promise((r) => setTimeout(r, delay));
2781
+ }
2782
+
2783
+ if (rule.crashed) {
2784
+ const err = new Error(`connect ECONNREFUSED 127.0.0.1:${port} (chaos: node crashed)`);
2785
+ err.code = 'ECONNREFUSED';
2786
+ err.chaosEffect = 'CRASHED';
2787
+ err.fromPort = fromPort;
2788
+ throw err;
2789
+ }
2790
+
2791
+ if (fromPort && Array.isArray(rule.partitionFromPorts) && rule.partitionFromPorts.includes(fromPort)) {
2792
+ const err = new Error(`connect EHOSTUNREACH 127.0.0.1:${port} (chaos: network partition from :${fromPort})`);
2793
+ err.code = 'EHOSTUNREACH';
2794
+ err.chaosEffect = `PARTITION(:${fromPort}-x->:${port})`;
2795
+ err.fromPort = fromPort;
2796
+ throw err;
2797
+ }
2798
+
2799
+ if (rule.dropRate > 0 && Math.random() < rule.dropRate) {
2800
+ const err = new Error(`socket hang up 127.0.0.1:${port} (chaos: packet dropped)`);
2801
+ err.code = 'ETIMEDOUT';
2802
+ err.chaosEffect = 'DROPPED';
2803
+ err.fromPort = fromPort;
2804
+ throw err;
2805
+ }
2806
+
2807
+ if (rule.errorRate > 0 && Math.random() < rule.errorRate) {
2808
+ const status = Number(rule.statusCode) || 503;
2809
+ const statusText = status === 429
2810
+ ? 'Too Many Requests'
2811
+ : (status === 504 ? 'Gateway Timeout' : 'Service Unavailable');
2812
+ const chaosTag = appliedDelayMs > 0 ? `ERROR_${status}+${appliedDelayMs}ms` : `ERROR_${status}`;
2813
+ const res = new Response(
2814
+ JSON.stringify({ error: `${statusText} (Chaos Injected)`, chaos: true, port, status }),
2815
+ {
2816
+ status,
2817
+ statusText,
2818
+ headers: {
2819
+ 'content-type': 'application/json',
2820
+ 'x-codelab-chaos': chaosTag
2821
+ }
2822
+ }
2823
+ );
2824
+ res._chaosEffect = chaosTag;
2825
+ res._fromPort = fromPort;
2826
+ return res;
2827
+ }
2828
+ }
2829
+
2698
2830
  const entry = table.get(port);
2699
2831
  if (!entry) {
2700
2832
  const err = new Error(`connect ECONNREFUSED 127.0.0.1:${port}`);
2701
2833
  err.code = 'ECONNREFUSED';
2834
+ err.fromPort = fromPort;
2702
2835
  throw err;
2703
2836
  }
2837
+ let res;
2704
2838
  if (entry.fetch) {
2705
- return entry.fetch(new Request(url, init));
2839
+ res = await entry.fetch(new Request(url, init));
2840
+ } else if (entry.server && typeof entry.server.dispatchRequest === 'function') {
2841
+ res = await entry.server.dispatchRequest(url, init);
2842
+ } else {
2843
+ res = new Response('OK', { status: 200 });
2706
2844
  }
2707
- if (entry.server && typeof entry.server.dispatchRequest === 'function') {
2708
- return entry.server.dispatchRequest(url, init);
2845
+ if (res && typeof res === 'object') {
2846
+ res._fromPort = fromPort;
2847
+ if (appliedDelayMs > 0 && !res._chaosEffect) {
2848
+ res._chaosEffect = `DELAY_+${appliedDelayMs}ms`;
2849
+ }
2709
2850
  }
2710
- return new Response('OK', { status: 200 });
2851
+ return res;
2711
2852
  }
2712
2853
  };
2713
2854
  }
@@ -3039,6 +3180,78 @@ function __initVirtualRuntime(rootScope) {
3039
3180
  return;
3040
3181
  }
3041
3182
  const server = activeServers.get(this.port);
3183
+ const hasChaosRule = Boolean(
3184
+ activePortTable &&
3185
+ typeof activePortTable.getChaosRule === 'function' &&
3186
+ activePortTable.getChaosRule(this.port)
3187
+ );
3188
+ const hasPortTableServer = Boolean(
3189
+ activePortTable &&
3190
+ typeof activePortTable.getServer === 'function' &&
3191
+ activePortTable.getServer(this.port)
3192
+ );
3193
+ if ((!server || !server._listening || hasChaosRule) && activePortTable && (hasPortTableServer || hasChaosRule) && typeof activePortTable.dispatchRequest === 'function') {
3194
+ let inferredFromPort = null;
3195
+ if (activeServers.size > 0) {
3196
+ const firstLocalPort = Array.from(activeServers.keys()).find((p) => Number(p) !== Number(this.port));
3197
+ if (firstLocalPort) inferredFromPort = firstLocalPort;
3198
+ } else if (resourceTracker && resourceTracker.pid && typeof activePortTable.listServers === 'function') {
3199
+ const owned = activePortTable.listServers().find((s) => s && s.pid === resourceTracker.pid && Number(s.port) !== Number(this.port));
3200
+ if (owned) inferredFromPort = owned.port;
3201
+ }
3202
+ const reqBody = this._bodyChunks.length > 0 ? VirtualBuffer.concat(this._bodyChunks) : undefined;
3203
+ const fullUrl = `http://${this.host}:${this.port}${this.path.startsWith('/') ? '' : '/'}${this.path}`;
3204
+ activePortTable.dispatchRequest(fullUrl, {
3205
+ method: this.method,
3206
+ headers: { ...this.headers },
3207
+ body: reqBody,
3208
+ _fromPort: inferredFromPort
3209
+ }).then(async (res) => {
3210
+ if (this.destroyed) {
3211
+ this._finishInFlight();
3212
+ return;
3213
+ }
3214
+ const resHeaders = {};
3215
+ if (res && res.headers && typeof res.headers.forEach === 'function') {
3216
+ res.headers.forEach((v, k) => { resHeaders[String(k).toLowerCase()] = String(v); });
3217
+ }
3218
+ let buf = VirtualBuffer.alloc(0);
3219
+ if (res && typeof res.arrayBuffer === 'function') {
3220
+ const ab = await res.arrayBuffer();
3221
+ buf = VirtualBuffer.from(ab);
3222
+ }
3223
+ traceEntry.status = (res && res.status) || 200;
3224
+ traceEntry.durationMs = Math.max(0, performance.now() - traceEntry._t0);
3225
+ traceEntry.responseBytes = buf.length;
3226
+ traceEntry.responseHeaders = resHeaders;
3227
+ if (inferredFromPort) traceEntry.fromPort = inferredFromPort;
3228
+ if (res && res._chaosEffect) traceEntry.chaosEffect = res._chaosEffect;
3229
+ const clientRes = new IncomingMessage({
3230
+ statusCode: (res && res.status) || 200,
3231
+ headers: resHeaders
3232
+ });
3233
+ this._onResponseHeaders(clientRes);
3234
+ if (buf.length > 0) clientRes._pushData(buf);
3235
+ clientRes._pushEnd();
3236
+ this._finishInFlight();
3237
+ }).catch((err) => {
3238
+ if (this.destroyed) {
3239
+ this._finishInFlight();
3240
+ return;
3241
+ }
3242
+ err.errno = err.errno || -61;
3243
+ err.syscall = err.syscall || 'connect';
3244
+ err.address = this.host;
3245
+ err.port = this.port;
3246
+ traceEntry.status = err.code || 'ECONNREFUSED';
3247
+ traceEntry.durationMs = Math.max(0, performance.now() - traceEntry._t0);
3248
+ if (inferredFromPort) traceEntry.fromPort = inferredFromPort;
3249
+ if (err && err.chaosEffect) traceEntry.chaosEffect = err.chaosEffect;
3250
+ this._finishInFlight();
3251
+ this.emit('error', err);
3252
+ });
3253
+ return;
3254
+ }
3042
3255
  if (!server || !server._listening) {
3043
3256
  const err = new Error(`connect ECONNREFUSED ${this.host}:${this.port}`);
3044
3257
  err.code = 'ECONNREFUSED';
@@ -6617,411 +6830,114 @@ function __initVirtualRuntime(rootScope) {
6617
6830
  });
6618
6831
  });
6619
6832
 
6620
- class SqliteDatabase {
6621
- constructor(filename = ':memory:') {
6622
- this.filename = filename;
6623
- this.tables = new Map();
6624
- }
6625
-
6626
- run(sql, params = []) {
6627
- const stmt = sql.trim();
6628
- if (/^CREATE\s+TABLE/i.test(stmt)) {
6629
- const match = stmt.match(/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s*\((.*)\)/is);
6630
- if (match) {
6631
- const tableName = match[1];
6632
- const colDefs = match[2].split(',').map(c => c.trim());
6633
- const cols = [];
6634
- for (const c of colDefs) {
6635
- const parts = c.split(/\s+/);
6636
- const colName = parts[0];
6637
- const isPk = /PRIMARY\s+KEY/i.test(c);
6638
- const isAuto = /AUTOINCREMENT/i.test(c) || (/INTEGER/i.test(parts[1]) && isPk);
6639
- cols.push({ name: colName, type: parts[1] || 'TEXT', isPk, isAuto });
6640
- }
6641
- if (!this.tables.has(tableName)) {
6642
- this.tables.set(tableName, { columns: cols, rows: [], autoInc: 0 });
6643
- }
6644
- }
6645
- return { changes: 0, lastInsertRowid: 0 };
6646
- }
6647
-
6648
- if (/^DROP\s+TABLE/i.test(stmt)) {
6649
- const match = stmt.match(/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);
6650
- if (match) this.tables.delete(match[1]);
6651
- return { changes: 0, lastInsertRowid: 0 };
6652
- }
6653
-
6654
- if (/^INSERT\s+INTO/i.test(stmt)) {
6655
- const match = stmt.match(/^INSERT\s+INTO\s+([a-zA-Z0-9_]+)(?:\s*\(([^)]+)\))?\s*VALUES\s*\((.*)\)/is);
6656
- if (match) {
6657
- const tableName = match[1];
6658
- const table = this.tables.get(tableName);
6659
- if (!table) throw new Error(`no such table: ${tableName}`);
6660
- const colNames = match[2] ? match[2].split(',').map(s => s.trim()) : table.columns.filter(c => !c.isPk).map(c => c.name);
6661
- const valExprs = match[3].split(',').map(s => s.trim());
6662
- const pList = Array.isArray(params) ? [...params] : [params];
6663
- const row = {};
6833
+ const SqliteDatabase = createSqliteDatabase(vfs, () => sandboxProcess.cwd());
6664
6834
 
6665
- table.autoInc++;
6666
- const pkCol = table.columns.find(c => c.isPk);
6667
- if (pkCol) {
6668
- row[pkCol.name] = table.autoInc;
6669
- }
6835
+ function crc32Hash(str) {
6836
+ return VirtualZlib.crc32( typeof str === 'string' || str instanceof Uint8Array ? str : String(str) );
6837
+ }
6670
6838
 
6671
- for (let i = 0; i < colNames.length; i++) {
6672
- const cName = colNames[i];
6673
- const expr = valExprs[i] !== undefined ? valExprs[i] : '?';
6674
- if (expr === '?') {
6675
- row[cName] = pList.shift();
6676
- } else if (/^['"].*['"]$/.test(expr)) {
6677
- row[cName] = expr.slice(1, -1);
6678
- } else if (!isNaN(Number(expr))) {
6679
- row[cName] = Number(expr);
6680
- } else {
6681
- row[cName] = expr;
6682
- }
6683
- }
6684
- table.rows.push(row);
6685
- return { changes: 1, lastInsertRowid: table.autoInc };
6686
- }
6687
- }
6839
+ const bunHashFn = function hash(val) {
6840
+ return crc32Hash(val);
6841
+ };
6842
+ bunHashFn.crc32 = (val) => crc32Hash(val);
6843
+ bunHashFn.cityHash64 = (val) => {
6844
+ const h1 = crc32Hash(val);
6845
+ const h2 = crc32Hash(String(val) + ':seed64');
6846
+ return (BigInt(h1) << 32n) | BigInt(h2);
6847
+ };
6688
6848
 
6689
- if (/^DELETE\s+FROM/i.test(stmt)) {
6690
- const match = stmt.match(/^DELETE\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+(.*))?$/is);
6691
- if (match) {
6692
- const table = this.tables.get(match[1]);
6693
- if (!table) throw new Error(`no such table: ${match[1]}`);
6694
- const whereClause = match[2] ? match[2].trim() : null;
6695
- const pList = Array.isArray(params) ? [...params] : [params];
6696
- const beforeLen = table.rows.length;
6697
- if (!whereClause) {
6698
- table.rows = [];
6699
- } else {
6700
- table.rows = table.rows.filter(r => !this._matchWhere(r, whereClause, pList));
6701
- }
6702
- return { changes: beforeLen - table.rows.length, lastInsertRowid: table.autoInc };
6703
- }
6704
- }
6849
+ function deepEquals(a, b) {
6850
+ return isDeepEqual(a, b, true);
6851
+ }
6705
6852
 
6706
- if (/^UPDATE\s+/i.test(stmt)) {
6707
- const match = stmt.match(/^UPDATE\s+([a-zA-Z0-9_]+)\s+SET\s+(.*?)(?:\s+WHERE\s+(.*))?$/is);
6708
- if (match) {
6709
- const table = this.tables.get(match[1]);
6710
- if (!table) throw new Error(`no such table: ${match[1]}`);
6711
- const setParts = match[2].split(',').map(s => s.trim());
6712
- const whereClause = match[3] ? match[3].trim() : null;
6713
- const pList = Array.isArray(params) ? [...params] : [params];
6714
- let changes = 0;
6715
- for (const row of table.rows) {
6716
- const rowParams = [...pList];
6717
- const setUpdates = [];
6718
- for (const sp of setParts) {
6719
- const eqIdx = sp.indexOf('=');
6720
- const col = sp.slice(0, eqIdx).trim();
6721
- let valExpr = sp.slice(eqIdx + 1).trim();
6722
- let val = valExpr === '?' ? rowParams.shift() : (/^['"].*['"]$/.test(valExpr) ? valExpr.slice(1, -1) : (!isNaN(Number(valExpr)) ? Number(valExpr) : valExpr));
6723
- setUpdates.push([col, val]);
6724
- }
6725
- if (!whereClause || this._matchWhere(row, whereClause, rowParams)) {
6726
- for (const [col, val] of setUpdates) row[col] = val;
6727
- changes++;
6728
- }
6729
- }
6730
- return { changes, lastInsertRowid: table.autoInc };
6853
+ const BunObj = {
6854
+ version: '1.1.0',
6855
+ serve(opts = {}) {
6856
+ const port = Number(opts.port || 3000);
6857
+ const hostname = opts.hostname || '127.0.0.1';
6858
+ const serverObj = {
6859
+ port,
6860
+ hostname,
6861
+ development: false,
6862
+ stop() {
6863
+ activePortTable.unregisterServer(port);
6731
6864
  }
6732
- }
6733
-
6734
- return { changes: 0, lastInsertRowid: 0 };
6735
- }
6736
-
6737
- _matchWhere(row, whereClause, pList) {
6738
- if (!whereClause) return true;
6739
- const eqMatch = whereClause.match(/^([a-zA-Z0-9_]+)\s*(=|!=|<>|>=|<=|>|<)\s*(.*)$/);
6740
- if (eqMatch) {
6741
- const col = eqMatch[1].trim();
6742
- const op = eqMatch[2];
6743
- let expected = eqMatch[3].trim();
6744
- if (expected === '?') {
6745
- expected = pList.shift();
6746
- } else if (/^['"].*['"]$/.test(expected)) {
6747
- expected = expected.slice(1, -1);
6748
- } else if (!isNaN(Number(expected))) {
6749
- expected = Number(expected);
6750
- }
6751
- const actual = row[col];
6752
- if (op === '=') return String(actual) === String(expected);
6753
- if (op === '!=' || op === '<>') return String(actual) !== String(expected);
6754
- if (op === '>') return Number(actual) > Number(expected);
6755
- if (op === '<') return Number(actual) < Number(expected);
6756
- if (op === '>=') return Number(actual) >= Number(expected);
6757
- if (op === '<=') return Number(actual) <= Number(expected);
6758
- }
6759
- return true;
6760
- }
6761
-
6762
- exec(sql) {
6763
- const statements = sql.split(';').map(s => s.trim()).filter(Boolean);
6764
- for (const s of statements) {
6765
- this.run(s);
6766
- }
6767
- }
6768
-
6769
- transaction(fn) {
6770
- return (...args) => fn(...args);
6771
- }
6772
-
6773
- close() {}
6774
-
6775
- query(sql) {
6776
- const db = this;
6865
+ };
6866
+ activePortTable.registerServer(port, {
6867
+ server: serverObj,
6868
+ name: opts.name || 'bun-server',
6869
+ port,
6870
+ pid: resourceTracker.pid || 1,
6871
+ fetch: opts.fetch ? opts.fetch.bind(serverObj) : undefined,
6872
+ stop: () => serverObj.stop()
6873
+ });
6874
+ return serverObj;
6875
+ },
6876
+ file(p) {
6877
+ const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(p));
6777
6878
  return {
6778
- all(...args) {
6779
- let params = args;
6780
- if (args.length === 1 && Array.isArray(args[0])) params = args[0];
6781
- return db._executeSelect(sql, params);
6879
+ name: VirtualPath.basename(resolved),
6880
+ get size() {
6881
+ try {
6882
+ return vfs.statSync(resolved).size;
6883
+ } catch (_) {
6884
+ return 0;
6885
+ }
6782
6886
  },
6783
- get(...args) {
6784
- const rows = this.all(...args);
6785
- return rows[0] || null;
6887
+ async exists() {
6888
+ return vfs.existsSync(resolved);
6786
6889
  },
6787
- values(...args) {
6788
- const rows = this.all(...args);
6789
- return rows.map(r => Object.values(r));
6890
+ async text() {
6891
+ return vfs.readFileSync(resolved, 'utf8');
6790
6892
  },
6791
- run(...args) {
6792
- let params = args;
6793
- if (args.length === 1 && Array.isArray(args[0])) params = args[0];
6794
- return db.run(sql, params);
6893
+ async json() {
6894
+ return JSON.parse(vfs.readFileSync(resolved, 'utf8'));
6895
+ },
6896
+ async arrayBuffer() {
6897
+ const buf = vfs.readFileSync(resolved);
6898
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
6795
6899
  }
6796
6900
  };
6901
+ },
6902
+ async write(dest, data) {
6903
+ const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(dest));
6904
+ const dir = VirtualPath.dirname(resolved);
6905
+ if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
6906
+ let buf;
6907
+ if (typeof data === 'string') {
6908
+ buf = VirtualBuffer.from(data, 'utf8');
6909
+ } else if (data && data.arrayBuffer && typeof data.arrayBuffer === 'function') {
6910
+ const ab = await data.arrayBuffer();
6911
+ buf = VirtualBuffer.from(ab);
6912
+ } else if (data instanceof Uint8Array || VirtualBuffer.isBuffer(data)) {
6913
+ buf = VirtualBuffer.from(data);
6914
+ } else {
6915
+ buf = VirtualBuffer.from(String(data), 'utf8');
6916
+ }
6917
+ vfs.writeFileSync(resolved, buf);
6918
+ return buf.length;
6919
+ },
6920
+ sleep(ms) {
6921
+ return new Promise(resolve => sandboxSetTimeout(resolve, Number(ms) || 0));
6922
+ },
6923
+ hash: bunHashFn,
6924
+ deepEquals,
6925
+ inspect(val) {
6926
+ return VirtualUtil.inspect(val);
6927
+ },
6928
+ nanoseconds() {
6929
+ return Math.round(performance.now() * 1e6);
6797
6930
  }
6931
+ };
6798
6932
 
6799
- prepare(sql) {
6800
- return this.query(sql);
6801
- }
6802
-
6803
- _executeSelect(sql, params = []) {
6804
- const s = sql.trim().replace(/;$/, '');
6805
- 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);
6806
- if (!match) return [];
6807
- const selectColsRaw = match[1].trim();
6808
- const tableName = match[2].trim();
6809
- const whereClause = match[3] ? match[3].trim() : null;
6810
- const groupByClause = match[4] ? match[4].trim() : null;
6811
- const orderByClause = match[5] ? match[5].trim() : null;
6812
- const limitRaw = match[6] ? match[6].trim() : null;
6813
- const offsetRaw = match[7] ? match[7].trim() : null;
6814
-
6815
- const table = this.tables.get(tableName);
6816
- if (!table) return [];
6817
-
6818
- let pList = Array.isArray(params) ? [...params] : [params];
6819
- let filteredRows = table.rows.filter(row => {
6820
- const rowParams = [...pList];
6821
- return this._matchWhere(row, whereClause, rowParams);
6822
- });
6823
- if (whereClause && whereClause.includes('?')) {
6824
- const qCount = (whereClause.match(/\?/g) || []).length;
6825
- pList.splice(0, qCount);
6826
- }
6827
-
6828
- const colSpecs = [];
6829
- if (selectColsRaw !== '*') {
6830
- const parts = selectColsRaw.split(',').map(p => p.trim());
6831
- for (const p of parts) {
6832
- const asMatch = p.match(/^(.*?)\s+(?:as\s+)?([a-zA-Z0-9_]+)$/i);
6833
- if (asMatch) {
6834
- colSpecs.push({ expr: asMatch[1].trim(), alias: asMatch[2].trim() });
6835
- } else {
6836
- colSpecs.push({ expr: p, alias: p });
6837
- }
6838
- }
6839
- }
6840
-
6841
- let outputRows = [];
6842
- if (groupByClause) {
6843
- const groupCol = groupByClause.trim();
6844
- const groups = new Map();
6845
- for (const row of filteredRows) {
6846
- const key = row[groupCol];
6847
- if (!groups.has(key)) groups.set(key, []);
6848
- groups.get(key).push(row);
6849
- }
6850
-
6851
- for (const [key, rows] of groups.entries()) {
6852
- const outRow = {};
6853
- for (const col of colSpecs) {
6854
- const expr = col.expr;
6855
- const alias = col.alias;
6856
- const aggMatch = expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\(([a-zA-Z0-9_*]+)\)$/i);
6857
- if (aggMatch) {
6858
- const fn = aggMatch[1].toUpperCase();
6859
- const aggCol = aggMatch[2];
6860
- if (fn === 'COUNT') {
6861
- outRow[alias] = rows.length;
6862
- } else if (fn === 'AVG') {
6863
- const sum = rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
6864
- outRow[alias] = rows.length > 0 ? sum / rows.length : 0;
6865
- } else if (fn === 'SUM') {
6866
- outRow[alias] = rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
6867
- } else if (fn === 'MIN') {
6868
- outRow[alias] = Math.min(...rows.map(r => Number(r[aggCol]) || 0));
6869
- } else if (fn === 'MAX') {
6870
- outRow[alias] = Math.max(...rows.map(r => Number(r[aggCol]) || 0));
6871
- }
6872
- } else if (expr === groupCol) {
6873
- outRow[alias] = key;
6874
- } else {
6875
- outRow[alias] = rows[0] ? rows[0][expr] : null;
6876
- }
6877
- }
6878
- outputRows.push(outRow);
6879
- }
6880
- } else {
6881
- for (const row of filteredRows) {
6882
- if (selectColsRaw === '*') {
6883
- outputRows.push(Object.assign({}, row));
6884
- } else {
6885
- const outRow = {};
6886
- for (const col of colSpecs) {
6887
- outRow[col.alias] = row[col.expr];
6888
- }
6889
- outputRows.push(outRow);
6890
- }
6891
- }
6892
- }
6893
-
6894
- if (orderByClause) {
6895
- const parts = orderByClause.trim().split(/\s+/);
6896
- const orderCol = parts[0];
6897
- const desc = parts[1] && parts[1].toUpperCase() === 'DESC';
6898
- outputRows.sort((a, b) => {
6899
- const valA = a[orderCol];
6900
- const valB = b[orderCol];
6901
- if (valA === valB) return 0;
6902
- if (valA === undefined) return 1;
6903
- if (valB === undefined) return -1;
6904
- const res = valA > valB ? 1 : -1;
6905
- return desc ? -res : res;
6906
- });
6907
- }
6908
-
6909
- if (limitRaw !== null) {
6910
- const limitVal = limitRaw === '?' ? Number(pList.shift() || 0) : Number(limitRaw);
6911
- const offsetVal = offsetRaw !== null ? (offsetRaw === '?' ? Number(pList.shift() || 0) : Number(offsetRaw)) : 0;
6912
- outputRows = outputRows.slice(offsetVal, offsetVal + limitVal);
6913
- }
6914
-
6915
- return outputRows;
6916
- }
6917
- }
6918
-
6919
- function crc32Hash(str) {
6920
- return VirtualZlib.crc32( typeof str === 'string' || str instanceof Uint8Array ? str : String(str) );
6921
- }
6922
-
6923
- const bunHashFn = function hash(val) {
6924
- return crc32Hash(val);
6925
- };
6926
- bunHashFn.crc32 = (val) => crc32Hash(val);
6927
- bunHashFn.cityHash64 = (val) => {
6928
- const h1 = crc32Hash(val);
6929
- const h2 = crc32Hash(String(val) + ':seed64');
6930
- return (BigInt(h1) << 32n) | BigInt(h2);
6931
- };
6932
-
6933
- function deepEquals(a, b) {
6934
- return isDeepEqual(a, b, true);
6935
- }
6936
-
6937
- const BunObj = {
6938
- version: '1.1.0',
6939
- serve(opts = {}) {
6940
- const port = Number(opts.port || 3000);
6941
- const hostname = opts.hostname || '127.0.0.1';
6942
- const serverObj = {
6943
- port,
6944
- hostname,
6945
- development: false,
6946
- stop() {
6947
- activePortTable.unregisterServer(port);
6948
- }
6949
- };
6950
- activePortTable.registerServer(port, {
6951
- server: serverObj,
6952
- name: opts.name || 'bun-server',
6953
- port,
6954
- pid: resourceTracker.pid || 1,
6955
- fetch: opts.fetch ? opts.fetch.bind(serverObj) : undefined,
6956
- stop: () => serverObj.stop()
6957
- });
6958
- return serverObj;
6959
- },
6960
- file(p) {
6961
- const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(p));
6962
- return {
6963
- name: VirtualPath.basename(resolved),
6964
- get size() {
6965
- try {
6966
- return vfs.statSync(resolved).size;
6967
- } catch (_) {
6968
- return 0;
6969
- }
6970
- },
6971
- async exists() {
6972
- return vfs.existsSync(resolved);
6973
- },
6974
- async text() {
6975
- return vfs.readFileSync(resolved, 'utf8');
6976
- },
6977
- async json() {
6978
- return JSON.parse(vfs.readFileSync(resolved, 'utf8'));
6979
- },
6980
- async arrayBuffer() {
6981
- const buf = vfs.readFileSync(resolved);
6982
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
6983
- }
6984
- };
6985
- },
6986
- async write(dest, data) {
6987
- const resolved = VirtualPath.resolve(sandboxProcess.cwd(), String(dest));
6988
- const dir = VirtualPath.dirname(resolved);
6989
- if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
6990
- let buf;
6991
- if (typeof data === 'string') {
6992
- buf = VirtualBuffer.from(data, 'utf8');
6993
- } else if (data && data.arrayBuffer && typeof data.arrayBuffer === 'function') {
6994
- const ab = await data.arrayBuffer();
6995
- buf = VirtualBuffer.from(ab);
6996
- } else if (data instanceof Uint8Array || VirtualBuffer.isBuffer(data)) {
6997
- buf = VirtualBuffer.from(data);
6998
- } else {
6999
- buf = VirtualBuffer.from(String(data), 'utf8');
7000
- }
7001
- vfs.writeFileSync(resolved, buf);
7002
- return buf.length;
7003
- },
7004
- sleep(ms) {
7005
- return new Promise(resolve => sandboxSetTimeout(resolve, Number(ms) || 0));
7006
- },
7007
- hash: bunHashFn,
7008
- deepEquals,
7009
- inspect(val) {
7010
- return VirtualUtil.inspect(val);
7011
- },
7012
- nanoseconds() {
7013
- return Math.round(performance.now() * 1e6);
7014
- }
7015
- };
7016
-
7017
- const bunTestModule = (() => {
7018
- function makeExpect(actual, isNot = false) {
7019
- const pass = (condition, msg) => {
7020
- const ok = isNot ? !condition : condition;
7021
- if (!ok) {
7022
- throw new Error(msg || `expect assertion failed: actual=${actual}`);
7023
- }
7024
- };
6933
+ const bunTestModule = (() => {
6934
+ function makeExpect(actual, isNot = false) {
6935
+ const pass = (condition, msg) => {
6936
+ const ok = isNot ? !condition : condition;
6937
+ if (!ok) {
6938
+ throw new Error(msg || `expect assertion failed: actual=${actual}`);
6939
+ }
6940
+ };
7025
6941
 
7026
6942
  const matchers = {
7027
6943
  toBe(expected) {
@@ -7668,14 +7584,25 @@ function __initVirtualRuntime(rootScope) {
7668
7584
  urlStr = String(urlOrReq);
7669
7585
  }
7670
7586
 
7587
+ let parsedLocal = null;
7671
7588
  try {
7672
7589
  const parsed = new URL(urlStr);
7673
7590
  const isLocal = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '0.0.0.0';
7674
- if (isLocal && activePortTable) {
7675
- return await activePortTable.dispatchRequest(urlStr, finalInit);
7676
- }
7591
+ if (isLocal) parsedLocal = parsed;
7677
7592
  } catch (err) {
7678
- _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
7593
+ _runtimeLogger.debug('virtualFetch local URL parse skipped', err);
7594
+ }
7595
+
7596
+ if (parsedLocal && activePortTable) {
7597
+ let dispatchInit = finalInit;
7598
+ if (!dispatchInit._fromPort && resourceTracker && resourceTracker.pid && typeof activePortTable.listServers === 'function') {
7599
+ const targetPort = Number(parsedLocal.port || (parsedLocal.protocol === 'https:' ? 443 : 80));
7600
+ const owned = activePortTable.listServers().find((s) => s && s.pid === resourceTracker.pid && Number(s.port) !== targetPort);
7601
+ if (owned) {
7602
+ dispatchInit = Object.assign({}, finalInit, { _fromPort: owned.port });
7603
+ }
7604
+ }
7605
+ return await activePortTable.dispatchRequest(urlStr, dispatchInit);
7679
7606
  }
7680
7607
 
7681
7608
  if (typeof globalThis.fetch === 'function') {
@@ -8111,6 +8038,641 @@ function __initVirtualRuntime(rootScope) {
8111
8038
  return transpileTS(source, filename, { keepEsm: true });
8112
8039
  }
8113
8040
 
8041
+ function createSqliteDatabase(vfs = null, getCwd = null) {
8042
+ function stripSqlComments(sql) {
8043
+ return String(sql || '')
8044
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
8045
+ .replace(/--[^\r\n]*/g, ' ')
8046
+ .trim();
8047
+ }
8048
+
8049
+ function splitValueTuples(rawValues) {
8050
+ const tuples = [];
8051
+ let depth = 0;
8052
+ let inQuote = null;
8053
+ let start = -1;
8054
+ for (let i = 0; i < rawValues.length; i++) {
8055
+ const ch = rawValues[i];
8056
+ if (inQuote) {
8057
+ if (ch === inQuote && rawValues[i - 1] !== '\\') inQuote = null;
8058
+ continue;
8059
+ }
8060
+ if (ch === "'" || ch === '"') {
8061
+ inQuote = ch;
8062
+ } else if (ch === '(') {
8063
+ if (depth === 0) start = i + 1;
8064
+ depth++;
8065
+ } else if (ch === ')') {
8066
+ depth--;
8067
+ if (depth === 0 && start !== -1) {
8068
+ tuples.push(rawValues.slice(start, i));
8069
+ start = -1;
8070
+ }
8071
+ }
8072
+ }
8073
+ return tuples;
8074
+ }
8075
+
8076
+ function splitCsvRespectingQuotes(str) {
8077
+ const out = [];
8078
+ let cur = '';
8079
+ let inQuote = null;
8080
+ let depth = 0;
8081
+ for (let i = 0; i < str.length; i++) {
8082
+ const ch = str[i];
8083
+ if (inQuote) {
8084
+ cur += ch;
8085
+ if (ch === inQuote && str[i - 1] !== '\\') inQuote = null;
8086
+ continue;
8087
+ }
8088
+ if (ch === "'" || ch === '"') {
8089
+ inQuote = ch;
8090
+ cur += ch;
8091
+ } else if (ch === '(') {
8092
+ depth++;
8093
+ cur += ch;
8094
+ } else if (ch === ')') {
8095
+ depth = Math.max(0, depth - 1);
8096
+ cur += ch;
8097
+ } else if (ch === ',' && depth === 0) {
8098
+ out.push(cur.trim());
8099
+ cur = '';
8100
+ } else {
8101
+ cur += ch;
8102
+ }
8103
+ }
8104
+ if (cur.trim()) out.push(cur.trim());
8105
+ return out;
8106
+ }
8107
+
8108
+ return class SqliteDatabase {
8109
+ constructor(filename = ':memory:') {
8110
+ this.filename = filename || ':memory:';
8111
+ this.tables = new Map();
8112
+ this.indexes = new Map();
8113
+ this._loadFromVfs();
8114
+ }
8115
+
8116
+ _resolveDbPath() {
8117
+ if (!this.filename || this.filename === ':memory:') return null;
8118
+ const cwd = typeof getCwd === 'function' ? getCwd() : '/workspace';
8119
+ return VirtualPath.resolve(cwd || '/workspace', String(this.filename));
8120
+ }
8121
+
8122
+ _loadFromVfs() {
8123
+ const p = this._resolveDbPath();
8124
+ if (!p || !vfs || typeof vfs.existsSync !== 'function' || !vfs.existsSync(p)) return;
8125
+ try {
8126
+ const raw = vfs.readFileSync(p, 'utf8');
8127
+ const trimmed = String(raw || '').trim();
8128
+ if (!trimmed) return;
8129
+ if (trimmed.startsWith('{')) {
8130
+ const parsed = JSON.parse(trimmed);
8131
+ if (parsed && parsed.__codelab_sqlite__) {
8132
+ if (parsed.tables && typeof parsed.tables === 'object') {
8133
+ for (const [tName, tVal] of Object.entries(parsed.tables)) {
8134
+ this.tables.set(tName, tVal);
8135
+ }
8136
+ }
8137
+ if (parsed.indexes && typeof parsed.indexes === 'object') {
8138
+ for (const [iName, iVal] of Object.entries(parsed.indexes)) {
8139
+ this.indexes.set(iName, iVal);
8140
+ }
8141
+ }
8142
+ return;
8143
+ }
8144
+ }
8145
+ this.exec(trimmed);
8146
+ } catch (err) {
8147
+ _runtimeLogger.debug('SqliteDatabase._loadFromVfs skipped', err);
8148
+ }
8149
+ }
8150
+
8151
+ _persistToVfs() {
8152
+ const p = this._resolveDbPath();
8153
+ if (!p || !vfs || typeof vfs.writeFileSync !== 'function') return;
8154
+ try {
8155
+ const dir = VirtualPath.dirname(p);
8156
+ if (typeof vfs.existsSync === 'function' && !vfs.existsSync(dir) && typeof vfs.mkdirSync === 'function') {
8157
+ vfs.mkdirSync(dir, { recursive: true });
8158
+ }
8159
+ const payload = JSON.stringify({
8160
+ __codelab_sqlite__: 1,
8161
+ tables: Object.fromEntries(this.tables),
8162
+ indexes: Object.fromEntries(this.indexes)
8163
+ });
8164
+ vfs.writeFileSync(p, payload);
8165
+ } catch (err) {
8166
+ _runtimeLogger.debug('SqliteDatabase._persistToVfs failed', err);
8167
+ }
8168
+ }
8169
+
8170
+ run(sql, params = []) {
8171
+ const stmt = stripSqlComments(sql).replace(/;$/, '').trim();
8172
+ if (!stmt) return { changes: 0, lastInsertRowid: 0 };
8173
+
8174
+ if (/^CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TABLE/i.test(stmt)) {
8175
+ 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);
8176
+ if (match) {
8177
+ const tableName = match[1];
8178
+ const colDefs = splitCsvRespectingQuotes(match[2]);
8179
+ const cols = [];
8180
+ for (const c of colDefs) {
8181
+ if (/^(PRIMARY\s+KEY|FOREIGN\s+KEY|CONSTRAINT|UNIQUE|CHECK)\b/i.test(c)) continue;
8182
+ const parts = c.split(/\s+/);
8183
+ const colName = parts[0].replace(/^["'`]|["'`]$/g, '');
8184
+ const isPk = /PRIMARY\s+KEY/i.test(c);
8185
+ const isAuto = /AUTOINCREMENT/i.test(c) || (/INTEGER/i.test(parts[1] || '') && isPk);
8186
+ cols.push({ name: colName, type: parts[1] || 'TEXT', isPk, isAuto, raw: c });
8187
+ }
8188
+ if (!this.tables.has(tableName)) {
8189
+ this.tables.set(tableName, { columns: cols, rows: [], autoInc: 0, sql: stmt });
8190
+ this._persistToVfs();
8191
+ }
8192
+ }
8193
+ return { changes: 0, lastInsertRowid: 0 };
8194
+ }
8195
+
8196
+ if (/^DROP\s+TABLE/i.test(stmt)) {
8197
+ const match = stmt.match(/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);
8198
+ if (match) {
8199
+ this.tables.delete(match[1]);
8200
+ this._persistToVfs();
8201
+ }
8202
+ return { changes: 0, lastInsertRowid: 0 };
8203
+ }
8204
+
8205
+ if (/^CREATE\s+(?:UNIQUE\s+)?INDEX/i.test(stmt)) {
8206
+ 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);
8207
+ if (match) {
8208
+ const unique = Boolean(match[1]);
8209
+ const idxName = match[2];
8210
+ const tblName = match[3];
8211
+ const cols = match[4].split(',').map((s) => s.trim().split(/\s+/)[0]);
8212
+ this.indexes.set(idxName, { name: idxName, table: tblName, columns: cols, unique, sql: stmt });
8213
+ this._persistToVfs();
8214
+ }
8215
+ return { changes: 0, lastInsertRowid: 0 };
8216
+ }
8217
+
8218
+ if (/^DROP\s+INDEX/i.test(stmt)) {
8219
+ const match = stmt.match(/^DROP\s+INDEX\s+(?:IF\s+EXISTS\s+)?([a-zA-Z0-9_]+)/i);
8220
+ if (match) {
8221
+ this.indexes.delete(match[1]);
8222
+ this._persistToVfs();
8223
+ }
8224
+ return { changes: 0, lastInsertRowid: 0 };
8225
+ }
8226
+
8227
+ if (/^ALTER\s+TABLE/i.test(stmt)) {
8228
+ const match = stmt.match(/^ALTER\s+TABLE\s+([a-zA-Z0-9_]+)\s+ADD\s+(?:COLUMN\s+)?([a-zA-Z0-9_]+)\s*(.*)$/i);
8229
+ if (match) {
8230
+ const table = this.tables.get(match[1]);
8231
+ if (table) {
8232
+ const colName = match[2];
8233
+ const colType = (match[3] || 'TEXT').split(/\s+/)[0] || 'TEXT';
8234
+ table.columns.push({ name: colName, type: colType, isPk: false, isAuto: false });
8235
+ this._persistToVfs();
8236
+ }
8237
+ }
8238
+ return { changes: 0, lastInsertRowid: 0 };
8239
+ }
8240
+
8241
+ if (/^PRAGMA\s+/i.test(stmt)) {
8242
+ return { changes: 0, lastInsertRowid: 0 };
8243
+ }
8244
+
8245
+ if (/^INSERT\s+(?:OR\s+(?:REPLACE|IGNORE)\s+)?INTO/i.test(stmt)) {
8246
+ const match = stmt.match(/^INSERT\s+(?:OR\s+(REPLACE|IGNORE)\s+)?INTO\s+([a-zA-Z0-9_]+)(?:\s*\(([^)]+)\))?\s*VALUES\s*([\s\S]*)$/i);
8247
+ if (match) {
8248
+ const conflictMode = (match[1] || '').toUpperCase();
8249
+ const tableName = match[2];
8250
+ const table = this.tables.get(tableName);
8251
+ if (!table) throw new Error(`no such table: ${tableName}`);
8252
+ const explicitCols = match[3] ? match[3].split(',').map((s) => s.trim()) : null;
8253
+ const tuples = splitValueTuples(match[4]);
8254
+ const pList = Array.isArray(params) ? [...params] : [params];
8255
+ let insertedCount = 0;
8256
+
8257
+ for (const tupleStr of (tuples.length > 0 ? tuples : [match[4].replace(/^\(|\)$/g, '')])) {
8258
+ const valExprs = splitCsvRespectingQuotes(tupleStr);
8259
+ const colNames = explicitCols
8260
+ ? explicitCols
8261
+ : (valExprs.length === table.columns.length
8262
+ ? table.columns.map((c) => c.name)
8263
+ : table.columns.filter((c) => !c.isPk).map((c) => c.name));
8264
+ const row = {};
8265
+ const pkCol = table.columns.find((c) => c.isPk);
8266
+
8267
+ for (let i = 0; i < colNames.length; i++) {
8268
+ const cName = colNames[i];
8269
+ const expr = valExprs[i] !== undefined ? valExprs[i] : '?';
8270
+ if (expr === '?') {
8271
+ row[cName] = pList.shift();
8272
+ } else if (/^['"][\s\S]*['"]$/.test(expr)) {
8273
+ row[cName] = expr.slice(1, -1).replace(/''/g, "'");
8274
+ } else if (/^null$/i.test(expr)) {
8275
+ row[cName] = null;
8276
+ } else if (!isNaN(Number(expr))) {
8277
+ row[cName] = Number(expr);
8278
+ } else {
8279
+ row[cName] = expr;
8280
+ }
8281
+ }
8282
+
8283
+ if (pkCol) {
8284
+ if (row[pkCol.name] === undefined || row[pkCol.name] === null) {
8285
+ table.autoInc++;
8286
+ row[pkCol.name] = table.autoInc;
8287
+ } else if (typeof row[pkCol.name] === 'number' && row[pkCol.name] > table.autoInc) {
8288
+ table.autoInc = row[pkCol.name];
8289
+ }
8290
+ const existingIdx = table.rows.findIndex((r) => String(r[pkCol.name]) === String(row[pkCol.name]));
8291
+ if (existingIdx !== -1) {
8292
+ if (conflictMode === 'IGNORE') continue;
8293
+ if (conflictMode === 'REPLACE') {
8294
+ table.rows[existingIdx] = row;
8295
+ insertedCount++;
8296
+ continue;
8297
+ }
8298
+ }
8299
+ } else {
8300
+ table.autoInc++;
8301
+ }
8302
+
8303
+ table.rows.push(row);
8304
+ insertedCount++;
8305
+ }
8306
+ this._persistToVfs();
8307
+ return { changes: insertedCount, lastInsertRowid: table.autoInc };
8308
+ }
8309
+ }
8310
+
8311
+ if (/^DELETE\s+FROM/i.test(stmt)) {
8312
+ const match = stmt.match(/^DELETE\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+([\s\S]*))?$/i);
8313
+ if (match) {
8314
+ const table = this.tables.get(match[1]);
8315
+ if (!table) throw new Error(`no such table: ${match[1]}`);
8316
+ const whereClause = match[2] ? match[2].trim() : null;
8317
+ const pList = Array.isArray(params) ? [...params] : [params];
8318
+ const beforeLen = table.rows.length;
8319
+ if (!whereClause) {
8320
+ table.rows = [];
8321
+ } else {
8322
+ table.rows = table.rows.filter((r) => !this._matchWhere(r, whereClause, [...pList]));
8323
+ }
8324
+ this._persistToVfs();
8325
+ return { changes: beforeLen - table.rows.length, lastInsertRowid: table.autoInc };
8326
+ }
8327
+ }
8328
+
8329
+ if (/^UPDATE\s+/i.test(stmt)) {
8330
+ const match = stmt.match(/^UPDATE\s+([a-zA-Z0-9_]+)\s+SET\s+([\s\S]*?)(?:\s+WHERE\s+([\s\S]*))?$/i);
8331
+ if (match) {
8332
+ const table = this.tables.get(match[1]);
8333
+ if (!table) throw new Error(`no such table: ${match[1]}`);
8334
+ const setParts = splitCsvRespectingQuotes(match[2]);
8335
+ const whereClause = match[3] ? match[3].trim() : null;
8336
+ const pList = Array.isArray(params) ? [...params] : [params];
8337
+ let changes = 0;
8338
+ for (const row of table.rows) {
8339
+ const rowParams = [...pList];
8340
+ const setUpdates = [];
8341
+ for (const sp of setParts) {
8342
+ const eqIdx = sp.indexOf('=');
8343
+ const col = sp.slice(0, eqIdx).trim();
8344
+ const valExpr = sp.slice(eqIdx + 1).trim();
8345
+ const val = valExpr === '?'
8346
+ ? rowParams.shift()
8347
+ : (/^['"][\s\S]*['"]$/.test(valExpr)
8348
+ ? valExpr.slice(1, -1)
8349
+ : (!isNaN(Number(valExpr)) ? Number(valExpr) : valExpr));
8350
+ setUpdates.push([col, val]);
8351
+ }
8352
+ if (!whereClause || this._matchWhere(row, whereClause, rowParams)) {
8353
+ for (const [col, val] of setUpdates) row[col] = val;
8354
+ changes++;
8355
+ }
8356
+ }
8357
+ this._persistToVfs();
8358
+ return { changes, lastInsertRowid: table.autoInc };
8359
+ }
8360
+ }
8361
+
8362
+ return { changes: 0, lastInsertRowid: 0 };
8363
+ }
8364
+
8365
+ _matchWhere(row, whereClause, pList) {
8366
+ if (!whereClause) return true;
8367
+ const andParts = whereClause.split(/\s+AND\s+/i);
8368
+ for (const part of andParts) {
8369
+ const trimmed = part.trim();
8370
+ const isNullMatch = trimmed.match(/^([a-zA-Z0-9_]+)\s+IS\s+(NOT\s+)?NULL$/i);
8371
+ if (isNullMatch) {
8372
+ const col = isNullMatch[1];
8373
+ const isNot = Boolean(isNullMatch[2]);
8374
+ const isNull = row[col] === null || row[col] === undefined;
8375
+ if (isNot ? isNull : !isNull) return false;
8376
+ continue;
8377
+ }
8378
+ const likeMatch = trimmed.match(/^([a-zA-Z0-9_]+)\s+LIKE\s+(.+)$/i);
8379
+ if (likeMatch) {
8380
+ const col = likeMatch[1];
8381
+ let pat = likeMatch[2].trim();
8382
+ if (pat === '?') pat = String(pList.shift() || '');
8383
+ else if (/^['"].*['"]$/.test(pat)) pat = pat.slice(1, -1);
8384
+ const re = new RegExp('^' + pat.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/%/g, '.*').replace(/_/g, '.') + '$', 'i');
8385
+ if (!re.test(String(row[col] ?? ''))) return false;
8386
+ continue;
8387
+ }
8388
+ const eqMatch = trimmed.match(/^([a-zA-Z0-9_]+)\s*(=|!=|<>|>=|<=|>|<)\s*(.*)$/);
8389
+ if (eqMatch) {
8390
+ const col = eqMatch[1].trim();
8391
+ const op = eqMatch[2];
8392
+ let expected = eqMatch[3].trim();
8393
+ if (expected === '?') {
8394
+ expected = pList.shift();
8395
+ } else if (/^['"].*['"]$/.test(expected)) {
8396
+ expected = expected.slice(1, -1);
8397
+ } else if (!isNaN(Number(expected))) {
8398
+ expected = Number(expected);
8399
+ }
8400
+ const actual = row[col];
8401
+ let ok = true;
8402
+ if (op === '=') ok = String(actual) === String(expected);
8403
+ else if (op === '!=' || op === '<>') ok = String(actual) !== String(expected);
8404
+ else if (op === '>') ok = Number(actual) > Number(expected);
8405
+ else if (op === '<') ok = Number(actual) < Number(expected);
8406
+ else if (op === '>=') ok = Number(actual) >= Number(expected);
8407
+ else if (op === '<=') ok = Number(actual) <= Number(expected);
8408
+ if (!ok) return false;
8409
+ }
8410
+ }
8411
+ return true;
8412
+ }
8413
+
8414
+ exec(sql) {
8415
+ const cleaned = stripSqlComments(sql);
8416
+ const statements = cleaned.split(';').map((s) => s.trim()).filter(Boolean);
8417
+ for (const s of statements) {
8418
+ this.run(s);
8419
+ }
8420
+ }
8421
+
8422
+ transaction(fn) {
8423
+ return (...args) => fn(...args);
8424
+ }
8425
+
8426
+ close() {
8427
+ this._persistToVfs();
8428
+ }
8429
+
8430
+ query(sql) {
8431
+ const db = this;
8432
+ return {
8433
+ all(...args) {
8434
+ let params = args;
8435
+ if (args.length === 1 && Array.isArray(args[0])) params = args[0];
8436
+ return db._executeSelect(sql, params);
8437
+ },
8438
+ get(...args) {
8439
+ const rows = this.all(...args);
8440
+ return rows[0] || null;
8441
+ },
8442
+ values(...args) {
8443
+ const rows = this.all(...args);
8444
+ return rows.map((r) => Object.values(r));
8445
+ },
8446
+ run(...args) {
8447
+ let params = args;
8448
+ if (args.length === 1 && Array.isArray(args[0])) params = args[0];
8449
+ return db.run(sql, params);
8450
+ }
8451
+ };
8452
+ }
8453
+
8454
+ prepare(sql) {
8455
+ return this.query(sql);
8456
+ }
8457
+
8458
+ _evalAggregate(fn, aggCol, rows) {
8459
+ if (fn === 'COUNT') {
8460
+ if (aggCol === '*') return rows.length;
8461
+ return rows.filter((r) => r[aggCol] !== null && r[aggCol] !== undefined).length;
8462
+ }
8463
+ if (fn === 'AVG') {
8464
+ const sum = rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
8465
+ return rows.length > 0 ? sum / rows.length : 0;
8466
+ }
8467
+ if (fn === 'SUM') {
8468
+ return rows.reduce((acc, r) => acc + (Number(r[aggCol]) || 0), 0);
8469
+ }
8470
+ if (fn === 'MIN') {
8471
+ return rows.length > 0 ? Math.min(...rows.map((r) => Number(r[aggCol]) || 0)) : null;
8472
+ }
8473
+ if (fn === 'MAX') {
8474
+ return rows.length > 0 ? Math.max(...rows.map((r) => Number(r[aggCol]) || 0)) : null;
8475
+ }
8476
+ return null;
8477
+ }
8478
+
8479
+ _executeSelect(sql, params = []) {
8480
+ const s = stripSqlComments(sql).replace(/;$/, '').trim();
8481
+ if (!s) return [];
8482
+
8483
+ if (/^EXPLAIN\s+QUERY\s+PLAN\s+/i.test(s)) {
8484
+ const inner = s.replace(/^EXPLAIN\s+QUERY\s+PLAN\s+/i, '').trim();
8485
+ 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);
8486
+ if (m) {
8487
+ const tblName = m[1];
8488
+ const whereRaw = (m[2] || '').replace(/'[^']*'|"[^"]*"/g, '');
8489
+ const table = this.tables.get(tblName);
8490
+ const pkCol = table && table.columns.find((c) => c.isPk);
8491
+ if (pkCol && new RegExp(`\\b${pkCol.name}\\b`, 'i').test(whereRaw)) {
8492
+ return [{ id: 0, parent: 0, notused: 0, detail: `SEARCH ${tblName} USING INTEGER PRIMARY KEY (rowid=?)` }];
8493
+ }
8494
+ for (const idx of this.indexes.values()) {
8495
+ if (idx.table === tblName && idx.columns.some((c) => new RegExp(`\\b${c}\\b`, 'i').test(whereRaw))) {
8496
+ return [{ id: 0, parent: 0, notused: 0, detail: `SEARCH ${tblName} USING INDEX ${idx.name} (${idx.columns.join(',')}=?)` }];
8497
+ }
8498
+ }
8499
+ return [{ id: 0, parent: 0, notused: 0, detail: `SCAN ${tblName}` }];
8500
+ }
8501
+ return [{ id: 0, parent: 0, notused: 0, detail: 'SCAN' }];
8502
+ }
8503
+
8504
+ if (/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(s)) {
8505
+ const m = s.match(/^PRAGMA\s+table_info\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i);
8506
+ const tbl = m && this.tables.get(m[1]);
8507
+ if (!tbl) return [];
8508
+ return tbl.columns.map((c, idx) => ({
8509
+ cid: idx,
8510
+ name: c.name,
8511
+ type: c.type || 'TEXT',
8512
+ notnull: 0,
8513
+ dflt_value: null,
8514
+ pk: c.isPk ? 1 : 0
8515
+ }));
8516
+ }
8517
+
8518
+ if (/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i.test(s)) {
8519
+ const m = s.match(/^PRAGMA\s+index_list\s*\(\s*([a-zA-Z0-9_]+)\s*\)/i);
8520
+ const tblName = m ? m[1] : '';
8521
+ const out = [];
8522
+ let seq = 0;
8523
+ for (const idx of this.indexes.values()) {
8524
+ if (idx.table === tblName) {
8525
+ out.push({
8526
+ seq: seq++,
8527
+ name: idx.name,
8528
+ unique: idx.unique ? 1 : 0,
8529
+ origin: 'c',
8530
+ partial: 0
8531
+ });
8532
+ }
8533
+ }
8534
+ return out;
8535
+ }
8536
+
8537
+ if (/^(?:INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|PRAGMA)\b/i.test(s)) {
8538
+ this.run(s, params);
8539
+ return [];
8540
+ }
8541
+
8542
+ 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);
8543
+ if (!match) {
8544
+ const noFromMatch = s.match(/^SELECT\s+([\s\S]+)$/i);
8545
+ if (noFromMatch) {
8546
+ const parts = splitCsvRespectingQuotes(noFromMatch[1]);
8547
+ const outRow = {};
8548
+ for (const p of parts) {
8549
+ const asMatch = p.match(/^([\s\S]*?)\s+AS\s+([a-zA-Z0-9_]+)$/i);
8550
+ const expr = (asMatch ? asMatch[1] : p).trim();
8551
+ const alias = (asMatch ? asMatch[2] : p).trim();
8552
+ if (/^sqlite_version\(\)$/i.test(expr)) outRow[alias] = '3.45.0';
8553
+ else if (/^['"].*['"]$/.test(expr)) outRow[alias] = expr.slice(1, -1);
8554
+ else if (!isNaN(Number(expr))) outRow[alias] = Number(expr);
8555
+ else outRow[alias] = expr;
8556
+ }
8557
+ return [outRow];
8558
+ }
8559
+ return [];
8560
+ }
8561
+ const selectColsRaw = match[1].trim();
8562
+ const tableName = match[2].trim();
8563
+ const whereClause = match[3] ? match[3].trim() : null;
8564
+ const groupByClause = match[4] ? match[4].trim() : null;
8565
+ const orderByClause = match[5] ? match[5].trim() : null;
8566
+ const limitRaw = match[6] ? match[6].trim() : null;
8567
+ const offsetRaw = match[7] ? match[7].trim() : null;
8568
+
8569
+ const table = this.tables.get(tableName);
8570
+ if (!table) return [];
8571
+
8572
+ const pList = Array.isArray(params) ? [...params] : [params];
8573
+ const filteredRows = table.rows.filter((row) => {
8574
+ const rowParams = [...pList];
8575
+ return this._matchWhere(row, whereClause, rowParams);
8576
+ });
8577
+ if (whereClause && whereClause.includes('?')) {
8578
+ const qCount = (whereClause.match(/\?/g) || []).length;
8579
+ pList.splice(0, qCount);
8580
+ }
8581
+
8582
+ const colSpecs = [];
8583
+ let hasAggregate = false;
8584
+ if (selectColsRaw !== '*') {
8585
+ const parts = splitCsvRespectingQuotes(selectColsRaw);
8586
+ for (const p of parts) {
8587
+ const asMatch = p.match(/^([\s\S]*?)\s+(?:AS\s+)?([a-zA-Z0-9_]+)$/i);
8588
+ const isFuncWithSpace = /^(AVG|SUM|COUNT|MIN|MAX)\s*\([^)]+\)$/i.test(p.trim());
8589
+ const spec = (asMatch && !isFuncWithSpace)
8590
+ ? { expr: asMatch[1].trim(), alias: asMatch[2].trim() }
8591
+ : { expr: p.trim(), alias: p.trim() };
8592
+ if (/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i.test(spec.expr)) {
8593
+ hasAggregate = true;
8594
+ }
8595
+ colSpecs.push(spec);
8596
+ }
8597
+ }
8598
+
8599
+ let outputRows = [];
8600
+ if (groupByClause) {
8601
+ const groupCol = groupByClause.trim();
8602
+ const groups = new Map();
8603
+ for (const row of filteredRows) {
8604
+ const key = row[groupCol];
8605
+ if (!groups.has(key)) groups.set(key, []);
8606
+ groups.get(key).push(row);
8607
+ }
8608
+
8609
+ for (const [key, rows] of groups.entries()) {
8610
+ const outRow = {};
8611
+ for (const col of colSpecs) {
8612
+ const expr = col.expr;
8613
+ const alias = col.alias;
8614
+ const aggMatch = expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i);
8615
+ if (aggMatch) {
8616
+ outRow[alias] = this._evalAggregate(aggMatch[1].toUpperCase(), aggMatch[2].trim(), rows);
8617
+ } else if (expr === groupCol) {
8618
+ outRow[alias] = key;
8619
+ } else {
8620
+ outRow[alias] = rows[0] ? rows[0][expr] : null;
8621
+ }
8622
+ }
8623
+ outputRows.push(outRow);
8624
+ }
8625
+ } else if (hasAggregate) {
8626
+ const outRow = {};
8627
+ for (const col of colSpecs) {
8628
+ const aggMatch = col.expr.match(/^(AVG|SUM|COUNT|MIN|MAX)\s*\(([^)]+)\)$/i);
8629
+ if (aggMatch) {
8630
+ outRow[col.alias] = this._evalAggregate(aggMatch[1].toUpperCase(), aggMatch[2].trim(), filteredRows);
8631
+ } else {
8632
+ outRow[col.alias] = filteredRows[0] ? filteredRows[0][col.expr] : null;
8633
+ }
8634
+ }
8635
+ outputRows.push(outRow);
8636
+ } else {
8637
+ for (const row of filteredRows) {
8638
+ if (selectColsRaw === '*') {
8639
+ outputRows.push(Object.assign({}, row));
8640
+ } else {
8641
+ const outRow = {};
8642
+ for (const col of colSpecs) {
8643
+ outRow[col.alias] = row[col.expr];
8644
+ }
8645
+ outputRows.push(outRow);
8646
+ }
8647
+ }
8648
+ }
8649
+
8650
+ if (orderByClause) {
8651
+ const parts = orderByClause.trim().split(/\s+/);
8652
+ const orderCol = parts[0];
8653
+ const desc = parts[1] && parts[1].toUpperCase() === 'DESC';
8654
+ outputRows.sort((a, b) => {
8655
+ const valA = a[orderCol];
8656
+ const valB = b[orderCol];
8657
+ if (valA === valB) return 0;
8658
+ if (valA === undefined) return 1;
8659
+ if (valB === undefined) return -1;
8660
+ const res = valA > valB ? 1 : -1;
8661
+ return desc ? -res : res;
8662
+ });
8663
+ }
8664
+
8665
+ if (limitRaw !== null) {
8666
+ const limitVal = limitRaw === '?' ? Number(pList.shift() || 0) : Number(limitRaw);
8667
+ const offsetVal = offsetRaw !== null ? (offsetRaw === '?' ? Number(pList.shift() || 0) : Number(offsetRaw)) : 0;
8668
+ outputRows = outputRows.slice(offsetVal, offsetVal + limitVal);
8669
+ }
8670
+
8671
+ return outputRows;
8672
+ }
8673
+ };
8674
+ }
8675
+
8114
8676
  return {
8115
8677
  VirtualBuffer,
8116
8678
  VirtualCrypto,
@@ -8129,6 +8691,7 @@ function __initVirtualRuntime(rootScope) {
8129
8691
  createVirtualFs,
8130
8692
  createVirtualHttp,
8131
8693
  createVirtualNet,
8694
+ createSqliteDatabase,
8132
8695
  transpileTS,
8133
8696
  transpileForBrowser,
8134
8697
  preloadNpmPackages,