@innovatorved/code-lab 0.1.12 → 0.1.13

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