@innovatorved/code-lab 0.1.7 → 0.1.9

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.7 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.9 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -16,6 +16,1870 @@
16
16
  */
17
17
  const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : {};
18
18
 
19
+ // --- Module 0: Preview CSP, Structured Logger, Safe HTML & Leaf Engines ---
20
+ var CodeLabCsp = (() => {
21
+ var __defProp = Object.defineProperty;
22
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
23
+ var __getOwnPropNames = Object.getOwnPropertyNames;
24
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
+
39
+ // src/csp.ts
40
+ var csp_exports = {};
41
+ __export(csp_exports, {
42
+ PREVIEW_SHIM_MARKER: () => PREVIEW_SHIM_MARKER,
43
+ buildPreviewPolicy: () => buildPreviewPolicy,
44
+ buildPreviewShims: () => buildPreviewShims,
45
+ default: () => csp_default,
46
+ describePreviewNetwork: () => describePreviewNetwork,
47
+ normalizeOrigin: () => normalizeOrigin,
48
+ normalizePreviewCspConfig: () => normalizePreviewCspConfig
49
+ });
50
+ var IMPORT_MAP_CDNS = ["https://cdn.jsdelivr.net", "https://esm.sh"];
51
+ var FONT_CDNS = ["https://cdn.jsdelivr.net", "https://fonts.gstatic.com"];
52
+ var PRESETS = {
53
+ strict: {},
54
+ balanced: {
55
+ scriptSrc: IMPORT_MAP_CDNS.slice(),
56
+ styleSrc: ["https://cdn.jsdelivr.net", "https://fonts.googleapis.com"],
57
+ fontSrc: FONT_CDNS.slice(),
58
+ connectSrc: IMPORT_MAP_CDNS.slice(),
59
+ imgSrc: ["https://cdn.jsdelivr.net"]
60
+ }
61
+ };
62
+ var SOURCE_KEYS = [
63
+ "scriptSrc",
64
+ "styleSrc",
65
+ "imgSrc",
66
+ "fontSrc",
67
+ "connectSrc",
68
+ "mediaSrc",
69
+ "workerSrc",
70
+ "frameSrc"
71
+ ];
72
+ var MAX_SOURCES = 64;
73
+ var MAX_SOURCE_LENGTH = 512;
74
+ var PREVIEW_SHIM_MARKER = "data-codelab-preview-shims";
75
+ function normalizeOrigin(raw) {
76
+ if (raw === null || raw === void 0 || raw === "") return null;
77
+ try {
78
+ const parsed = new URL(String(raw));
79
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
80
+ return parsed.origin;
81
+ } catch (_) {
82
+ return null;
83
+ }
84
+ }
85
+ function normalizeMode(raw) {
86
+ if (raw === "strict" || raw === "custom") return raw;
87
+ return "balanced";
88
+ }
89
+ var ALLOWED_KEYWORDS = [
90
+ "'self'",
91
+ "'none'",
92
+ "'unsafe-inline'",
93
+ "'unsafe-eval'",
94
+ "'wasm-unsafe-eval'",
95
+ "'strict-dynamic'",
96
+ "'unsafe-hashes'"
97
+ ];
98
+ var SOURCE_PATTERN = /^(?:https?:\/\/[A-Za-z0-9._~%-]+(?::\d{1,5})?(?:\/[^\s;,'"]*)?|data:|blob:|filesystem:)$/;
99
+ function isSafeSource(source) {
100
+ return ALLOWED_KEYWORDS.indexOf(source) !== -1 || SOURCE_PATTERN.test(source);
101
+ }
102
+ function cleanSources(raw) {
103
+ if (!Array.isArray(raw)) return [];
104
+ const out = [];
105
+ for (const value of raw.slice(0, MAX_SOURCES)) {
106
+ if (typeof value !== "string") continue;
107
+ const source = value.trim();
108
+ if (!source || source.length > MAX_SOURCE_LENGTH) continue;
109
+ if (!isSafeSource(source)) continue;
110
+ if (out.indexOf(source) === -1) out.push(source);
111
+ }
112
+ return out;
113
+ }
114
+ function unique(...lists) {
115
+ const out = [];
116
+ for (const list of lists) {
117
+ if (!list) continue;
118
+ for (const value of list) {
119
+ if (value && out.indexOf(value) === -1) out.push(value);
120
+ }
121
+ }
122
+ return out;
123
+ }
124
+ function normalizePreviewCspConfig(raw) {
125
+ if (typeof raw === "string") return { mode: normalizeMode(raw), allow: {} };
126
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
127
+ return { mode: "balanced", allow: {} };
128
+ }
129
+ const input = raw;
130
+ const nested = input.allow;
131
+ const sources = nested && typeof nested === "object" && !Array.isArray(nested) ? nested : input;
132
+ const allow = {};
133
+ for (const key of SOURCE_KEYS) {
134
+ const list = cleanSources(sources[key]);
135
+ if (list.length) allow[key] = list;
136
+ }
137
+ return { mode: normalizeMode(input.mode), allow };
138
+ }
139
+ function sourcesFor(mode, allow, key) {
140
+ const preset = mode === "custom" ? {} : PRESETS[mode];
141
+ return unique(preset[key], cleanSources(allow[key]));
142
+ }
143
+ function buildPreviewPolicy(options = {}) {
144
+ const mode = normalizeMode(options.mode);
145
+ const allow = options;
146
+ const host = normalizeOrigin(options.hostOrigin);
147
+ const self = host || "'self'";
148
+ const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
149
+ const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
150
+ const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
151
+ const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
152
+ return [
153
+ directive("default-src", [self, "data:", "blob:"]),
154
+ directive("base-uri", [self]),
155
+ "object-src 'none'",
156
+ directive("script-src", script()),
157
+ directive("style-src", style()),
158
+ directive("img-src", withData("imgSrc")),
159
+ directive("font-src", [self, "data:"].concat(sourcesFor(mode, allow, "fontSrc"))),
160
+ directive("connect-src", withData("connectSrc")),
161
+ directive("media-src", withData("mediaSrc")),
162
+ directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
163
+ directive("frame-src", withData("frameSrc")),
164
+ directive("form-action", [self]),
165
+ directive("frame-ancestors", [options.frameAncestors || "'self'"])
166
+ ].join("; ");
167
+ }
168
+ function describePreviewNetwork(config) {
169
+ const normalized = normalizePreviewCspConfig(config);
170
+ if (normalized.mode === "strict") return [];
171
+ const preset = normalized.mode === "custom" ? {} : PRESETS[normalized.mode];
172
+ const hosts = [];
173
+ for (const key of ["scriptSrc", "connectSrc", "imgSrc", "styleSrc", "fontSrc"]) {
174
+ for (const source of unique(preset[key], normalized.allow[key])) {
175
+ if (!/^https?:\/\//i.test(source)) continue;
176
+ let host;
177
+ try {
178
+ host = new URL(source).host;
179
+ } catch (_) {
180
+ continue;
181
+ }
182
+ if (hosts.indexOf(host) === -1) hosts.push(host);
183
+ }
184
+ }
185
+ return hosts;
186
+ }
187
+ function buildPreviewShims() {
188
+ return `<script ${PREVIEW_SHIM_MARKER}>
189
+ (function () {
190
+ 'use strict';
191
+ function memoryStorage() {
192
+ var data = new Map();
193
+ return {
194
+ getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
195
+ setItem: function (k, v) { data.set(String(k), String(v)); },
196
+ removeItem: function (k) { data.delete(String(k)); },
197
+ clear: function () { data.clear(); },
198
+ key: function (i) { return Array.from(data.keys())[i] || null; },
199
+ get length() { return data.size; }
200
+ };
201
+ }
202
+ function shim(name) {
203
+ var blocked = false;
204
+ try {
205
+ var existing = window[name];
206
+ if (existing) { existing.getItem('__codelab_probe__'); return; }
207
+ } catch (err) {
208
+ // Expected on an opaque origin: the accessor itself throws.
209
+ blocked = Boolean(err);
210
+ }
211
+ void blocked;
212
+ try {
213
+ Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
214
+ } catch (err) {
215
+ console.warn('[code-lab] preview: unable to shim ' + name, err);
216
+ }
217
+ }
218
+ shim('localStorage');
219
+ shim('sessionStorage');
220
+ document.addEventListener('securitypolicyviolation', function (event) {
221
+ try {
222
+ parent.postMessage({
223
+ type: 'codelab:preview-violation',
224
+ directive: event.effectiveDirective || event.violatedDirective || '',
225
+ blockedURI: event.blockedURI || '',
226
+ sourceFile: event.sourceFile || '',
227
+ line: event.lineNumber || 0
228
+ }, '*');
229
+ } catch (err) {
230
+ console.warn('[code-lab] preview: could not report CSP violation', err);
231
+ }
232
+ });
233
+ function serializeArg(arg) {
234
+ if (typeof arg !== 'object' || arg === null) return String(arg);
235
+ try {
236
+ return JSON.stringify(arg);
237
+ } catch (err) {
238
+ void err;
239
+ return '[Circular/Unserializable]';
240
+ }
241
+ }
242
+ ['log', 'warn', 'error', 'info'].forEach(function (level) {
243
+ var orig = console[level];
244
+ if (typeof orig !== 'function') return;
245
+ console[level] = function () {
246
+ var args = Array.prototype.slice.call(arguments);
247
+ try {
248
+ parent.postMessage({
249
+ type: 'codelab:preview-console',
250
+ level: level,
251
+ args: args.map(serializeArg)
252
+ }, '*');
253
+ } catch (err) {
254
+ void err;
255
+ }
256
+ return orig.apply(console, args);
257
+ };
258
+ });
259
+ function showPreviewErrorOverlay(msg, stack) {
260
+ try {
261
+ if (!document || !document.body) return;
262
+ var existing = document.getElementById('codelab-preview-error-overlay');
263
+ if (!existing) {
264
+ existing = document.createElement('div');
265
+ existing.id = 'codelab-preview-error-overlay';
266
+ existing.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:rgba(15,23,42,0.94);color:#f8fafc;font-family:ui-monospace,monospace;padding:24px;overflow:auto;';
267
+ document.body.appendChild(existing);
268
+ }
269
+ existing.textContent = '';
270
+ var topBar = document.createElement('div');
271
+ topBar.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;padding-bottom:10px;border-bottom:1px solid rgba(248,113,113,0.28);';
272
+ var header = document.createElement('div');
273
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
274
+ header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
275
+ var closeBtn = document.createElement('button');
276
+ closeBtn.type = 'button';
277
+ closeBtn.textContent = 'Dismiss \xD7';
278
+ closeBtn.style.cssText = 'background:rgba(255,255,255,0.08);color:#e2e8f0;border:1px solid rgba(255,255,255,0.16);border-radius:6px;padding:4px 10px;font-size:11px;cursor:pointer;font-family:inherit;';
279
+ closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
280
+ topBar.appendChild(header);
281
+ topBar.appendChild(closeBtn);
282
+ var pre = document.createElement('pre');
283
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
284
+ pre.textContent = String(stack || msg || '');
285
+ existing.appendChild(topBar);
286
+ existing.appendChild(pre);
287
+ } catch (err) {
288
+ void err;
289
+ }
290
+ }
291
+ window.addEventListener('error', function (event) {
292
+ var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
293
+ var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
294
+ showPreviewErrorOverlay(msg, stack);
295
+ try {
296
+ parent.postMessage({
297
+ type: 'codelab:preview-error',
298
+ message: msg,
299
+ file: (event && event.filename) || null,
300
+ line: (event && event.lineno) || null,
301
+ col: (event && event.colno) || null,
302
+ stack: stack || null
303
+ }, '*');
304
+ } catch (err) {
305
+ void err;
306
+ }
307
+ });
308
+ window.addEventListener('unhandledrejection', function (event) {
309
+ var reason = event ? event.reason : null;
310
+ var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
311
+ var stack = reason && reason.stack ? String(reason.stack) : '';
312
+ showPreviewErrorOverlay(msg, stack);
313
+ try {
314
+ parent.postMessage({
315
+ type: 'codelab:preview-error',
316
+ message: msg,
317
+ file: null,
318
+ line: null,
319
+ col: null,
320
+ stack: stack || null
321
+ }, '*');
322
+ } catch (err) {
323
+ void err;
324
+ }
325
+ });
326
+
327
+ // Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
328
+ var pendingFetches = new Map();
329
+ var fetchSeq = 0;
330
+ function parseLoopbackTarget(rawUrl) {
331
+ if (!rawUrl || typeof rawUrl !== 'string') return null;
332
+ var trimmed = rawUrl.trim();
333
+ if (!trimmed) return null;
334
+ var lower = trimmed.toLowerCase();
335
+ if (lower.indexOf('data:') === 0 || lower.indexOf('blob:') === 0 || lower.indexOf('mailto:') === 0 || lower.indexOf('tel:') === 0 || lower.indexOf('javascript:') === 0 || trimmed.charAt(0) === '#') return null;
336
+ if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
337
+ try {
338
+ var u = new URL(trimmed);
339
+ if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
340
+ return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
341
+ }
342
+ if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
343
+ var rest = u.pathname.slice('/__preview/'.length);
344
+ var slashIdx = rest.indexOf('/');
345
+ var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
346
+ var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
347
+ var portNum = Number(portStr);
348
+ if (portNum > 0) {
349
+ return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
350
+ }
351
+ }
352
+ } catch (e) { void e; }
353
+ return null;
354
+ }
355
+ if (trimmed.indexOf('/__preview/') === 0) {
356
+ var restRel = trimmed.slice('/__preview/'.length);
357
+ var sIdx = restRel.indexOf('/');
358
+ var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
359
+ var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
360
+ var pNum = Number(pStr);
361
+ if (pNum > 0) {
362
+ return { port: pNum, path: sPath || '/' };
363
+ }
364
+ }
365
+ var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
366
+ var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
367
+ return { port: null, path: pathPart };
368
+ }
369
+
370
+ window.addEventListener('message', function (event) {
371
+ var data = event && event.data;
372
+ if (!data || typeof data !== 'object') return;
373
+ if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
374
+ var entry = pendingFetches.get(data.reqId);
375
+ if (!entry) return;
376
+ pendingFetches.delete(data.reqId);
377
+ entry.resolve(data);
378
+ }
379
+ });
380
+
381
+ if (typeof window.fetch === 'function') {
382
+ var origFetch = window.fetch.bind(window);
383
+ window.fetch = function (input, init) {
384
+ var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
385
+ var target = parseLoopbackTarget(urlStr);
386
+ // Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
387
+ var isOpaque = false;
388
+ try {
389
+ var lowerUrl = urlStr.toLowerCase();
390
+ var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
391
+ isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
392
+ } catch (e) { isOpaque = true; void e; }
393
+ if (!target || !isOpaque || window.parent === window) {
394
+ return origFetch(input, init);
395
+ }
396
+ return new Promise(function (resolve, reject) {
397
+ var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
398
+ var method = (init && init.method) || (input && input.method) || 'GET';
399
+ var headersObj = {};
400
+ try {
401
+ var rawH = (init && init.headers) || (input && input.headers);
402
+ if (rawH) {
403
+ if (typeof rawH.forEach === 'function') {
404
+ rawH.forEach(function (v, k) { headersObj[k] = v; });
405
+ } else if (Array.isArray(rawH)) {
406
+ rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
407
+ } else if (typeof rawH === 'object') {
408
+ Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
409
+ }
410
+ }
411
+ } catch (e) { void e; }
412
+ var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
413
+ var timer = setTimeout(function () {
414
+ if (pendingFetches.has(reqId)) {
415
+ pendingFetches.delete(reqId);
416
+ origFetch(input, init).then(resolve, reject);
417
+ }
418
+ }, 5000);
419
+ pendingFetches.set(reqId, {
420
+ resolve: function (payload) {
421
+ clearTimeout(timer);
422
+ if (payload && payload.error) {
423
+ reject(new TypeError(String(payload.error)));
424
+ return;
425
+ }
426
+ var status = Number(payload && payload.status) || 200;
427
+ var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
428
+ var body = payload && payload.body !== undefined ? String(payload.body) : '';
429
+ try {
430
+ resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
431
+ } catch (err) {
432
+ void err;
433
+ resolve({
434
+ ok: status >= 200 && status < 300,
435
+ status: status,
436
+ headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
437
+ text: function () { return Promise.resolve(body); },
438
+ json: function () { return Promise.resolve(JSON.parse(body)); }
439
+ });
440
+ }
441
+ }
442
+ });
443
+ try {
444
+ parent.postMessage({
445
+ type: 'codelab:preview-fetch',
446
+ reqId: reqId,
447
+ port: target.port,
448
+ path: target.path,
449
+ method: String(method).toUpperCase(),
450
+ headers: headersObj,
451
+ body: bodyStr
452
+ }, '*');
453
+ } catch (err) {
454
+ clearTimeout(timer);
455
+ pendingFetches.delete(reqId);
456
+ origFetch(input, init).then(resolve, reject);
457
+ }
458
+ });
459
+ };
460
+ }
461
+
462
+ // Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
463
+ document.addEventListener('click', function (event) {
464
+ if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
465
+ var el = event.target;
466
+ while (el && el.tagName !== 'A') el = el.parentElement;
467
+ if (!el || !el.getAttribute) return;
468
+ var href = el.getAttribute('href');
469
+ var targetAttr = el.getAttribute('target');
470
+ if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
471
+ var lowerHref = href.toLowerCase();
472
+ if (href.charAt(0) === '#' || lowerHref.indexOf('mailto:') === 0 || lowerHref.indexOf('tel:') === 0 || lowerHref.indexOf('javascript:') === 0 || lowerHref.indexOf('data:') === 0 || lowerHref.indexOf('blob:') === 0) return;
473
+ var parsed = parseLoopbackTarget(href);
474
+ if (!parsed) return;
475
+ event.preventDefault();
476
+ try {
477
+ parent.postMessage({
478
+ type: 'codelab:preview-navigate',
479
+ port: parsed.port,
480
+ path: parsed.path
481
+ }, '*');
482
+ } catch (e) { void e; }
483
+ });
484
+
485
+ // Sync SPA history.pushState / replaceState with the preview omni-address bar
486
+ try {
487
+ ['pushState', 'replaceState'].forEach(function (method) {
488
+ var orig = history[method];
489
+ if (typeof orig !== 'function') return;
490
+ history[method] = function (state, title, url) {
491
+ var ret;
492
+ try { ret = orig.apply(history, arguments); } catch (e) { void e; }
493
+ if (url !== undefined && url !== null) {
494
+ var parsed = parseLoopbackTarget(String(url));
495
+ if (parsed) {
496
+ try {
497
+ parent.postMessage({
498
+ type: 'codelab:preview-url-change',
499
+ path: parsed.path,
500
+ replace: method === 'replaceState'
501
+ }, '*');
502
+ } catch (e) { void e; }
503
+ }
504
+ }
505
+ return ret;
506
+ };
507
+ });
508
+ } catch (e) { void e; }
509
+ })();
510
+ <\/script>`;
511
+ }
512
+ var csp_default = {
513
+ buildPreviewPolicy,
514
+ buildPreviewShims,
515
+ describePreviewNetwork,
516
+ normalizePreviewCspConfig,
517
+ normalizeOrigin,
518
+ PREVIEW_SHIM_MARKER
519
+ };
520
+ return __toCommonJS(csp_exports);
521
+ })();
522
+
523
+ var CodeLabLogger = (() => {
524
+ var __defProp = Object.defineProperty;
525
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
526
+ var __getOwnPropNames = Object.getOwnPropertyNames;
527
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
528
+ var __export = (target, all) => {
529
+ for (var name in all)
530
+ __defProp(target, name, { get: all[name], enumerable: true });
531
+ };
532
+ var __copyProps = (to, from, except, desc) => {
533
+ if (from && typeof from === "object" || typeof from === "function") {
534
+ for (let key of __getOwnPropNames(from))
535
+ if (!__hasOwnProp.call(to, key) && key !== except)
536
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
537
+ }
538
+ return to;
539
+ };
540
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
541
+
542
+ // src/logger.ts
543
+ var logger_exports = {};
544
+ __export(logger_exports, {
545
+ CodeLabError: () => CodeLabError,
546
+ DEFAULT_LOGGER: () => DEFAULT_LOGGER,
547
+ LOG_PREFIX: () => LOG_PREFIX,
548
+ createLogger: () => createLogger,
549
+ default: () => logger_default,
550
+ isCodeLabError: () => isCodeLabError
551
+ });
552
+ var LOG_PREFIX = "[code-lab]";
553
+ var CodeLabError = class extends Error {
554
+ code;
555
+ options;
556
+ cause;
557
+ recoverable;
558
+ details;
559
+ context;
560
+ constructor(code, message, options = {}) {
561
+ super(message);
562
+ this.name = "CodeLabError";
563
+ this.code = code;
564
+ this.options = options;
565
+ this.cause = options.cause;
566
+ this.recoverable = options.recoverable !== false;
567
+ const meta = options.details ?? options.context;
568
+ if (meta !== void 0) {
569
+ this.details = meta;
570
+ this.context = meta;
571
+ }
572
+ Object.setPrototypeOf(this, new.target.prototype);
573
+ }
574
+ };
575
+ function isCodeLabError(value) {
576
+ return Boolean(
577
+ value && typeof value === "object" && (value instanceof CodeLabError || value.name === "CodeLabError" && typeof value.code === "string")
578
+ );
579
+ }
580
+ function createLogger(options = {}) {
581
+ const sink = options.logger ?? null;
582
+ const debugEnabled = options.debug === true;
583
+ const prefix = options.prefix || LOG_PREFIX;
584
+ const write = (level, args) => {
585
+ if (level === "debug" && !debugEnabled) return;
586
+ if (sink && typeof sink[level] === "function") {
587
+ let sinkError = null;
588
+ try {
589
+ sink[level](...args);
590
+ return;
591
+ } catch (err) {
592
+ sinkError = err;
593
+ }
594
+ }
595
+ const consoleObj = typeof console !== "undefined" ? console : null;
596
+ const fn = consoleObj ? consoleObj[level] : null;
597
+ if (typeof fn === "function") {
598
+ fn.call(consoleObj, prefix, ...args);
599
+ }
600
+ };
601
+ return {
602
+ debug: (...args) => write("debug", args),
603
+ info: (...args) => write("info", args),
604
+ warn: (...args) => write("warn", args),
605
+ error: (...args) => write("error", args)
606
+ };
607
+ }
608
+ var DEFAULT_LOGGER = createLogger();
609
+ var _loggerNamespace = {
610
+ LOG_PREFIX,
611
+ CodeLabError,
612
+ isCodeLabError,
613
+ createLogger,
614
+ DEFAULT_LOGGER
615
+ };
616
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
617
+ if (_globalRoot && !_globalRoot.CodeLabLogger) {
618
+ _globalRoot.CodeLabLogger = _loggerNamespace;
619
+ }
620
+ var logger_default = _loggerNamespace;
621
+ return __toCommonJS(logger_exports);
622
+ })();
623
+
624
+ var CodeLabHtml = (() => {
625
+ var __defProp = Object.defineProperty;
626
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
627
+ var __getOwnPropNames = Object.getOwnPropertyNames;
628
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
629
+ var __export = (target, all) => {
630
+ for (var name in all)
631
+ __defProp(target, name, { get: all[name], enumerable: true });
632
+ };
633
+ var __copyProps = (to, from, except, desc) => {
634
+ if (from && typeof from === "object" || typeof from === "function") {
635
+ for (let key of __getOwnPropNames(from))
636
+ if (!__hasOwnProp.call(to, key) && key !== except)
637
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
638
+ }
639
+ return to;
640
+ };
641
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
642
+
643
+ // src/html.ts
644
+ var html_exports = {};
645
+ __export(html_exports, {
646
+ default: () => html_default,
647
+ escapeHtml: () => escapeHtml,
648
+ html: () => html,
649
+ isSafeHtml: () => isSafeHtml,
650
+ raw: () => raw
651
+ });
652
+ var SAFE_HTML_BRAND = Symbol.for("codelab.SafeHtml");
653
+ var SafeHtmlImpl = class {
654
+ [SAFE_HTML_BRAND] = true;
655
+ __html;
656
+ constructor(trusted) {
657
+ this.__html = String(trusted);
658
+ }
659
+ toString() {
660
+ return this.__html;
661
+ }
662
+ };
663
+ function isSafeHtml(value) {
664
+ return Boolean(
665
+ value && typeof value === "object" && value[SAFE_HTML_BRAND] === true && typeof value.__html === "string"
666
+ );
667
+ }
668
+ function escapeHtml(value) {
669
+ if (value === null || value === void 0) return "";
670
+ if (isSafeHtml(value)) return value.__html;
671
+ return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
672
+ }
673
+ function raw(trustedHtml) {
674
+ return new SafeHtmlImpl(trustedHtml);
675
+ }
676
+ function renderInterpolation(value) {
677
+ if (value === null || value === void 0 || value === false) return "";
678
+ if (isSafeHtml(value)) return value.__html;
679
+ if (Array.isArray(value)) {
680
+ let out = "";
681
+ for (let i = 0; i < value.length; i++) {
682
+ out += renderInterpolation(value[i]);
683
+ }
684
+ return out;
685
+ }
686
+ return escapeHtml(value);
687
+ }
688
+ function html(strings, ...values) {
689
+ let out = strings[0] ?? "";
690
+ for (let i = 0; i < values.length; i++) {
691
+ out += renderInterpolation(values[i]);
692
+ out += strings[i + 1] ?? "";
693
+ }
694
+ return new SafeHtmlImpl(out);
695
+ }
696
+ var _htmlNamespace = {
697
+ escapeHtml,
698
+ raw,
699
+ isSafeHtml,
700
+ html
701
+ };
702
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
703
+ if (_globalRoot && !_globalRoot.CodeLabHtml) {
704
+ _globalRoot.CodeLabHtml = _htmlNamespace;
705
+ }
706
+ var html_default = _htmlNamespace;
707
+ return __toCommonJS(html_exports);
708
+ })();
709
+
710
+ var CodeLabZip = (() => {
711
+ var __defProp = Object.defineProperty;
712
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
713
+ var __getOwnPropNames = Object.getOwnPropertyNames;
714
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
715
+ var __export = (target, all) => {
716
+ for (var name in all)
717
+ __defProp(target, name, { get: all[name], enumerable: true });
718
+ };
719
+ var __copyProps = (to, from, except, desc) => {
720
+ if (from && typeof from === "object" || typeof from === "function") {
721
+ for (let key of __getOwnPropNames(from))
722
+ if (!__hasOwnProp.call(to, key) && key !== except)
723
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
724
+ }
725
+ return to;
726
+ };
727
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
728
+
729
+ // src/zip.ts
730
+ var zip_exports = {};
731
+ __export(zip_exports, {
732
+ computeCrc32: () => computeCrc32,
733
+ createZip: () => createZip,
734
+ default: () => zip_default,
735
+ extractZip: () => extractZip,
736
+ sanitizeZipPath: () => sanitizeZipPath,
737
+ toUint8Array: () => toUint8Array
738
+ });
739
+ var LOCAL_FILE_HEADER_SIG = 67324752;
740
+ var CENTRAL_DIR_HEADER_SIG = 33639248;
741
+ var END_OF_CENTRAL_DIR_SIG = 101010256;
742
+ var UTF8_FLAG = 2048;
743
+ var CRC32_TABLE = new Uint32Array(256);
744
+ for (let i = 0; i < 256; i++) {
745
+ let c = i;
746
+ for (let k = 0; k < 8; k++) {
747
+ c = (c & 1) !== 0 ? 3988292384 ^ c >>> 1 : c >>> 1;
748
+ }
749
+ CRC32_TABLE[i] = c >>> 0;
750
+ }
751
+ var textEncoder = new TextEncoder();
752
+ var textDecoder = new TextDecoder("utf-8");
753
+ function toUint8Array(input) {
754
+ if (typeof input === "string") {
755
+ return textEncoder.encode(input);
756
+ }
757
+ if (input instanceof Uint8Array) {
758
+ return input;
759
+ }
760
+ if (input instanceof ArrayBuffer) {
761
+ return new Uint8Array(input);
762
+ }
763
+ return new Uint8Array(0);
764
+ }
765
+ function computeCrc32(data) {
766
+ const bytes = toUint8Array(data);
767
+ let crc = 4294967295;
768
+ for (let i = 0; i < bytes.length; i++) {
769
+ const index = (crc ^ bytes[i]) & 255;
770
+ crc = crc >>> 8 ^ CRC32_TABLE[index];
771
+ }
772
+ return (crc ^ 4294967295) >>> 0;
773
+ }
774
+ function sanitizeZipPath(rawPath) {
775
+ const normalized = String(rawPath || "").replace(/\\/g, "/").replace(/^[A-Za-z]:/, "");
776
+ const parts = normalized.split("/");
777
+ const safeParts = [];
778
+ for (const part of parts) {
779
+ const trimmed = part.trim();
780
+ if (!trimmed || trimmed === ".") continue;
781
+ if (trimmed === "..") {
782
+ if (safeParts.length > 0) {
783
+ safeParts.pop();
784
+ }
785
+ continue;
786
+ }
787
+ safeParts.push(trimmed);
788
+ }
789
+ return safeParts.join("/");
790
+ }
791
+ function writeUInt16LE(buf, offset, value) {
792
+ buf[offset] = value & 255;
793
+ buf[offset + 1] = value >>> 8 & 255;
794
+ }
795
+ function writeUInt32LE(buf, offset, value) {
796
+ buf[offset] = value & 255;
797
+ buf[offset + 1] = value >>> 8 & 255;
798
+ buf[offset + 2] = value >>> 16 & 255;
799
+ buf[offset + 3] = value >>> 24 & 255;
800
+ }
801
+ function readUInt16LE(buf, offset) {
802
+ return (buf[offset] | buf[offset + 1] << 8) >>> 0;
803
+ }
804
+ function readUInt32LE(buf, offset) {
805
+ return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
806
+ }
807
+ async function createZip(files) {
808
+ const entries = [];
809
+ let localSectionSize = 0;
810
+ let centralDirSize = 0;
811
+ const rawKeys = Object.keys(files || {});
812
+ for (const rawKey of rawKeys) {
813
+ const safePath = sanitizeZipPath(rawKey);
814
+ if (!safePath) continue;
815
+ const rawContent = files[rawKey];
816
+ const dataBytes = toUint8Array(rawContent);
817
+ const nameBytes = textEncoder.encode(safePath);
818
+ const crc = computeCrc32(dataBytes);
819
+ entries.push({
820
+ nameBytes,
821
+ dataBytes,
822
+ crc32: crc,
823
+ offset: localSectionSize
824
+ });
825
+ localSectionSize += 30 + nameBytes.length + dataBytes.length;
826
+ centralDirSize += 46 + nameBytes.length;
827
+ }
828
+ const totalSize = localSectionSize + centralDirSize + 22;
829
+ const out = new Uint8Array(totalSize);
830
+ let cursor = 0;
831
+ for (const entry of entries) {
832
+ writeUInt32LE(out, cursor, LOCAL_FILE_HEADER_SIG);
833
+ writeUInt16LE(out, cursor + 4, 20);
834
+ writeUInt16LE(out, cursor + 6, UTF8_FLAG);
835
+ writeUInt16LE(out, cursor + 8, 0);
836
+ writeUInt16LE(out, cursor + 10, 0);
837
+ writeUInt16LE(out, cursor + 12, 8448);
838
+ writeUInt32LE(out, cursor + 14, entry.crc32);
839
+ writeUInt32LE(out, cursor + 18, entry.dataBytes.length);
840
+ writeUInt32LE(out, cursor + 22, entry.dataBytes.length);
841
+ writeUInt16LE(out, cursor + 26, entry.nameBytes.length);
842
+ writeUInt16LE(out, cursor + 28, 0);
843
+ cursor += 30;
844
+ out.set(entry.nameBytes, cursor);
845
+ cursor += entry.nameBytes.length;
846
+ out.set(entry.dataBytes, cursor);
847
+ cursor += entry.dataBytes.length;
848
+ }
849
+ const centralDirOffset = cursor;
850
+ for (const entry of entries) {
851
+ writeUInt32LE(out, cursor, CENTRAL_DIR_HEADER_SIG);
852
+ writeUInt16LE(out, cursor + 4, 20);
853
+ writeUInt16LE(out, cursor + 6, 20);
854
+ writeUInt16LE(out, cursor + 8, UTF8_FLAG);
855
+ writeUInt16LE(out, cursor + 10, 0);
856
+ writeUInt16LE(out, cursor + 12, 0);
857
+ writeUInt16LE(out, cursor + 14, 8448);
858
+ writeUInt32LE(out, cursor + 16, entry.crc32);
859
+ writeUInt32LE(out, cursor + 20, entry.dataBytes.length);
860
+ writeUInt32LE(out, cursor + 24, entry.dataBytes.length);
861
+ writeUInt16LE(out, cursor + 28, entry.nameBytes.length);
862
+ writeUInt16LE(out, cursor + 30, 0);
863
+ writeUInt16LE(out, cursor + 32, 0);
864
+ writeUInt16LE(out, cursor + 34, 0);
865
+ writeUInt16LE(out, cursor + 36, 0);
866
+ writeUInt32LE(out, cursor + 38, 0);
867
+ writeUInt32LE(out, cursor + 42, entry.offset);
868
+ cursor += 46;
869
+ out.set(entry.nameBytes, cursor);
870
+ cursor += entry.nameBytes.length;
871
+ }
872
+ writeUInt32LE(out, cursor, END_OF_CENTRAL_DIR_SIG);
873
+ writeUInt16LE(out, cursor + 4, 0);
874
+ writeUInt16LE(out, cursor + 6, 0);
875
+ writeUInt16LE(out, cursor + 8, entries.length);
876
+ writeUInt16LE(out, cursor + 10, entries.length);
877
+ writeUInt32LE(out, cursor + 12, centralDirSize);
878
+ writeUInt32LE(out, cursor + 16, centralDirOffset);
879
+ writeUInt16LE(out, cursor + 20, 0);
880
+ return out;
881
+ }
882
+ async function extractZip(data) {
883
+ const bytes = toUint8Array(data);
884
+ if (bytes.length < 22) {
885
+ throw new Error("Invalid or truncated ZIP archive: buffer shorter than minimum 22-byte EOCD record");
886
+ }
887
+ let eocdOffset = -1;
888
+ const minSearchOffset = Math.max(0, bytes.length - 65557);
889
+ for (let i = bytes.length - 22; i >= minSearchOffset; i--) {
890
+ if (readUInt32LE(bytes, i) === END_OF_CENTRAL_DIR_SIG) {
891
+ eocdOffset = i;
892
+ break;
893
+ }
894
+ }
895
+ if (eocdOffset === -1) {
896
+ throw new Error("Invalid ZIP archive: End of Central Directory (PK\\x05\\x06) signature not found");
897
+ }
898
+ const totalEntries = readUInt16LE(bytes, eocdOffset + 10);
899
+ const centralDirSize = readUInt32LE(bytes, eocdOffset + 12);
900
+ const centralDirOffset = readUInt32LE(bytes, eocdOffset + 16);
901
+ if (centralDirOffset + centralDirSize > bytes.length) {
902
+ throw new Error("Corrupted ZIP archive: Central Directory extends past end of buffer");
903
+ }
904
+ const result = {};
905
+ let cdCursor = centralDirOffset;
906
+ for (let i = 0; i < totalEntries; i++) {
907
+ if (cdCursor + 46 > bytes.length) {
908
+ throw new Error("Corrupted ZIP archive: truncated Central Directory header");
909
+ }
910
+ const sig = readUInt32LE(bytes, cdCursor);
911
+ if (sig !== CENTRAL_DIR_HEADER_SIG) {
912
+ throw new Error(`Corrupted ZIP archive: invalid Central Directory signature 0x${sig.toString(16)}`);
913
+ }
914
+ const compressionMethod = readUInt16LE(bytes, cdCursor + 10);
915
+ const expectedCrc = readUInt32LE(bytes, cdCursor + 16);
916
+ const compressedSize = readUInt32LE(bytes, cdCursor + 20);
917
+ const fileNameLen = readUInt16LE(bytes, cdCursor + 28);
918
+ const extraLen = readUInt16LE(bytes, cdCursor + 30);
919
+ const commentLen = readUInt16LE(bytes, cdCursor + 32);
920
+ const localHeaderOffset = readUInt32LE(bytes, cdCursor + 42);
921
+ const nameStart = cdCursor + 46;
922
+ const nameEnd = nameStart + fileNameLen;
923
+ if (nameEnd > bytes.length) {
924
+ throw new Error("Corrupted ZIP archive: file name exceeds buffer");
925
+ }
926
+ const rawName = textDecoder.decode(bytes.subarray(nameStart, nameEnd));
927
+ cdCursor = nameEnd + extraLen + commentLen;
928
+ if (rawName.endsWith("/")) continue;
929
+ const safeName = sanitizeZipPath(rawName);
930
+ if (!safeName) continue;
931
+ if (localHeaderOffset + 30 > bytes.length) {
932
+ throw new Error(`Corrupted ZIP archive: local header offset out of bounds for ${safeName}`);
933
+ }
934
+ const localSig = readUInt32LE(bytes, localHeaderOffset);
935
+ if (localSig !== LOCAL_FILE_HEADER_SIG) {
936
+ throw new Error(`Corrupted ZIP archive: invalid Local File Header signature for ${safeName}`);
937
+ }
938
+ const localNameLen = readUInt16LE(bytes, localHeaderOffset + 26);
939
+ const localExtraLen = readUInt16LE(bytes, localHeaderOffset + 28);
940
+ const dataStart = localHeaderOffset + 30 + localNameLen + localExtraLen;
941
+ const dataEnd = dataStart + compressedSize;
942
+ if (dataEnd > bytes.length) {
943
+ throw new Error(`Corrupted ZIP archive: file data truncated for ${safeName}`);
944
+ }
945
+ const rawFileBytes = bytes.subarray(dataStart, dataEnd);
946
+ if (compressionMethod !== 0) {
947
+ throw new Error(`Unsupported ZIP compression method ${compressionMethod} for ${safeName} (only Store=0 is supported)`);
948
+ }
949
+ const actualCrc = computeCrc32(rawFileBytes);
950
+ if (actualCrc !== expectedCrc) {
951
+ throw new Error(
952
+ `CRC32 integrity mismatch for ${safeName}: expected 0x${expectedCrc.toString(16)}, got 0x${actualCrc.toString(16)}`
953
+ );
954
+ }
955
+ result[safeName] = textDecoder.decode(rawFileBytes);
956
+ }
957
+ return result;
958
+ }
959
+ var zip_default = {
960
+ createZip,
961
+ extractZip,
962
+ computeCrc32,
963
+ sanitizeZipPath,
964
+ toUint8Array
965
+ };
966
+ return __toCommonJS(zip_exports);
967
+ })();
968
+
969
+ var CodeLabStorage = (() => {
970
+ var __defProp = Object.defineProperty;
971
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
972
+ var __getOwnPropNames = Object.getOwnPropertyNames;
973
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
974
+ var __export = (target, all) => {
975
+ for (var name in all)
976
+ __defProp(target, name, { get: all[name], enumerable: true });
977
+ };
978
+ var __copyProps = (to, from, except, desc) => {
979
+ if (from && typeof from === "object" || typeof from === "function") {
980
+ for (let key of __getOwnPropNames(from))
981
+ if (!__hasOwnProp.call(to, key) && key !== except)
982
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
983
+ }
984
+ return to;
985
+ };
986
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
987
+
988
+ // src/storage.ts
989
+ var storage_exports = {};
990
+ __export(storage_exports, {
991
+ WorkspaceStorage: () => WorkspaceStorage,
992
+ createWorkspaceStorage: () => createWorkspaceStorage,
993
+ default: () => storage_default
994
+ });
995
+ var DEFAULT_DB_NAME = "codelab_workspace_db";
996
+ var DEFAULT_STORE_NAME = "projects";
997
+ var DEFAULT_LS_PREFIX = "codelab:project:";
998
+ function cloneProject(project) {
999
+ const filesCopy = {};
1000
+ if (project.files && typeof project.files === "object") {
1001
+ for (const [k, v] of Object.entries(project.files)) {
1002
+ filesCopy[k] = String(v);
1003
+ }
1004
+ }
1005
+ return {
1006
+ id: String(project.id),
1007
+ name: String(project.name || project.id),
1008
+ files: filesCopy,
1009
+ updatedAt: typeof project.updatedAt === "number" ? project.updatedAt : Date.now(),
1010
+ ...project.createdAt !== void 0 ? { createdAt: project.createdAt } : {},
1011
+ ...project.entry !== void 0 ? { entry: project.entry } : {},
1012
+ ...project.testEntry !== void 0 ? { testEntry: project.testEntry } : {},
1013
+ ...project.version !== void 0 ? { version: project.version } : {}
1014
+ };
1015
+ }
1016
+ function isLocalStorageAvailable(prefix) {
1017
+ try {
1018
+ if (typeof globalThis === "undefined" || !("localStorage" in globalThis)) {
1019
+ return false;
1020
+ }
1021
+ const ls = globalThis.localStorage;
1022
+ if (!ls || typeof ls.getItem !== "function" || typeof ls.setItem !== "function") {
1023
+ return false;
1024
+ }
1025
+ const probeKey = `${prefix}__probe__`;
1026
+ ls.setItem(probeKey, "1");
1027
+ ls.removeItem(probeKey);
1028
+ return true;
1029
+ } catch (err) {
1030
+ const _ignored = err;
1031
+ return false;
1032
+ }
1033
+ }
1034
+ function isIndexedDbAvailable() {
1035
+ try {
1036
+ if (typeof globalThis === "undefined" || !("indexedDB" in globalThis)) {
1037
+ return false;
1038
+ }
1039
+ return Boolean(globalThis.indexedDB && typeof globalThis.indexedDB.open === "function");
1040
+ } catch (err) {
1041
+ const _ignored = err;
1042
+ return false;
1043
+ }
1044
+ }
1045
+ var WorkspaceStorage = class {
1046
+ dbName;
1047
+ storeName;
1048
+ storagePrefix;
1049
+ backendType;
1050
+ memoryStore = /* @__PURE__ */ new Map();
1051
+ dbPromise = null;
1052
+ constructor(options = {}) {
1053
+ this.dbName = options.dbName || DEFAULT_DB_NAME;
1054
+ this.storeName = options.storeName || DEFAULT_STORE_NAME;
1055
+ this.storagePrefix = options.storagePrefix || DEFAULT_LS_PREFIX;
1056
+ if (options.preferredBackend) {
1057
+ this.backendType = options.preferredBackend;
1058
+ } else if (isIndexedDbAvailable()) {
1059
+ this.backendType = "indexeddb";
1060
+ } else if (isLocalStorageAvailable(this.storagePrefix)) {
1061
+ this.backendType = "localstorage";
1062
+ } else {
1063
+ this.backendType = "memory";
1064
+ }
1065
+ }
1066
+ getBackendType() {
1067
+ return this.backendType;
1068
+ }
1069
+ openIdb() {
1070
+ if (this.dbPromise) return this.dbPromise;
1071
+ this.dbPromise = new Promise((resolve) => {
1072
+ try {
1073
+ const req = globalThis.indexedDB.open(this.dbName, 1);
1074
+ req.onupgradeneeded = () => {
1075
+ const db = req.result;
1076
+ if (!db.objectStoreNames.contains(this.storeName)) {
1077
+ db.createObjectStore(this.storeName, { keyPath: "id" });
1078
+ }
1079
+ };
1080
+ req.onsuccess = () => {
1081
+ resolve(req.result);
1082
+ };
1083
+ req.onerror = () => {
1084
+ resolve(null);
1085
+ };
1086
+ } catch (err) {
1087
+ const _ignored = err;
1088
+ resolve(null);
1089
+ }
1090
+ });
1091
+ return this.dbPromise;
1092
+ }
1093
+ downgradeFromIdb() {
1094
+ if (isLocalStorageAvailable(this.storagePrefix)) {
1095
+ this.backendType = "localstorage";
1096
+ } else {
1097
+ this.backendType = "memory";
1098
+ }
1099
+ }
1100
+ async saveProject(project) {
1101
+ if (!project || typeof project.id !== "string" || !project.id.trim()) {
1102
+ return false;
1103
+ }
1104
+ const normalized = cloneProject(project);
1105
+ this.memoryStore.set(normalized.id, normalized);
1106
+ if (this.backendType === "indexeddb") {
1107
+ const db = await this.openIdb();
1108
+ if (!db) {
1109
+ this.downgradeFromIdb();
1110
+ } else {
1111
+ const ok = await new Promise((resolve) => {
1112
+ try {
1113
+ const tx = db.transaction(this.storeName, "readwrite");
1114
+ const store = tx.objectStore(this.storeName);
1115
+ const req = store.put(normalized);
1116
+ req.onsuccess = () => resolve(true);
1117
+ req.onerror = () => resolve(false);
1118
+ } catch (err) {
1119
+ const _ignored = err;
1120
+ resolve(false);
1121
+ }
1122
+ });
1123
+ if (ok) return true;
1124
+ this.downgradeFromIdb();
1125
+ }
1126
+ }
1127
+ if (this.backendType === "localstorage") {
1128
+ try {
1129
+ const key = `${this.storagePrefix}${normalized.id}`;
1130
+ globalThis.localStorage.setItem(key, JSON.stringify(normalized));
1131
+ return true;
1132
+ } catch (err) {
1133
+ const _ignored = err;
1134
+ this.backendType = "memory";
1135
+ }
1136
+ }
1137
+ return true;
1138
+ }
1139
+ async loadProject(id) {
1140
+ if (!id || typeof id !== "string") return null;
1141
+ if (this.backendType === "indexeddb") {
1142
+ const db = await this.openIdb();
1143
+ if (!db) {
1144
+ this.downgradeFromIdb();
1145
+ } else {
1146
+ const found = await new Promise((resolve) => {
1147
+ try {
1148
+ const tx = db.transaction(this.storeName, "readonly");
1149
+ const store = tx.objectStore(this.storeName);
1150
+ const req = store.get(id);
1151
+ req.onsuccess = () => {
1152
+ const res = req.result;
1153
+ resolve(res ? cloneProject(res) : null);
1154
+ };
1155
+ req.onerror = () => resolve(null);
1156
+ } catch (err) {
1157
+ const _ignored = err;
1158
+ resolve(null);
1159
+ }
1160
+ });
1161
+ if (found) return found;
1162
+ }
1163
+ }
1164
+ if (this.backendType === "localstorage") {
1165
+ try {
1166
+ const raw = globalThis.localStorage.getItem(`${this.storagePrefix}${id}`);
1167
+ if (raw) {
1168
+ const parsed = JSON.parse(raw);
1169
+ if (parsed && typeof parsed.id === "string" && parsed.files && typeof parsed.files === "object") {
1170
+ return cloneProject(parsed);
1171
+ }
1172
+ }
1173
+ } catch (err) {
1174
+ const _ignored = err;
1175
+ }
1176
+ }
1177
+ const fromMem = this.memoryStore.get(id);
1178
+ return fromMem ? cloneProject(fromMem) : null;
1179
+ }
1180
+ async listProjects() {
1181
+ const byId = /* @__PURE__ */ new Map();
1182
+ const recordSummary = (proj) => {
1183
+ if (!proj || typeof proj.id !== "string") return;
1184
+ byId.set(proj.id, {
1185
+ id: proj.id,
1186
+ name: proj.name || proj.id,
1187
+ updatedAt: typeof proj.updatedAt === "number" ? proj.updatedAt : Date.now(),
1188
+ fileCount: proj.files && typeof proj.files === "object" ? Object.keys(proj.files).length : 0
1189
+ });
1190
+ };
1191
+ for (const p of this.memoryStore.values()) {
1192
+ recordSummary(p);
1193
+ }
1194
+ if (this.backendType === "indexeddb") {
1195
+ const db = await this.openIdb();
1196
+ if (db) {
1197
+ await new Promise((resolve) => {
1198
+ try {
1199
+ const tx = db.transaction(this.storeName, "readonly");
1200
+ const store = tx.objectStore(this.storeName);
1201
+ const req = store.getAll();
1202
+ req.onsuccess = () => {
1203
+ const items = Array.isArray(req.result) ? req.result : [];
1204
+ for (const item of items) {
1205
+ recordSummary(item);
1206
+ }
1207
+ resolve();
1208
+ };
1209
+ req.onerror = () => resolve();
1210
+ } catch (err) {
1211
+ const _ignored = err;
1212
+ resolve();
1213
+ }
1214
+ });
1215
+ }
1216
+ } else if (this.backendType === "localstorage") {
1217
+ try {
1218
+ const ls = globalThis.localStorage;
1219
+ for (let i = 0; i < ls.length; i++) {
1220
+ const key = ls.key(i);
1221
+ if (key && key.startsWith(this.storagePrefix)) {
1222
+ const raw = ls.getItem(key);
1223
+ if (raw) {
1224
+ try {
1225
+ const parsed = JSON.parse(raw);
1226
+ recordSummary(parsed);
1227
+ } catch (parseErr) {
1228
+ const _ignored = parseErr;
1229
+ }
1230
+ }
1231
+ }
1232
+ }
1233
+ } catch (err) {
1234
+ const _ignored = err;
1235
+ }
1236
+ }
1237
+ return Array.from(byId.values()).sort((a, b) => b.updatedAt - a.updatedAt);
1238
+ }
1239
+ async deleteProject(id) {
1240
+ if (!id || typeof id !== "string") return false;
1241
+ let existed = this.memoryStore.delete(id);
1242
+ if (this.backendType === "indexeddb") {
1243
+ const db = await this.openIdb();
1244
+ if (db) {
1245
+ const idbDeleted = await new Promise((resolve) => {
1246
+ try {
1247
+ const tx = db.transaction(this.storeName, "readwrite");
1248
+ const store = tx.objectStore(this.storeName);
1249
+ const checkReq = store.get(id);
1250
+ checkReq.onsuccess = () => {
1251
+ if (!checkReq.result) {
1252
+ resolve(false);
1253
+ return;
1254
+ }
1255
+ const delReq = store.delete(id);
1256
+ delReq.onsuccess = () => resolve(true);
1257
+ delReq.onerror = () => resolve(false);
1258
+ };
1259
+ checkReq.onerror = () => resolve(false);
1260
+ } catch (err) {
1261
+ const _ignored = err;
1262
+ resolve(false);
1263
+ }
1264
+ });
1265
+ existed = existed || idbDeleted;
1266
+ }
1267
+ }
1268
+ if (this.backendType === "localstorage") {
1269
+ try {
1270
+ const key = `${this.storagePrefix}${id}`;
1271
+ if (globalThis.localStorage.getItem(key) !== null) {
1272
+ globalThis.localStorage.removeItem(key);
1273
+ existed = true;
1274
+ }
1275
+ } catch (err) {
1276
+ const _ignored = err;
1277
+ }
1278
+ }
1279
+ return existed;
1280
+ }
1281
+ };
1282
+ function createWorkspaceStorage(options = {}) {
1283
+ return new WorkspaceStorage(options);
1284
+ }
1285
+ var storage_default = {
1286
+ WorkspaceStorage,
1287
+ createWorkspaceStorage
1288
+ };
1289
+ return __toCommonJS(storage_exports);
1290
+ })();
1291
+
1292
+ var CodeLabSearch = (() => {
1293
+ var __defProp = Object.defineProperty;
1294
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1295
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1296
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1297
+ var __export = (target, all) => {
1298
+ for (var name in all)
1299
+ __defProp(target, name, { get: all[name], enumerable: true });
1300
+ };
1301
+ var __copyProps = (to, from, except, desc) => {
1302
+ if (from && typeof from === "object" || typeof from === "function") {
1303
+ for (let key of __getOwnPropNames(from))
1304
+ if (!__hasOwnProp.call(to, key) && key !== except)
1305
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1306
+ }
1307
+ return to;
1308
+ };
1309
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1310
+
1311
+ // src/search.ts
1312
+ var search_exports = {};
1313
+ __export(search_exports, {
1314
+ escapeRegex: () => escapeRegex,
1315
+ matchesGlob: () => matchesGlob,
1316
+ normalizeSearchPath: () => normalizeSearchPath,
1317
+ replaceInFiles: () => replaceInFiles,
1318
+ searchInFiles: () => searchInFiles
1319
+ });
1320
+ function escapeRegex(text) {
1321
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1322
+ }
1323
+ function normalizeSearchPath(filePath) {
1324
+ let p = filePath.replace(/\\/g, "/");
1325
+ while (p.startsWith("./")) {
1326
+ p = p.slice(2);
1327
+ }
1328
+ while (p.startsWith("/")) {
1329
+ p = p.slice(1);
1330
+ }
1331
+ return p;
1332
+ }
1333
+ function matchesGlob(filePath, pattern) {
1334
+ if (!pattern || pattern === "*" || pattern === "**") return true;
1335
+ const normPath = normalizeSearchPath(filePath);
1336
+ const normPattern = normalizeSearchPath(pattern);
1337
+ if (normPattern === normPath) return true;
1338
+ if (!normPattern.includes("*") && !normPattern.includes("?")) {
1339
+ return normPath.includes(normPattern) || normPath.endsWith(normPattern);
1340
+ }
1341
+ let regexStr = "^";
1342
+ let i = 0;
1343
+ while (i < normPattern.length) {
1344
+ const c = normPattern[i];
1345
+ if (c === "*") {
1346
+ if (normPattern[i + 1] === "*") {
1347
+ regexStr += ".*";
1348
+ i += 2;
1349
+ if (normPattern[i] === "/") {
1350
+ i++;
1351
+ }
1352
+ continue;
1353
+ } else {
1354
+ regexStr += "[^/]*";
1355
+ i++;
1356
+ continue;
1357
+ }
1358
+ } else if (c === "?") {
1359
+ regexStr += "[^/]";
1360
+ i++;
1361
+ continue;
1362
+ } else if ("./+^$()|[]{}\\".includes(c)) {
1363
+ regexStr += "\\" + c;
1364
+ i++;
1365
+ continue;
1366
+ } else {
1367
+ regexStr += c;
1368
+ i++;
1369
+ }
1370
+ }
1371
+ regexStr += "$";
1372
+ try {
1373
+ const re = new RegExp(regexStr);
1374
+ return re.test(normPath);
1375
+ } catch (err) {
1376
+ return normPath.includes(normPattern.replace(/[*?]/g, ""));
1377
+ }
1378
+ }
1379
+ function checkFilter(path, filter) {
1380
+ if (!filter) return true;
1381
+ if (Array.isArray(filter)) {
1382
+ return filter.some((f) => matchesGlob(path, f));
1383
+ }
1384
+ return matchesGlob(path, filter);
1385
+ }
1386
+ function createSearchResult(groups, totalMatches, fileCount, query, error) {
1387
+ const arr = [...groups];
1388
+ const result = Object.assign(arr, {
1389
+ matches: groups,
1390
+ totalMatches,
1391
+ fileCount,
1392
+ filesCount: fileCount,
1393
+ query,
1394
+ durationMs: 0,
1395
+ error
1396
+ });
1397
+ return result;
1398
+ }
1399
+ function searchInFiles(files, queryOrOptions, optionsOrUndefined) {
1400
+ let query = "";
1401
+ let opts = {};
1402
+ if (typeof queryOrOptions === "string") {
1403
+ query = queryOrOptions;
1404
+ opts = optionsOrUndefined || {};
1405
+ } else if (queryOrOptions && typeof queryOrOptions === "object") {
1406
+ opts = queryOrOptions;
1407
+ query = opts.query || "";
1408
+ }
1409
+ if (!query) {
1410
+ return createSearchResult([], 0, 0, query);
1411
+ }
1412
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1413
+ const isWholeWord = Boolean(opts.wholeWord);
1414
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1415
+ const maxMatches = opts.maxMatches ?? 1e4;
1416
+ const maxMatchesPerFile = opts.maxMatchesPerFile ?? 1e3;
1417
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1418
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1419
+ let patternStr = isRegex ? query : escapeRegex(query);
1420
+ if (isWholeWord) {
1421
+ patternStr = `\\b${patternStr}\\b`;
1422
+ }
1423
+ let regex = /(?:)/;
1424
+ try {
1425
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1426
+ } catch (err) {
1427
+ const _err = err;
1428
+ const msg = typeof _err === "object" && _err && "message" in _err ? String(_err.message) : "Invalid regular expression";
1429
+ return createSearchResult([], 0, 0, query, msg);
1430
+ }
1431
+ const matchedGroups = [];
1432
+ let totalMatches = 0;
1433
+ for (const [filePath, content] of Object.entries(files)) {
1434
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1435
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1436
+ if (opts.targetFiles && !opts.targetFiles.includes(filePath)) continue;
1437
+ const fileMatches = [];
1438
+ const lines = content.split("\n");
1439
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
1440
+ const lineText = lines[lineIndex];
1441
+ regex.lastIndex = 0;
1442
+ let m = null;
1443
+ while ((m = regex.exec(lineText)) !== null) {
1444
+ const matchLen = m[0].length;
1445
+ const col = m.index + 1;
1446
+ fileMatches.push({
1447
+ line: lineIndex + 1,
1448
+ col,
1449
+ column: col,
1450
+ length: matchLen,
1451
+ matchText: m[0],
1452
+ lineText,
1453
+ beforeSnippet: lineText.slice(0, m.index),
1454
+ afterSnippet: lineText.slice(m.index + matchLen),
1455
+ matchIndex: m.index,
1456
+ matchEndIndex: m.index + matchLen
1457
+ });
1458
+ totalMatches++;
1459
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1460
+ break;
1461
+ }
1462
+ if (matchLen === 0) {
1463
+ regex.lastIndex++;
1464
+ if (regex.lastIndex > lineText.length) {
1465
+ break;
1466
+ }
1467
+ }
1468
+ }
1469
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1470
+ break;
1471
+ }
1472
+ }
1473
+ if (fileMatches.length > 0) {
1474
+ matchedGroups.push({
1475
+ file: filePath,
1476
+ matches: fileMatches
1477
+ });
1478
+ }
1479
+ if (totalMatches >= maxMatches) {
1480
+ break;
1481
+ }
1482
+ }
1483
+ return createSearchResult(matchedGroups, totalMatches, matchedGroups.length, query);
1484
+ }
1485
+ function replaceInFiles(files, arg2, arg3, arg4) {
1486
+ let query = "";
1487
+ const replacement = typeof arg3 === "string" ? arg3 : "";
1488
+ let opts = {};
1489
+ let targetFiles = void 0;
1490
+ if (typeof arg2 === "string") {
1491
+ query = arg2;
1492
+ if (Array.isArray(arg4)) {
1493
+ targetFiles = arg4;
1494
+ } else if (arg4 && typeof arg4 === "object") {
1495
+ opts = arg4;
1496
+ targetFiles = opts.targetFiles;
1497
+ }
1498
+ } else if (arg2 && typeof arg2 === "object") {
1499
+ opts = arg2;
1500
+ query = opts.query || "";
1501
+ if (Array.isArray(arg4)) {
1502
+ targetFiles = arg4;
1503
+ } else {
1504
+ targetFiles = opts.targetFiles;
1505
+ }
1506
+ }
1507
+ if (!query) {
1508
+ return {
1509
+ updatedFiles: { ...files },
1510
+ replacedCount: 0,
1511
+ filesAffected: []
1512
+ };
1513
+ }
1514
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1515
+ const isWholeWord = Boolean(opts.wholeWord);
1516
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1517
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1518
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1519
+ let patternStr = isRegex ? query : escapeRegex(query);
1520
+ if (isWholeWord) {
1521
+ patternStr = `\\b${patternStr}\\b`;
1522
+ }
1523
+ let regex = /(?:)/;
1524
+ try {
1525
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1526
+ } catch (err) {
1527
+ return {
1528
+ updatedFiles: { ...files },
1529
+ replacedCount: 0,
1530
+ filesAffected: []
1531
+ };
1532
+ }
1533
+ const updatedFiles = { ...files };
1534
+ const filesAffected = [];
1535
+ let replacedCount = 0;
1536
+ for (const [filePath, content] of Object.entries(files)) {
1537
+ if (targetFiles && !targetFiles.includes(filePath)) continue;
1538
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1539
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1540
+ regex.lastIndex = 0;
1541
+ let countInFile = 0;
1542
+ let m;
1543
+ while ((m = regex.exec(content)) !== null) {
1544
+ countInFile++;
1545
+ if (m[0].length === 0) {
1546
+ regex.lastIndex++;
1547
+ if (regex.lastIndex > content.length) {
1548
+ break;
1549
+ }
1550
+ }
1551
+ }
1552
+ if (countInFile > 0) {
1553
+ regex.lastIndex = 0;
1554
+ let newContent;
1555
+ if (isRegex) {
1556
+ newContent = content.replace(regex, replacement);
1557
+ } else {
1558
+ newContent = content.replace(regex, () => replacement);
1559
+ }
1560
+ updatedFiles[filePath] = newContent;
1561
+ filesAffected.push(filePath);
1562
+ replacedCount += countInFile;
1563
+ }
1564
+ }
1565
+ return {
1566
+ updatedFiles,
1567
+ replacedCount,
1568
+ filesAffected
1569
+ };
1570
+ }
1571
+ return __toCommonJS(search_exports);
1572
+ })();
1573
+
1574
+ var CodeLabDiagnostics = (() => {
1575
+ var __defProp = Object.defineProperty;
1576
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1577
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1578
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1579
+ var __export = (target, all) => {
1580
+ for (var name in all)
1581
+ __defProp(target, name, { get: all[name], enumerable: true });
1582
+ };
1583
+ var __copyProps = (to, from, except, desc) => {
1584
+ if (from && typeof from === "object" || typeof from === "function") {
1585
+ for (let key of __getOwnPropNames(from))
1586
+ if (!__hasOwnProp.call(to, key) && key !== except)
1587
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1588
+ }
1589
+ return to;
1590
+ };
1591
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1592
+
1593
+ // src/diagnostics.ts
1594
+ var diagnostics_exports = {};
1595
+ __export(diagnostics_exports, {
1596
+ DiagnosticsStore: () => DiagnosticsStore,
1597
+ createDiagnosticsStore: () => createDiagnosticsStore,
1598
+ default: () => diagnostics_default
1599
+ });
1600
+ var DiagnosticsStore = class {
1601
+ items = /* @__PURE__ */ new Map();
1602
+ listeners = /* @__PURE__ */ new Set();
1603
+ add(item) {
1604
+ if (!item || typeof item.id !== "string" || !item.id) return;
1605
+ const normalized = {
1606
+ ...item,
1607
+ file: String(item.file || ""),
1608
+ line: typeof item.line === "number" && item.line > 0 ? Math.floor(item.line) : 1,
1609
+ col: typeof item.col === "number" && item.col > 0 ? Math.floor(item.col) : typeof item.column === "number" && item.column > 0 ? Math.floor(item.column) : 1,
1610
+ message: String(item.message || ""),
1611
+ severity: item.severity || "error"
1612
+ };
1613
+ this.items.set(normalized.id, normalized);
1614
+ this.notify();
1615
+ }
1616
+ remove(id) {
1617
+ if (this.items.delete(id)) {
1618
+ this.notify();
1619
+ }
1620
+ }
1621
+ clear(source) {
1622
+ if (source !== void 0 && source !== "") {
1623
+ let changed = false;
1624
+ for (const [id, item] of this.items.entries()) {
1625
+ if (item.source === source) {
1626
+ this.items.delete(id);
1627
+ changed = true;
1628
+ }
1629
+ }
1630
+ if (changed) {
1631
+ this.notify();
1632
+ }
1633
+ } else if (this.items.size > 0) {
1634
+ this.items.clear();
1635
+ this.notify();
1636
+ }
1637
+ }
1638
+ getAll() {
1639
+ return Array.from(this.items.values());
1640
+ }
1641
+ getByFile(file) {
1642
+ const out = [];
1643
+ for (const item of this.items.values()) {
1644
+ if (item.file === file) {
1645
+ out.push(item);
1646
+ }
1647
+ }
1648
+ return out;
1649
+ }
1650
+ subscribe(listener) {
1651
+ this.listeners.add(listener);
1652
+ return () => {
1653
+ this.listeners.delete(listener);
1654
+ };
1655
+ }
1656
+ notify() {
1657
+ if (this.listeners.size === 0) return;
1658
+ const snapshot = this.getAll();
1659
+ for (const listener of this.listeners) {
1660
+ try {
1661
+ listener(snapshot);
1662
+ } catch (err) {
1663
+ console.warn("[code-lab] diagnostics subscriber error:", err);
1664
+ }
1665
+ }
1666
+ }
1667
+ };
1668
+ function createDiagnosticsStore() {
1669
+ return new DiagnosticsStore();
1670
+ }
1671
+ var diagnostics_default = {
1672
+ DiagnosticsStore,
1673
+ createDiagnosticsStore
1674
+ };
1675
+ return __toCommonJS(diagnostics_exports);
1676
+ })();
1677
+
1678
+ var CodeLabScm = (() => {
1679
+ var __defProp = Object.defineProperty;
1680
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1681
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1682
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1683
+ var __export = (target, all) => {
1684
+ for (var name in all)
1685
+ __defProp(target, name, { get: all[name], enumerable: true });
1686
+ };
1687
+ var __copyProps = (to, from, except, desc) => {
1688
+ if (from && typeof from === "object" || typeof from === "function") {
1689
+ for (let key of __getOwnPropNames(from))
1690
+ if (!__hasOwnProp.call(to, key) && key !== except)
1691
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1692
+ }
1693
+ return to;
1694
+ };
1695
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1696
+
1697
+ // src/scm.ts
1698
+ var scm_exports = {};
1699
+ __export(scm_exports, {
1700
+ commitChanges: () => commitChanges,
1701
+ computeGitStatus: () => computeGitStatus,
1702
+ computeShortCommitHash: () => computeShortCommitHash,
1703
+ createGitState: () => createGitState,
1704
+ default: () => scm_default,
1705
+ stageFile: () => stageFile,
1706
+ unstageFile: () => unstageFile
1707
+ });
1708
+ function computeShortCommitHash(input) {
1709
+ let h1 = 3735928559 ^ input.length;
1710
+ let h2 = 1103547991 ^ input.length;
1711
+ for (let i = 0; i < input.length; i++) {
1712
+ const ch = input.charCodeAt(i);
1713
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1714
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1715
+ }
1716
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1717
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1718
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
1719
+ return combined.toString(16).padStart(7, "0").slice(0, 7);
1720
+ }
1721
+ function createGitState(initialFiles = {}, branch = "main") {
1722
+ const headFiles = { ...initialFiles };
1723
+ const initialHash = computeShortCommitHash(JSON.stringify(headFiles) + ":init");
1724
+ return {
1725
+ branch,
1726
+ branches: [branch],
1727
+ headCommit: initialHash,
1728
+ headFiles,
1729
+ staged: /* @__PURE__ */ new Map(),
1730
+ commits: [
1731
+ {
1732
+ hash: initialHash,
1733
+ message: "Initial commit",
1734
+ timestamp: Date.now(),
1735
+ files: { ...headFiles }
1736
+ }
1737
+ ]
1738
+ };
1739
+ }
1740
+ function computeGitStatus(vfsFiles, _repoRoot = "/workspace", gitState) {
1741
+ const state = gitState || createGitState({});
1742
+ const headFiles = state.headFiles || {};
1743
+ const currentStaged = state.staged instanceof Map ? state.staged : /* @__PURE__ */ new Map();
1744
+ const untracked = [];
1745
+ const modified = [];
1746
+ const deleted = [];
1747
+ const staged = [];
1748
+ for (const [filePath, stagedContent] of currentStaged.entries()) {
1749
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
1750
+ if (stagedContent === null) {
1751
+ staged.push({
1752
+ path: filePath,
1753
+ status: "deleted",
1754
+ staged: true,
1755
+ oldContent: headFiles[filePath]
1756
+ });
1757
+ } else {
1758
+ staged.push({
1759
+ path: filePath,
1760
+ status: inHead ? "modified" : "added",
1761
+ staged: true,
1762
+ oldContent: inHead ? headFiles[filePath] : void 0,
1763
+ newContent: stagedContent
1764
+ });
1765
+ }
1766
+ }
1767
+ for (const [filePath, content] of Object.entries(vfsFiles || {})) {
1768
+ if (currentStaged.has(filePath)) {
1769
+ const stagedVal = currentStaged.get(filePath);
1770
+ if (stagedVal !== content) {
1771
+ modified.push({
1772
+ path: filePath,
1773
+ status: "modified",
1774
+ staged: false,
1775
+ oldContent: stagedVal ?? void 0,
1776
+ newContent: content
1777
+ });
1778
+ }
1779
+ } else if (Object.prototype.hasOwnProperty.call(headFiles, filePath)) {
1780
+ if (headFiles[filePath] !== content) {
1781
+ modified.push({
1782
+ path: filePath,
1783
+ status: "modified",
1784
+ staged: false,
1785
+ oldContent: headFiles[filePath],
1786
+ newContent: content
1787
+ });
1788
+ }
1789
+ } else {
1790
+ untracked.push({
1791
+ path: filePath,
1792
+ status: "untracked",
1793
+ staged: false,
1794
+ newContent: content
1795
+ });
1796
+ }
1797
+ }
1798
+ for (const filePath of Object.keys(headFiles)) {
1799
+ if (!Object.prototype.hasOwnProperty.call(vfsFiles, filePath) && !currentStaged.has(filePath)) {
1800
+ deleted.push({
1801
+ path: filePath,
1802
+ status: "deleted",
1803
+ staged: false,
1804
+ oldContent: headFiles[filePath]
1805
+ });
1806
+ }
1807
+ }
1808
+ const unstaged = [...modified, ...deleted];
1809
+ const isClean = untracked.length === 0 && modified.length === 0 && deleted.length === 0 && staged.length === 0;
1810
+ return {
1811
+ branch: state.branch || "main",
1812
+ headCommit: state.headCommit || "",
1813
+ untracked,
1814
+ modified,
1815
+ deleted,
1816
+ staged,
1817
+ unstaged,
1818
+ hasChanges: !isClean,
1819
+ isClean
1820
+ };
1821
+ }
1822
+ function stageFile(gitState, relativePath, currentContent) {
1823
+ if (!gitState) return;
1824
+ if (!(gitState.staged instanceof Map)) {
1825
+ gitState.staged = /* @__PURE__ */ new Map();
1826
+ }
1827
+ gitState.staged.set(relativePath, currentContent === void 0 ? null : currentContent);
1828
+ }
1829
+ function unstageFile(gitState, relativePath) {
1830
+ if (!gitState || !(gitState.staged instanceof Map)) return;
1831
+ gitState.staged.delete(relativePath);
1832
+ }
1833
+ function commitChanges(gitState, message) {
1834
+ const trimmed = typeof message === "string" ? message.trim() : "";
1835
+ if (!trimmed) {
1836
+ throw new Error("Commit message cannot be empty");
1837
+ }
1838
+ if (!gitState || !(gitState.staged instanceof Map) || gitState.staged.size === 0) {
1839
+ throw new Error("Nothing to commit (staging area is empty)");
1840
+ }
1841
+ const newHeadFiles = { ...gitState.headFiles || {} };
1842
+ for (const [filePath, content] of gitState.staged.entries()) {
1843
+ if (content === null) {
1844
+ delete newHeadFiles[filePath];
1845
+ } else {
1846
+ newHeadFiles[filePath] = content;
1847
+ }
1848
+ }
1849
+ const timestamp = Date.now();
1850
+ const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
1851
+ const commit = {
1852
+ hash,
1853
+ message: trimmed,
1854
+ timestamp,
1855
+ files: newHeadFiles
1856
+ };
1857
+ if (!Array.isArray(gitState.commits)) {
1858
+ gitState.commits = [];
1859
+ }
1860
+ gitState.commits.push(commit);
1861
+ gitState.headCommit = hash;
1862
+ gitState.headFiles = newHeadFiles;
1863
+ gitState.staged.clear();
1864
+ return hash;
1865
+ }
1866
+ var scm_default = {
1867
+ createGitState,
1868
+ computeGitStatus,
1869
+ stageFile,
1870
+ unstageFile,
1871
+ commitChanges,
1872
+ computeShortCommitHash
1873
+ };
1874
+ return __toCommonJS(scm_exports);
1875
+ })();
1876
+
1877
+ _root.CodeLabZip = CodeLabZip;
1878
+ _root.CodeLabStorage = CodeLabStorage;
1879
+ _root.CodeLabSearch = CodeLabSearch;
1880
+ _root.CodeLabDiagnostics = CodeLabDiagnostics;
1881
+ _root.CodeLabScm = CodeLabScm;
1882
+
19
1883
  // --- Module 1: Runtime Engine ---
20
1884
  (function () {
21
1885
  // @ts-nocheck
@@ -40,6 +1904,14 @@ if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined')
40
1904
  */
41
1905
 
42
1906
  function __initVirtualRuntime(rootScope) {
1907
+ const _runtimeLogger = (rootScope && rootScope.CodeLabLogger && typeof rootScope.CodeLabLogger.createLogger === 'function')
1908
+ ? rootScope.CodeLabLogger.createLogger()
1909
+ : {
1910
+ debug() {},
1911
+ info() {},
1912
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
1913
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
1914
+ };
43
1915
  // =========================================================================
44
1916
  // 1. UTF-8 / HEX / BASE64 / BASE64URL CODECS & VIRTUAL BUFFER
45
1917
  // =========================================================================
@@ -1599,7 +3471,7 @@ function __initVirtualRuntime(rootScope) {
1599
3471
  },
1600
3472
  final(cb) {
1601
3473
  if (fd !== null) {
1602
- try { fsShim.closeSync(fd); } catch (_) {}
3474
+ try { fsShim.closeSync(fd); } catch (err) { _runtimeLogger.debug('vfs writeStream closeSync failed', err); }
1603
3475
  fd = null;
1604
3476
  }
1605
3477
  cb(null);
@@ -2119,7 +3991,9 @@ function __initVirtualRuntime(rootScope) {
2119
3991
  return pathname + search + hash;
2120
3992
  }
2121
3993
  return resolvedUrl.href;
2122
- } catch (_) {}
3994
+ } catch (err) {
3995
+ _runtimeLogger.debug('url.resolve fallback used', err);
3996
+ }
2123
3997
  }
2124
3998
  if (toStr.startsWith('/')) {
2125
3999
  const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(fromStr);
@@ -2558,10 +4432,10 @@ function __initVirtualRuntime(rootScope) {
2558
4432
  for (const [port, entry] of Array.from(table.entries())) {
2559
4433
  if (entry.pid !== undefined && String(entry.pid) === pStr) {
2560
4434
  if (entry.server && typeof entry.server.close === 'function') {
2561
- try { entry.server.close(); } catch (_) {}
4435
+ try { entry.server.close(); } catch (err) { _runtimeLogger.debug('portTable server.close failed', err); }
2562
4436
  }
2563
4437
  if (typeof entry.stop === 'function') {
2564
- try { entry.stop(); } catch (_) {}
4438
+ try { entry.stop(); } catch (err) { _runtimeLogger.debug('portTable entry.stop failed', err); }
2565
4439
  }
2566
4440
  // Avoid a double 'close' emission when entry.server.close() already
2567
4441
  // unregistered the port through unregisterServer().
@@ -3198,7 +5072,7 @@ function __initVirtualRuntime(rootScope) {
3198
5072
  },
3199
5073
  closeAllServers() {
3200
5074
  for (const s of Array.from(activeServers.values())) {
3201
- try { s.close(); } catch (_) {}
5075
+ try { s.close(); } catch (err) { _runtimeLogger.debug('vhttp closeAllServers close failed', err); }
3202
5076
  }
3203
5077
  activeServers.clear();
3204
5078
  }
@@ -4024,7 +5898,7 @@ function __initVirtualRuntime(rootScope) {
4024
5898
 
4025
5899
  function closeAllServers() {
4026
5900
  for (const srv of servers.values()) {
4027
- try { srv.close(); } catch (_) {}
5901
+ try { srv.close(); } catch (err) { _runtimeLogger.debug('vnet closeAllServers close failed', err); }
4028
5902
  }
4029
5903
  servers.clear();
4030
5904
  }
@@ -5104,7 +6978,9 @@ function __initVirtualRuntime(rootScope) {
5104
6978
  try {
5105
6979
  const pkgJson = JSON.parse(content);
5106
6980
  for (const dep of Object.keys(pkgJson.dependencies || {})) addSpec(dep);
5107
- } catch (_) {}
6981
+ } catch (err) {
6982
+ _runtimeLogger.debug('preloadNpmPackages invalid package.json', err);
6983
+ }
5108
6984
  continue;
5109
6985
  }
5110
6986
  const reqRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
@@ -5133,7 +7009,9 @@ function __initVirtualRuntime(rootScope) {
5133
7009
  const meta = await res.json();
5134
7010
  deps = Object.keys((meta && meta.dependencies) || {});
5135
7011
  }
5136
- } catch (_) {}
7012
+ } catch (err) {
7013
+ _runtimeLogger.debug('preloadNpmPackages metadata fetch failed', { pkg, err });
7014
+ }
5137
7015
  _npmMetadataCache.set(pkg, deps);
5138
7016
  }));
5139
7017
  for (const pkg of pending) {
@@ -5151,7 +7029,7 @@ function __initVirtualRuntime(rootScope) {
5151
7029
  continue;
5152
7030
  }
5153
7031
  if (typeof onProgress === 'function') {
5154
- try { onProgress(pkg); } catch (_) {}
7032
+ try { onProgress(pkg); } catch (err) { _runtimeLogger.debug('preloadNpmPackages onProgress callback failed', err); }
5155
7033
  }
5156
7034
  if (typeof fetch === 'function') {
5157
7035
  try {
@@ -5161,7 +7039,9 @@ function __initVirtualRuntime(rootScope) {
5161
7039
  if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
5162
7040
  loaded[pkg] = text;
5163
7041
  }
5164
- } catch (_) {}
7042
+ } catch (err) {
7043
+ _runtimeLogger.debug('preloadNpmPackages package fetch failed', { pkg, err });
7044
+ }
5165
7045
  }
5166
7046
  }
5167
7047
  return loaded;
@@ -5353,7 +7233,9 @@ function __initVirtualRuntime(rootScope) {
5353
7233
  const dir = VirtualPath.dirname(abs);
5354
7234
  if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
5355
7235
  vfs.writeFileSync(abs, content);
5356
- } catch (_) {}
7236
+ } catch (err) {
7237
+ _runtimeLogger.warn('vfs initial file seed failed', { abs, err });
7238
+ }
5357
7239
  }
5358
7240
  }
5359
7241
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
@@ -5798,7 +7680,7 @@ function __initVirtualRuntime(rootScope) {
5798
7680
  exitCode = Number(code) || 0;
5799
7681
  if (!hasExited) {
5800
7682
  hasExited = true;
5801
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
7683
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('process exit listener threw', err); }
5802
7684
  }
5803
7685
  if (syncExecDepth > 0) {
5804
7686
  throw new ProcessExitSignal(exitCode);
@@ -5831,8 +7713,8 @@ function __initVirtualRuntime(rootScope) {
5831
7713
  resourceTracker.inFlightHttp.clear();
5832
7714
 
5833
7715
  if (!isBackground) {
5834
- try { vhttp.closeAllServers(); } catch (_) {}
5835
- try { vnet.closeAllServers(); } catch (_) {}
7716
+ try { vhttp.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vhttp closeAllServers failed', err); }
7717
+ try { vnet.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vnet closeAllServers failed', err); }
5836
7718
  }
5837
7719
  };
5838
7720
 
@@ -5942,10 +7824,10 @@ function __initVirtualRuntime(rootScope) {
5942
7824
  sandboxConsole.log(`✗ ${fullName}\n ${e && e.stack ? e.stack : e}`);
5943
7825
  } finally {
5944
7826
  for (const ae of hooksSnapshot.afterEachList) {
5945
- try { await ae(); } catch (_) {}
7827
+ try { await ae(); } catch (err) { _runtimeLogger.debug('node:test afterEach hook failed', err); }
5946
7828
  }
5947
7829
  for (const af of hooksSnapshot.afterToRun) {
5948
- try { await af(); } catch (_) {}
7830
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test after hook failed', err); }
5949
7831
  }
5950
7832
  hooksSnapshot.afterToRun.length = 0;
5951
7833
  }
@@ -5993,7 +7875,7 @@ function __initVirtualRuntime(rootScope) {
5993
7875
  const afters = [...suiteCtx.afterCallbacks];
5994
7876
  const cleanupTask = nodeTestChain.then(async () => {
5995
7877
  for (const af of afters) {
5996
- try { await af(); } catch (_) {}
7878
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test suite after hook failed', err); }
5997
7879
  }
5998
7880
  });
5999
7881
  nodeTestChain = cleanupTask.catch(() => {});
@@ -6039,7 +7921,7 @@ function __initVirtualRuntime(rootScope) {
6039
7921
  getEntriesByName: (n, t) => (entry.name === n && (!t || entry.entryType === t) ? [entry] : []),
6040
7922
  getEntriesByType: (t) => (entry.entryType === t ? [entry] : [])
6041
7923
  };
6042
- try { obs._cb(list, obs); } catch (_) {}
7924
+ try { obs._cb(list, obs); } catch (err) { _runtimeLogger.debug('PerformanceObserver callback failed', err); }
6043
7925
  }
6044
7926
  }
6045
7927
  }
@@ -6144,7 +8026,7 @@ function __initVirtualRuntime(rootScope) {
6144
8026
  getEntriesByName: (n, t) => buffered.filter((e) => e.name === n && (!t || e.entryType === t)),
6145
8027
  getEntriesByType: (t) => buffered.filter((e) => e.entryType === t)
6146
8028
  };
6147
- queueMicrotask(() => { try { this._cb(list, this); } catch (_) {} });
8029
+ queueMicrotask(() => { try { this._cb(list, this); } catch (err) { _runtimeLogger.debug('PerformanceObserver buffered callback failed', err); } });
6148
8030
  }
6149
8031
  }
6150
8032
  }
@@ -7415,7 +9297,9 @@ function __initVirtualRuntime(rootScope) {
7415
9297
  const resolvedEntry = resolveFileOrDirCandidates(VirtualPath.resolve(base, entryRel));
7416
9298
  if (resolvedEntry) return resolvedEntry;
7417
9299
  }
7418
- } catch (_) {}
9300
+ } catch (err) {
9301
+ _runtimeLogger.debug('resolveFileOrDirCandidates package.json parse failed', err);
9302
+ }
7419
9303
  }
7420
9304
  const indexCandidates = ['index.js', 'index.ts', 'index.mjs', 'index.cjs', 'index.json'];
7421
9305
  for (const idx of indexCandidates) {
@@ -7485,7 +9369,9 @@ function __initVirtualRuntime(rootScope) {
7485
9369
  if (found) return found;
7486
9370
  }
7487
9371
  }
7488
- } catch (_) {}
9372
+ } catch (err) {
9373
+ _runtimeLogger.debug('resolveModulePath subpath package.json parse failed', err);
9374
+ }
7489
9375
  }
7490
9376
  const foundSub = resolveFileOrDirCandidates(VirtualPath.join(pkgRoot, subpath));
7491
9377
  if (foundSub) return foundSub;
@@ -7527,7 +9413,9 @@ function __initVirtualRuntime(rootScope) {
7527
9413
  if (isLocal && activePortTable) {
7528
9414
  return await activePortTable.dispatchRequest(urlStr, finalInit);
7529
9415
  }
7530
- } catch (_) {}
9416
+ } catch (err) {
9417
+ _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
9418
+ }
7531
9419
 
7532
9420
  if (typeof globalThis.fetch === 'function') {
7533
9421
  return await globalThis.fetch(urlOrReq, init);
@@ -7694,7 +9582,9 @@ function __initVirtualRuntime(rootScope) {
7694
9582
  if (err instanceof SyntaxError && (/\bawait\b/.test(body) || /await/i.test(err.message))) {
7695
9583
  try {
7696
9584
  return new AsyncFunction(...argNames, body);
7697
- } catch (_) {}
9585
+ } catch (asyncErr) {
9586
+ _runtimeLogger.debug('AsyncFunction compilation fallback failed', asyncErr);
9587
+ }
7698
9588
  }
7699
9589
  if (
7700
9590
  err &&
@@ -7748,7 +9638,9 @@ function __initVirtualRuntime(rootScope) {
7748
9638
  if (signal && onAbort) {
7749
9639
  try {
7750
9640
  signal.removeEventListener('abort', onAbort);
7751
- } catch (_) {}
9641
+ } catch (err) {
9642
+ _runtimeLogger.debug('raceWithAbort removeEventListener failed', err);
9643
+ }
7752
9644
  }
7753
9645
  };
7754
9646
 
@@ -7907,11 +9799,11 @@ function __initVirtualRuntime(rootScope) {
7907
9799
  }
7908
9800
  } finally {
7909
9801
  if (signal && signalListener) {
7910
- try { signal.removeEventListener('abort', signalListener); } catch (_) {}
9802
+ try { signal.removeEventListener('abort', signalListener); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime removeEventListener failed', err); }
7911
9803
  }
7912
9804
  if (!hasExited) {
7913
9805
  hasExited = true;
7914
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
9806
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
7915
9807
  }
7916
9808
  for (const rawId of resourceTracker.allTimers) {
7917
9809
  clearTimeout(rawId);
@@ -8019,7 +9911,16 @@ function createWorkerRuntimeSource() {
8019
9911
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
8020
9912
  }
8021
9913
 
8022
- const _hostRuntime = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
9914
+ const _hostScope = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global);
9915
+ const _hostLogger = (_hostScope && _hostScope.CodeLabLogger && typeof _hostScope.CodeLabLogger.createLogger === 'function')
9916
+ ? _hostScope.CodeLabLogger.createLogger()
9917
+ : {
9918
+ debug() {},
9919
+ info() {},
9920
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
9921
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
9922
+ };
9923
+ const _hostRuntime = __initVirtualRuntime(_hostScope);
8023
9924
  _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
8024
9925
 
8025
9926
  let _cachedWorkerUrl = null;
@@ -8043,7 +9944,7 @@ function _ensureWarmWorker() {
8043
9944
 
8044
9945
  function _destroyWarmWorker() {
8045
9946
  if (_warmWorker) {
8046
- try { _warmWorker.terminate(); } catch (_) {}
9947
+ try { _warmWorker.terminate(); } catch (err) { _hostLogger.debug('warmWorker.terminate failed', err); }
8047
9948
  _warmWorker = null;
8048
9949
  }
8049
9950
  _warmWorkerBusy = false;
@@ -8098,7 +9999,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8098
9999
 
8099
10000
  function releaseWorker(terminateWorker) {
8100
10001
  if (options.signal && abortListener) {
8101
- try { options.signal.removeEventListener('abort', abortListener); } catch (_) {}
10002
+ try { options.signal.removeEventListener('abort', abortListener); } catch (err) { _hostLogger.debug('executeInWorker removeEventListener failed', err); }
8102
10003
  abortListener = null;
8103
10004
  }
8104
10005
  _activeWorkerJobs.delete(requestId);
@@ -8113,7 +10014,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8113
10014
  }
8114
10015
  }
8115
10016
  } else {
8116
- try { worker.terminate(); } catch (_) {}
10017
+ try { worker.terminate(); } catch (err) { _hostLogger.debug('worker.terminate failed', err); }
8117
10018
  }
8118
10019
  }
8119
10020
 
@@ -8301,12 +10202,23 @@ if (typeof module !== 'undefined' && module.exports) {
8301
10202
  })(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
8302
10203
  'use strict';
8303
10204
 
10205
+ const _shellLogger = (root && root.CodeLabLogger && typeof root.CodeLabLogger.createLogger === 'function')
10206
+ ? root.CodeLabLogger.createLogger()
10207
+ : {
10208
+ debug() {},
10209
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
10210
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
10211
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
10212
+ };
10213
+
8304
10214
  function getRuntimeModule() {
8305
10215
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
8306
10216
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
8307
10217
  try {
8308
10218
  if (typeof require !== 'undefined') return require('./runtime.js');
8309
- } catch (_) {}
10219
+ } catch (err) {
10220
+ _shellLogger.debug('Optional ./runtime.js require skipped in shell.', err);
10221
+ }
8310
10222
  return null;
8311
10223
  }
8312
10224
 
@@ -8898,7 +10810,9 @@ if (typeof module !== 'undefined' && module.exports) {
8898
10810
  if (typeof vfs.statSync === 'function') {
8899
10811
  isDir = vfs.statSync(full).isDirectory();
8900
10812
  }
8901
- } catch (_) {}
10813
+ } catch (err) {
10814
+ _shellLogger.debug('Glob statSync failed.', full, err);
10815
+ }
8902
10816
 
8903
10817
  if (isDir) {
8904
10818
  traverse(full, rel);
@@ -10220,7 +12134,9 @@ if (typeof module !== 'undefined' && module.exports) {
10220
12134
  : name;
10221
12135
  try {
10222
12136
  snap[rel] = String(vfs.readFileSync(full, 'utf8'));
10223
- } catch (_) {}
12137
+ } catch (err) {
12138
+ _shellLogger.debug('Skipped unreadable VFS file in snapshot.', full, err);
12139
+ }
10224
12140
  }
10225
12141
  }
10226
12142
  }
@@ -10324,8 +12240,9 @@ if (typeof module !== 'undefined' && module.exports) {
10324
12240
  }
10325
12241
  }
10326
12242
  }
10327
- } catch (_) {
12243
+ } catch (err) {
10328
12244
  // Network or rate limit error on api.github.com; proceed to Strategy B
12245
+ _shellLogger.debug('GitHub REST API tree fetch failed; falling back to jsDelivr.', err);
10329
12246
  }
10330
12247
 
10331
12248
  // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
@@ -10352,7 +12269,9 @@ if (typeof module !== 'undefined' && module.exports) {
10352
12269
  }
10353
12270
  }
10354
12271
  }
10355
- } catch (_) {}
12272
+ } catch (err) {
12273
+ _shellLogger.debug('jsDelivr flat tree fetch failed.', err);
12274
+ }
10356
12275
  }
10357
12276
 
10358
12277
  if (repoNotFound || !rawTreeEntries) {
@@ -10500,7 +12419,9 @@ if (typeof module !== 'undefined' && module.exports) {
10500
12419
  }));
10501
12420
  }
10502
12421
  }
10503
- } catch (_) {}
12422
+ } catch (err) {
12423
+ _shellLogger.debug('Optional commit history fetch skipped.', err);
12424
+ }
10504
12425
 
10505
12426
  if (commits.length === 0) {
10506
12427
  commits = [
@@ -10566,7 +12487,9 @@ if (typeof module !== 'undefined' && module.exports) {
10566
12487
  try {
10567
12488
  const parsed = JSON.parse(vfs.readFileSync(p, 'utf8'));
10568
12489
  return { path: p, data: parsed };
10569
- } catch (_) {}
12490
+ } catch (err) {
12491
+ _shellLogger.warn(`Invalid JSON in ${p}; falling back to default package metadata.`, err);
12492
+ }
10570
12493
  }
10571
12494
  return { path: p, data: { name: 'app', dependencies: {}, devDependencies: {}, scripts: {} } };
10572
12495
  }
@@ -10607,13 +12530,20 @@ if (typeof module !== 'undefined' && module.exports) {
10607
12530
  vfs.rmdirSync(dirPath);
10608
12531
  }
10609
12532
  if (typeof emitMutation === 'function') emitMutation('delete', dirPath);
10610
- } catch (_) {}
12533
+ } catch (err) {
12534
+ _shellLogger.debug('removeDirRecursive failed.', dirPath, err);
12535
+ }
10611
12536
  }
10612
12537
 
10613
12538
  // ---------------------------------------------------------------------------
10614
12539
  // Real npm package installation via the jsDelivr CDN
10615
12540
  // ---------------------------------------------------------------------------
10616
12541
  const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
12542
+ const CDN_NPM_BASES = [
12543
+ 'https://cdn.jsdelivr.net/npm',
12544
+ 'https://unpkg.com',
12545
+ 'https://esm.sh'
12546
+ ];
10617
12547
 
10618
12548
  // Minimal offline registry, used only when the CDN is unreachable so common
10619
12549
  // demos still resolve without network access.
@@ -10759,16 +12689,23 @@ if (typeof module !== 'undefined' && module.exports) {
10759
12689
  }
10760
12690
 
10761
12691
  async function resolvePackageMetadata(fetchImpl, name, range) {
10762
- const urls = range
10763
- ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
10764
- : [`${CDN_NPM_BASE}/${name}/package.json`];
10765
- for (const url of urls) {
10766
- const text = await fetchTextFromCdn(fetchImpl, url);
10767
- if (!text) continue;
10768
- try {
10769
- const parsed = JSON.parse(text);
10770
- if (parsed && parsed.version) return parsed;
10771
- } catch (_) {}
12692
+ for (const base of CDN_NPM_BASES) {
12693
+ const urls = range
12694
+ ? [`${base}/${name}@${range}/package.json`, `${base}/${name}/package.json`]
12695
+ : [`${base}/${name}/package.json`];
12696
+ for (const url of urls) {
12697
+ const text = await fetchTextFromCdn(fetchImpl, url);
12698
+ if (!text) continue;
12699
+ try {
12700
+ const parsed = JSON.parse(text);
12701
+ if (parsed && parsed.version) {
12702
+ parsed._resolvedCdnBase = base;
12703
+ return parsed;
12704
+ }
12705
+ } catch (err) {
12706
+ _shellLogger.debug('Invalid package.json metadata from CDN.', url, err);
12707
+ }
12708
+ }
10772
12709
  }
10773
12710
  return null;
10774
12711
  }
@@ -10786,6 +12723,7 @@ if (typeof module !== 'undefined' && module.exports) {
10786
12723
  return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
10787
12724
  }
10788
12725
 
12726
+ const activeCdnBase = meta._resolvedCdnBase || CDN_NPM_BASE;
10789
12727
  const version = meta.version;
10790
12728
  const key = `${name}@${version}`;
10791
12729
  if (seen.has(key)) {
@@ -10833,7 +12771,7 @@ if (typeof module !== 'undefined' && module.exports) {
10833
12771
  frontier = [];
10834
12772
  if (batch.length === 0) break;
10835
12773
  const texts = await Promise.all(
10836
- batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
12774
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/${rel}`))
10837
12775
  );
10838
12776
  for (let idx = 0; idx < batch.length; idx++) {
10839
12777
  const rel = batch[idx];
@@ -10857,7 +12795,7 @@ if (typeof module !== 'undefined' && module.exports) {
10857
12795
  }
10858
12796
  // The declared entry may be missing on the CDN; fall back to index.js.
10859
12797
  if (!files.some(f => f.rel === entry)) {
10860
- const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
12798
+ const idxText = await fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/index.js`);
10861
12799
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10862
12800
  }
10863
12801
 
@@ -10904,7 +12842,9 @@ if (typeof module !== 'undefined' && module.exports) {
10904
12842
  // directory target would otherwise raise EISDIR).
10905
12843
  try {
10906
12844
  if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
10907
- } catch (_) {}
12845
+ } catch (err) {
12846
+ _shellLogger.debug('Package install statSync check skipped.', full, err);
12847
+ }
10908
12848
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10909
12849
  ctx.vfs.writeFileSync(full, f.content);
10910
12850
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -10982,6 +12922,32 @@ if (typeof module !== 'undefined' && module.exports) {
10982
12922
  pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
10983
12923
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10984
12924
 
12925
+ // Also maintain package-lock.json in the same directory for deterministic lockfile verification
12926
+ try {
12927
+ const lockPath = PosixPath.join(PosixPath.dirname(pkgPath), 'package-lock.json');
12928
+ let lockData = { name: pkgData.name || 'workspace', version: pkgData.version || '1.0.0', lockfileVersion: 3, packages: {} };
12929
+ if (ctx.vfs.existsSync(lockPath)) {
12930
+ const rawLock = String(ctx.vfs.readFileSync(lockPath, 'utf8') || '');
12931
+ const parsedLock = JSON.parse(rawLock);
12932
+ if (parsedLock && typeof parsedLock === 'object') {
12933
+ lockData = parsedLock;
12934
+ if (!lockData.packages || typeof lockData.packages !== 'object') lockData.packages = {};
12935
+ }
12936
+ }
12937
+ for (const inst of installed) {
12938
+ if (inst && inst.name) {
12939
+ lockData.packages[`node_modules/${inst.name}`] = {
12940
+ version: inst.version || '1.0.0',
12941
+ resolved: `${CDN_NPM_BASE}/${inst.name}@${inst.version || '1.0.0'}`
12942
+ };
12943
+ }
12944
+ }
12945
+ ctx.vfs.writeFileSync(lockPath, JSON.stringify(lockData, null, 2) + '\n');
12946
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('modify', lockPath);
12947
+ } catch (err) {
12948
+ _shellLogger.debug('Could not write package-lock.json during installPackage.', err);
12949
+ }
12950
+
10985
12951
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
10986
12952
  }
10987
12953
 
@@ -11179,7 +13145,9 @@ if (typeof module !== 'undefined' && module.exports) {
11179
13145
  const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
11180
13146
  if (parsed && parsed.version) return parsed.version;
11181
13147
  }
11182
- } catch (_) {}
13148
+ } catch (err) {
13149
+ _shellLogger.debug('Could not read installed module package.json.', pkgName, err);
13150
+ }
11183
13151
  try {
11184
13152
  for (const dir of [rootDir, '/workspace']) {
11185
13153
  const pkgPath = PosixPath.join(dir, 'package.json');
@@ -11188,7 +13156,9 @@ if (typeof module !== 'undefined' && module.exports) {
11188
13156
  const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
11189
13157
  if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
11190
13158
  }
11191
- } catch (_) {}
13159
+ } catch (err) {
13160
+ _shellLogger.debug('Could not read workspace package.json for version resolution.', pkgName, err);
13161
+ }
11192
13162
  return 'latest';
11193
13163
  }
11194
13164
 
@@ -11211,10 +13181,10 @@ if (typeof module !== 'undefined' && module.exports) {
11211
13181
  return imports;
11212
13182
  }
11213
13183
 
11214
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
11215
- const scripts = [];
13184
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
13185
+ const files = [];
11216
13186
  const walk = (dir, depth) => {
11217
- if (depth > 8 || scripts.length >= maxFiles) return;
13187
+ if (depth > 8 || files.length >= maxFiles) return;
11218
13188
  let entries = [];
11219
13189
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
11220
13190
  for (const name of entries) {
@@ -11225,13 +13195,23 @@ if (typeof module !== 'undefined' && module.exports) {
11225
13195
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
11226
13196
  if (dirFlag) {
11227
13197
  walk(full, depth + 1);
11228
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
11229
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
13198
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
13199
+ try {
13200
+ const content = vfs.readFileSync(full, 'utf8');
13201
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
13202
+ files.push({ full, rel, content });
13203
+ } catch (err) {
13204
+ _shellLogger.debug('Preview script read skipped.', full, err);
13205
+ }
11230
13206
  }
11231
13207
  }
11232
13208
  };
11233
13209
  walk(rootDir, 0);
11234
- return scripts;
13210
+ return files;
13211
+ }
13212
+
13213
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
13214
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
11235
13215
  }
11236
13216
 
11237
13217
  function injectPreviewExtras(html, importMap) {
@@ -11256,12 +13236,6 @@ if (typeof module !== 'undefined' && module.exports) {
11256
13236
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
11257
13237
  while (taken.has(port)) port++;
11258
13238
 
11259
- const specifiers = new Set();
11260
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
11261
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
11262
- }
11263
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
11264
-
11265
13239
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
11266
13240
  const isDir = (p) => {
11267
13241
  try {
@@ -11269,11 +13243,112 @@ if (typeof module !== 'undefined' && module.exports) {
11269
13243
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
11270
13244
  } catch (_) { return false; }
11271
13245
  };
13246
+ const isFile = (p) => exists(p) && !isDir(p);
11272
13247
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
11273
13248
 
13249
+ const resolveLocalTarget = (baseDir, rawSpec) => {
13250
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
13251
+ const clean = rawSpec.split(/[?#]/)[0].trim();
13252
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
13253
+ const candidateBase = clean.startsWith('/')
13254
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
13255
+ : PosixPath.join(baseDir, clean);
13256
+ if (isFile(candidateBase)) return candidateBase;
13257
+ const cands = [
13258
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
13259
+ candidateBase + '.mjs', candidateBase + '.cjs',
13260
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
13261
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
13262
+ ];
13263
+ for (const c of cands) {
13264
+ if (isFile(c)) return c;
13265
+ }
13266
+ return null;
13267
+ };
13268
+
13269
+ const toLocalImportKey = (fullPath) => {
13270
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
13271
+ return `@codelab-local/${rel}`;
13272
+ };
13273
+
13274
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
13275
+ let out = code;
13276
+ try {
13277
+ const rm = getRuntimeModule();
13278
+ if (rm && typeof rm.transpileForBrowser === 'function') {
13279
+ out = rm.transpileForBrowser(out, sourcePath);
13280
+ }
13281
+ } catch (err) {
13282
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
13283
+ }
13284
+ const fromDir = PosixPath.dirname(sourcePath);
13285
+ const rewriteSpec = (spec) => {
13286
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
13287
+ const resolved = resolveLocalTarget(fromDir, spec);
13288
+ return resolved ? toLocalImportKey(resolved) : spec;
13289
+ };
13290
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13291
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13292
+ return out;
13293
+ };
13294
+
13295
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
13296
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
13297
+ const specifiers = new Set();
13298
+ for (const f of scriptFiles) {
13299
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
13300
+ }
13301
+ // Also scan inline module scripts in HTML for bare specifiers
13302
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
13303
+ let inlineMatch;
13304
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
13305
+ if (inlineMatch[1]) {
13306
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
13307
+ }
13308
+ }
13309
+
13310
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
13311
+ for (const f of scriptFiles) {
13312
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
13313
+ const key = toLocalImportKey(f.full);
13314
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
13315
+ }
13316
+
13317
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
13318
+ let transformedHtml = htmlBody;
13319
+
13320
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
13321
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
13322
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
13323
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
13324
+ if (!hrefMatch) return fullTag;
13325
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
13326
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
13327
+ const cssContent = readText(cssTarget);
13328
+ if (cssContent === null) return fullTag;
13329
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
13330
+ });
13331
+
13332
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
13333
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
13334
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
13335
+ if (!srcMatch) return fullTag;
13336
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
13337
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
13338
+ const rawScript = readText(scriptTarget);
13339
+ if (rawScript === null) return fullTag;
13340
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
13341
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
13342
+ const typeAttr = isMod ? ' type="module"' : '';
13343
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
13344
+ });
13345
+
13346
+ return injectPreviewExtras(transformedHtml, importMap);
13347
+ };
13348
+
11274
13349
  const handler = async (request) => {
11275
13350
  let pathname = '/';
11276
- try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
13351
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
11277
13352
  const rel = pathname.replace(/^\/+/, '');
11278
13353
  let target = PosixPath.join(rootDir, rel);
11279
13354
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
@@ -11305,14 +13380,16 @@ if (typeof module !== 'undefined' && module.exports) {
11305
13380
  let body = readText(target);
11306
13381
  if (body === null) body = '';
11307
13382
  if (/\.html?$/i.test(target)) {
11308
- body = injectPreviewExtras(body, importMap);
13383
+ body = buildHtmlPreviewResponse(body, target);
11309
13384
  } else if (isPreviewScriptPath(target)) {
11310
13385
  try {
11311
13386
  const rm = getRuntimeModule();
11312
13387
  if (rm && typeof rm.transpileForBrowser === 'function') {
11313
13388
  body = rm.transpileForBrowser(body, target);
11314
13389
  }
11315
- } catch (_) {}
13390
+ } catch (err) {
13391
+ _shellLogger.warn(`Preview script transpilation failed for ${target}.`, err);
13392
+ }
11316
13393
  }
11317
13394
 
11318
13395
  return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
@@ -11320,7 +13397,7 @@ if (typeof module !== 'undefined' && module.exports) {
11320
13397
 
11321
13398
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
11322
13399
  return portTable.registerServer(port, {
11323
- server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
13400
+ server: { close() { try { portTable.unregisterServer(port); } catch (err) { _shellLogger.debug('Preview server unregister failed.', port, err); } } },
11324
13401
  fetch: handler,
11325
13402
  name: 'code-lab-serve',
11326
13403
  pid,
@@ -11433,7 +13510,9 @@ if (typeof module !== 'undefined' && module.exports) {
11433
13510
  let isDir = false;
11434
13511
  try {
11435
13512
  isDir = ctx.vfs.statSync(resolved).isDirectory();
11436
- } catch (_) {}
13513
+ } catch (err) {
13514
+ _shellLogger.debug('cd statSync failed.', resolved, err);
13515
+ }
11437
13516
 
11438
13517
  if (!isDir) {
11439
13518
  return { code: 1, stdout: '', stderr: `cd: ${target}: Not a directory\n` };
@@ -11533,7 +13612,9 @@ if (typeof module !== 'undefined' && module.exports) {
11533
13612
  isDirectory = st.isDirectory();
11534
13613
  size = st.size;
11535
13614
  mtimeMs = st.mtimeMs || Date.now();
11536
- } catch (_) {}
13615
+ } catch (err) {
13616
+ _shellLogger.debug('ls statSync skipped.', itemPath, err);
13617
+ }
11537
13618
  return { name, isDirectory, size, mtimeMs, absPath: itemPath };
11538
13619
  });
11539
13620
 
@@ -11953,7 +14034,9 @@ if (typeof module !== 'undefined' && module.exports) {
11953
14034
  if (st.isDirectory()) walk(full);
11954
14035
  else targets.push(full);
11955
14036
  }
11956
- } catch (_) {}
14037
+ } catch (err) {
14038
+ _shellLogger.debug('grep directory walk skipped.', dir, err);
14039
+ }
11957
14040
  }
11958
14041
  if (ctx.vfs.existsSync(absRoot)) {
11959
14042
  const st = ctx.vfs.statSync(absRoot);
@@ -12077,7 +14160,9 @@ if (typeof module !== 'undefined' && module.exports) {
12077
14160
  let isDir = false;
12078
14161
  try {
12079
14162
  isDir = ctx.vfs.statSync(full).isDirectory();
12080
- } catch (_) {}
14163
+ } catch (err) {
14164
+ _shellLogger.debug('find statSync skipped.', full, err);
14165
+ }
12081
14166
 
12082
14167
  const relPath = root === '.'
12083
14168
  ? './' + full.replace(absRoot.endsWith('/') ? absRoot : absRoot + '/', '')
@@ -12096,7 +14181,7 @@ if (typeof module !== 'undefined' && module.exports) {
12096
14181
  // Root itself check
12097
14182
  if (ctx.vfs.existsSync(absRoot)) {
12098
14183
  let isDir = false;
12099
- try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (_) {}
14184
+ try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (err) { _shellLogger.debug('find root statSync skipped.', absRoot, err); }
12100
14185
  if (!typeFilter || (typeFilter === 'd' && isDir) || (typeFilter === 'f' && !isDir)) {
12101
14186
  if (!nameRegex || nameRegex.test(PosixPath.basename(root))) {
12102
14187
  results.push(root);
@@ -13008,7 +15093,7 @@ if (typeof module !== 'undefined' && module.exports) {
13008
15093
  const isLast = i === entries.length - 1;
13009
15094
  const full = dirPath === '/' ? '/' + entry : dirPath + '/' + entry;
13010
15095
  let isDir = false;
13011
- try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (_) {}
15096
+ try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (err) { _shellLogger.debug('tree statSync skipped.', full, err); }
13012
15097
 
13013
15098
  stdout += `${prefix}${isLast ? '└── ' : '├── '}${entry}\n`;
13014
15099
 
@@ -13236,10 +15321,10 @@ if (typeof module !== 'undefined' && module.exports) {
13236
15321
  for (const s of ctx.shell.portTable.listServers()) {
13237
15322
  if (s.pid !== undefined && String(s.pid) === String(pid)) {
13238
15323
  if (s.server && typeof s.server.close === 'function') {
13239
- try { s.server.close(); } catch (_) {}
15324
+ try { s.server.close(); } catch (err) { _shellLogger.debug('kill server.close failed.', err); }
13240
15325
  }
13241
15326
  if (typeof s.stop === 'function') {
13242
- try { s.stop(); } catch (_) {}
15327
+ try { s.stop(); } catch (err) { _shellLogger.debug('kill server.stop failed.', err); }
13243
15328
  }
13244
15329
  ctx.shell.portTable.unregisterServer(s.port);
13245
15330
  killedPort = true;
@@ -15570,6 +17655,16 @@ if (typeof module !== 'undefined' && module.exports) {
15570
17655
  })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
15571
17656
  'use strict';
15572
17657
 
17658
+ const _termRoot = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
17659
+ const _terminalLogger = (_termRoot && _termRoot.CodeLabLogger && typeof _termRoot.CodeLabLogger.createLogger === 'function')
17660
+ ? _termRoot.CodeLabLogger.createLogger()
17661
+ : {
17662
+ debug() {},
17663
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
17664
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
17665
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
17666
+ };
17667
+
15573
17668
  const ANSI_CODE_MAP = {
15574
17669
  1: 'cl-ansi-bold',
15575
17670
  2: 'cl-ansi-dim',
@@ -16110,7 +18205,7 @@ if (typeof module !== 'undefined' && module.exports) {
16110
18205
  if (!this.container || typeof this.container.querySelector !== 'function') return;
16111
18206
  const input = this.container.querySelector('#cl-repl-input');
16112
18207
  if (input && typeof input.focus === 'function') {
16113
- try { input.focus(); } catch (_) {}
18208
+ try { input.focus(); } catch (err) { _terminalLogger.debug('Terminal input focus skipped.', err); }
16114
18209
  }
16115
18210
  }
16116
18211
 
@@ -16134,9 +18229,9 @@ if (typeof module !== 'undefined' && module.exports) {
16134
18229
  }
16135
18230
  for (const entry of this._listeners) {
16136
18231
  if (typeof entry === 'function') {
16137
- try { entry(); } catch (_) {}
18232
+ try { entry(); } catch (err) { _terminalLogger.debug('Terminal listener cleanup callback failed.', err); }
16138
18233
  } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
16139
- try { entry.target.removeEventListener(entry.type, entry.handler); } catch (_) {}
18234
+ try { entry.target.removeEventListener(entry.type, entry.handler); } catch (err) { _terminalLogger.debug('Terminal removeEventListener failed.', err); }
16140
18235
  }
16141
18236
  }
16142
18237
  this._listeners = [];
@@ -16205,7 +18300,9 @@ if (typeof module !== 'undefined' && module.exports) {
16205
18300
  try {
16206
18301
  const res = this.onKey(e);
16207
18302
  if (res === false) return;
16208
- } catch (_) {}
18303
+ } catch (err) {
18304
+ _terminalLogger.warn('Terminal onKey callback threw.', err);
18305
+ }
16209
18306
  }
16210
18307
 
16211
18308
  const key = e.key;
@@ -16358,7 +18455,7 @@ if (typeof module !== 'undefined' && module.exports) {
16358
18455
  this.replMode = false;
16359
18456
  }
16360
18457
  if (this.onInterrupt) {
16361
- try { this.onInterrupt(); } catch (_) {}
18458
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
16362
18459
  }
16363
18460
  this.render();
16364
18461
  return;
@@ -16559,7 +18656,9 @@ if (typeof module !== 'undefined' && module.exports) {
16559
18656
  if (typeof nextInput.setSelectionRange === 'function') {
16560
18657
  nextInput.setSelectionRange(this.cursor, this.cursor);
16561
18658
  }
16562
- } catch (_) {}
18659
+ } catch (err) {
18660
+ _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
18661
+ }
16563
18662
  }
16564
18663
  }
16565
18664
  }
@@ -16597,13 +18696,26 @@ if (typeof module !== 'undefined' && module.exports) {
16597
18696
  (function (root) {
16598
18697
  'use strict';
16599
18698
 
16600
- let terminalModule = null;
16601
- let shellModule = null;
16602
- let runtimeModule = null;
18699
+ const _sharedLoggerMod = (typeof CodeLabLogger !== 'undefined' && CodeLabLogger) ||
18700
+ (root && root.CodeLabLogger) ||
18701
+ null;
18702
+ const _bootDebug = (_sharedLoggerMod && _sharedLoggerMod.DEFAULT_LOGGER && typeof _sharedLoggerMod.DEFAULT_LOGGER.debug === 'function')
18703
+ ? (...args) => _sharedLoggerMod.DEFAULT_LOGGER.debug(...args)
18704
+ : () => {};
18705
+
18706
+ let terminalModule = (root && root.CodeLabTerminal) || null;
18707
+ let shellModule = (root && root.CodeLabShell) || null;
18708
+ let runtimeModule = (root && root.CodeLabRuntime) || null;
16603
18709
  if (typeof require === 'function') {
16604
- try { terminalModule = require('./terminal.js'); } catch (_) {}
16605
- try { shellModule = require('./shell.js'); } catch (_) {}
16606
- try { runtimeModule = require('./runtime.js'); } catch (_) {}
18710
+ if (!terminalModule) {
18711
+ try { terminalModule = require('./terminal.js'); } catch (err) { _bootDebug('optional terminal.js require failed', err); }
18712
+ }
18713
+ if (!shellModule) {
18714
+ try { shellModule = require('./shell.js'); } catch (err) { _bootDebug('optional shell.js require failed', err); }
18715
+ }
18716
+ if (!runtimeModule) {
18717
+ try { runtimeModule = require('./runtime.js'); } catch (err) { _bootDebug('optional runtime.js require failed', err); }
18718
+ }
16607
18719
  }
16608
18720
  const CodeLabTerminal = (root && root.CodeLabTerminal) || terminalModule || {};
16609
18721
  const CodeLabShell = (root && root.CodeLabShell) || shellModule || {};
@@ -16634,7 +18746,7 @@ if (typeof module !== 'undefined' && module.exports) {
16634
18746
 
16635
18747
  // The bundler rewrites this literal from package.json at build time. Keeping
16636
18748
  // the fallback in sync lets tests require src/workbench.js directly.
16637
- const CODELAB_VERSION = '0.1.7';
18749
+ const CODELAB_VERSION = '0.1.9';
16638
18750
 
16639
18751
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
16640
18752
  const NODE_AMBIENT_DTS = `
@@ -16962,7 +19074,14 @@ declare module 'bun:sqlite' {
16962
19074
  }
16963
19075
  `;
16964
19076
 
19077
+ const _sharedHtmlMod = (typeof CodeLabHtml !== 'undefined' && CodeLabHtml) ||
19078
+ (root && root.CodeLabHtml) ||
19079
+ null;
19080
+
16965
19081
  function escapeHtml(str) {
19082
+ if (_sharedHtmlMod && typeof _sharedHtmlMod.escapeHtml === 'function') {
19083
+ return _sharedHtmlMod.escapeHtml(str);
19084
+ }
16966
19085
  if (str == null) return '';
16967
19086
  return String(str)
16968
19087
  .replace(/&/g, '&amp;')
@@ -16972,6 +19091,18 @@ declare module 'bun:sqlite' {
16972
19091
  .replace(/'/g, '&#39;');
16973
19092
  }
16974
19093
 
19094
+ const isSafeHtml = (_sharedHtmlMod && _sharedHtmlMod.isSafeHtml) || ((v) => Boolean(v && typeof v === 'object' && typeof v.__html === 'string'));
19095
+ const raw = (_sharedHtmlMod && _sharedHtmlMod.raw) || ((trusted) => ({ __html: String(trusted), toString() { return this.__html; } }));
19096
+ const html = (_sharedHtmlMod && _sharedHtmlMod.html) || ((strings, ...values) => {
19097
+ let out = strings[0] || '';
19098
+ for (let i = 0; i < values.length; i++) {
19099
+ const val = values[i];
19100
+ out += (val == null || val === false) ? '' : (isSafeHtml(val) ? val.__html : escapeHtml(val));
19101
+ out += strings[i + 1] || '';
19102
+ }
19103
+ return raw(out);
19104
+ });
19105
+
16975
19106
  // Schemes that may appear in a rendered href. Everything else
16976
19107
  // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
16977
19108
  const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
@@ -17190,11 +19321,11 @@ declare module 'bun:sqlite' {
17190
19321
  if (!str) return '';
17191
19322
  let text = String(str);
17192
19323
 
17193
- // Markdown Links: [label](url "title") or [label](url)
17194
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
19324
+ // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
19325
+ text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
17195
19326
  const cleanUrl = sanitizeUrl(url);
17196
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
17197
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
19327
+ const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
19328
+ return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
17198
19329
  });
17199
19330
 
17200
19331
  // Strikethrough: ~~del~~
@@ -17721,23 +19852,24 @@ declare module 'bun:sqlite' {
17721
19852
  let _workbenchInstanceCounter = 0;
17722
19853
  const _fallbackStorage = new Map();
17723
19854
 
17724
- // CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
17725
- // in src/preview-sw.js — keep both copies in sync.
17726
- const PREVIEW_CSP = [
17727
- "default-src 'self' data: blob:",
17728
- "base-uri 'self'",
17729
- "object-src 'none'",
17730
- "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
17731
- "style-src 'self' 'unsafe-inline'",
17732
- "img-src 'self' data: blob:",
17733
- "font-src 'self' data:",
17734
- "connect-src 'self' data: blob:",
17735
- "media-src 'self' data: blob:",
17736
- "worker-src 'self' blob:",
17737
- "frame-src 'self' data: blob:",
17738
- "form-action 'self'",
17739
- "frame-ancestors 'self'"
17740
- ].join('; ');
19855
+ // Preview CSP, storage shims and violation reporting live in src/csp.ts.
19856
+ // The build embeds that module in this bundle (and in dist/preview-sw.js), so
19857
+ // there is exactly one policy implementation shared by both sides.
19858
+ const PreviewCsp = (typeof CodeLabCsp !== 'undefined' && CodeLabCsp) ||
19859
+ (root && root.CodeLabCsp) ||
19860
+ null;
19861
+
19862
+ function normalizePreviewCspOption(raw) {
19863
+ if (PreviewCsp && typeof PreviewCsp.normalizePreviewCspConfig === 'function') {
19864
+ return PreviewCsp.normalizePreviewCspConfig(raw);
19865
+ }
19866
+ return { mode: 'balanced', allow: {} };
19867
+ }
19868
+
19869
+ // `previewOrigin` needs a relay page + service worker on that origin. Until
19870
+ // that ships, using it would silently *pretend* to isolate previews while the
19871
+ // iframe gets a 503 from a worker that has no clients on the preview origin.
19872
+ const PREVIEW_RELAY_AVAILABLE = false;
17741
19873
 
17742
19874
  function normalizePreviewOrigin(raw) {
17743
19875
  if (raw === null || raw === undefined || raw === '') return null;
@@ -17750,12 +19882,26 @@ declare module 'bun:sqlite' {
17750
19882
  }
17751
19883
  }
17752
19884
 
17753
- const LOG_PREFIX = '[code-lab]';
19885
+ const LOG_PREFIX = (_sharedLoggerMod && _sharedLoggerMod.LOG_PREFIX) || '[code-lab]';
19886
+ const CodeLabError = (_sharedLoggerMod && _sharedLoggerMod.CodeLabError) || class CodeLabError extends Error {
19887
+ constructor(code, message, options = {}) {
19888
+ super(message);
19889
+ this.name = 'CodeLabError';
19890
+ this.code = code || 'E_CODELAB';
19891
+ this.module = options.module || 'workbench';
19892
+ this.context = options.context || {};
19893
+ if (options.cause !== undefined) this.cause = options.cause;
19894
+ }
19895
+ };
19896
+ const isCodeLabError = (_sharedLoggerMod && _sharedLoggerMod.isCodeLabError) || ((value) => Boolean(value && typeof value === 'object' && value.name === 'CodeLabError' && typeof value.code === 'string'));
17754
19897
 
17755
19898
  // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
17756
19899
  // into their own telemetry; `options.debug` enables verbose output. Errors
17757
19900
  // are never silently discarded.
17758
19901
  function createLogger(options = {}) {
19902
+ if (_sharedLoggerMod && typeof _sharedLoggerMod.createLogger === 'function') {
19903
+ return _sharedLoggerMod.createLogger({ module: 'workbench', ...options });
19904
+ }
17759
19905
  const sink = options.logger;
17760
19906
  const debugEnabled = options.debug === true;
17761
19907
 
@@ -17765,8 +19911,9 @@ declare module 'bun:sqlite' {
17765
19911
  try {
17766
19912
  sink[level](...args);
17767
19913
  return;
17768
- } catch (_) {
17769
- // A broken host logger must not break the IDE; fall through.
19914
+ } catch (sinkErr) {
19915
+ const fallbackWarn = typeof console !== 'undefined' && typeof console.warn === 'function' ? console.warn : null;
19916
+ if (fallbackWarn) fallbackWarn(LOG_PREFIX, 'Host logger sink threw; falling back to console.', sinkErr);
17770
19917
  }
17771
19918
  }
17772
19919
  const fn = typeof console !== 'undefined' ? console[level] : null;
@@ -17798,7 +19945,7 @@ declare module 'bun:sqlite' {
17798
19945
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
17799
19946
  }
17800
19947
 
17801
- function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
19948
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER, onError = null) {
17802
19949
  const str = String(value);
17803
19950
  try {
17804
19951
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
@@ -17806,6 +19953,9 @@ declare module 'bun:sqlite' {
17806
19953
  return true;
17807
19954
  }
17808
19955
  } catch (err) {
19956
+ if (typeof onError === 'function') {
19957
+ onError(err);
19958
+ }
17809
19959
  if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
17810
19960
  if (!safeStorageSet._warnedKeys.has(key)) {
17811
19961
  safeStorageSet._warnedKeys.add(key);
@@ -17829,6 +19979,8 @@ declare module 'bun:sqlite' {
17829
19979
  this.options = options || {};
17830
19980
  this.logger = createLogger({ logger: options.logger, debug: options.debug });
17831
19981
  this._persistenceFailureReported = false;
19982
+ this.saveStatusState = 'saved';
19983
+ this.saveStatusError = null;
17832
19984
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
17833
19985
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
17834
19986
  this.title = options.title || this.labId;
@@ -17836,6 +19988,7 @@ declare module 'bun:sqlite' {
17836
19988
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
17837
19989
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
17838
19990
  this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
19991
+ this.previewCsp = normalizePreviewCspOption(options.previewCsp);
17839
19992
  this._previewIsolationWarned = false;
17840
19993
  if (options.previewOrigin && !this.previewOrigin) {
17841
19994
  this.logger.warn(
@@ -17912,14 +20065,22 @@ declare module 'bun:sqlite' {
17912
20065
  path: '/',
17913
20066
  url: '',
17914
20067
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
20068
+ dockMode: (options && options.previewDock === 'split') ? 'split' : 'bottom', // 'bottom' | 'split'
20069
+ maximized: false,
20070
+ consoleOpen: false,
20071
+ consoleLogs: [],
17915
20072
  loading: false,
17916
20073
  error: null,
17917
- srcdoc: ''
20074
+ srcdoc: '',
20075
+ violations: []
17918
20076
  };
17919
20077
  this.previewHistory = [];
17920
20078
  this.previewHistoryIdx = -1;
17921
20079
  this._previewSwReady = false;
17922
20080
  this._previewSwRegistration = null;
20081
+ this._previewViolationHandler = null;
20082
+ this._swMessageHandler = null;
20083
+ this._beforeUnloadHandler = null;
17923
20084
  this._portToasts = new Map();
17924
20085
  this.isFullscreen = false;
17925
20086
  this.isRunning = false;
@@ -18019,7 +20180,9 @@ declare module 'bun:sqlite' {
18019
20180
  onCommand: (cmd) => this._handleReplCommand(cmd),
18020
20181
  onInterrupt: () => this._handleInterrupt()
18021
20182
  });
18022
- } catch (_) {}
20183
+ } catch (err) {
20184
+ this.logger.debug('PTY engine initialization skipped.', err);
20185
+ }
18023
20186
  }
18024
20187
 
18025
20188
  this.shell = null;
@@ -18045,7 +20208,7 @@ declare module 'bun:sqlite' {
18045
20208
  intoRoot: options.cloneIntoRoot !== false,
18046
20209
  branch: options.branch || undefined,
18047
20210
  fetchImpl: options.fetchImpl || undefined
18048
- }).catch(() => {});
20211
+ }).catch((err) => this.logger.warn('Initial cloneRepo failed.', err));
18049
20212
  }
18050
20213
  }
18051
20214
 
@@ -18070,7 +20233,9 @@ declare module 'bun:sqlite' {
18070
20233
  }
18071
20234
  });
18072
20235
  this._syncFilesToShellVfs();
18073
- } catch (_) {}
20236
+ } catch (err) {
20237
+ this.logger.debug('POSIX shell initialization skipped.', err);
20238
+ }
18074
20239
  }
18075
20240
  }
18076
20241
 
@@ -18096,7 +20261,9 @@ declare module 'bun:sqlite' {
18096
20261
  const u = new URL(fullUrl);
18097
20262
  parsedPort = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
18098
20263
  reqPath = u.pathname + (u.search || '');
18099
- } catch (_) {}
20264
+ } catch (err) {
20265
+ this.logger.debug('Could not parse portTable dispatch URL.', err);
20266
+ }
18100
20267
  const method = String((init && init.method) || 'GET').toUpperCase();
18101
20268
  try {
18102
20269
  const res = await origDispatch(url, init);
@@ -18108,7 +20275,9 @@ declare module 'bun:sqlite' {
18108
20275
  } else if (res && res.body !== undefined) {
18109
20276
  bodyText = String(res.body);
18110
20277
  }
18111
- } catch (_) {}
20278
+ } catch (err) {
20279
+ this.logger.debug('Could not read response body for HTTP trace.', err);
20280
+ }
18112
20281
  const responseHeaders = {};
18113
20282
  if (res && res.headers) {
18114
20283
  if (typeof res.headers.forEach === 'function') {
@@ -18120,7 +20289,9 @@ declare module 'bun:sqlite' {
18120
20289
  let formattedBody = bodyText;
18121
20290
  try {
18122
20291
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
18123
- } catch (_) {}
20292
+ } catch (err) {
20293
+ void err;
20294
+ }
18124
20295
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
18125
20296
  this.lastHttpTrace.push({
18126
20297
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -18169,7 +20340,9 @@ declare module 'bun:sqlite' {
18169
20340
  vfs.writeFileSync(absPath, String(content ?? ''));
18170
20341
  }
18171
20342
  }
18172
- } catch (_) {}
20343
+ } catch (err) {
20344
+ this.logger.debug('Could not sync files to shell VFS.', err);
20345
+ }
18173
20346
  }
18174
20347
 
18175
20348
  _emitEvent(name, detail) {
@@ -18191,7 +20364,9 @@ declare module 'bun:sqlite' {
18191
20364
  if (shortName !== fullName) {
18192
20365
  this.container.dispatchEvent(new CustomEvent(shortName, { detail, bubbles: true, composed: true }));
18193
20366
  }
18194
- } catch (_) {}
20367
+ } catch (err) {
20368
+ this.logger.debug(`CustomEvent dispatch for "${name}" failed.`, err);
20369
+ }
18195
20370
  }
18196
20371
 
18197
20372
  _resolvedTheme() {
@@ -18225,13 +20400,26 @@ declare module 'bun:sqlite' {
18225
20400
  }
18226
20401
  }
18227
20402
 
18228
- _reportPersistenceFailure() {
18229
- if (this._persistenceFailureReported) return;
20403
+ _reportPersistenceFailure(cause) {
20404
+ const error = isCodeLabError(cause)
20405
+ ? cause
20406
+ : new CodeLabError(
20407
+ 'E_SAVE',
20408
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.',
20409
+ { cause, recoverable: true, details: { labId: this.labId } }
20410
+ );
20411
+ this.saveStatusState = 'failed';
20412
+ this.saveStatusError = error;
20413
+ this._updateStatusBar();
20414
+ this._emitEvent('save-state', { status: 'failed', state: 'failed', labId: this.labId, error });
20415
+ if (this._persistenceFailureReported) return error;
18230
20416
  this._persistenceFailureReported = true;
18231
20417
  this.logger.warn(
18232
20418
  'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
18233
20419
  );
18234
- this._emitEvent('persistence-error', { labId: this.labId });
20420
+ this._emitEvent('persistence-error', { labId: this.labId, error });
20421
+ this._emitEvent('error', error);
20422
+ return error;
18235
20423
  }
18236
20424
 
18237
20425
  _saveState() {
@@ -18239,6 +20427,11 @@ declare module 'bun:sqlite' {
18239
20427
  const key = `${this.mode}:${this.lang}`;
18240
20428
  const customFiles = (this.savedState && this.savedState.customFiles) || {};
18241
20429
  customFiles[key] = { ...this.files };
20430
+ const hasSnapshot = Object.assign(
20431
+ {},
20432
+ (this.savedState && this.savedState.hasSnapshot) || {},
20433
+ { [key]: true }
20434
+ );
18242
20435
  const completedArr = Array.from(this.completedSteps);
18243
20436
  const state = {
18244
20437
  mode: this.mode,
@@ -18246,6 +20439,7 @@ declare module 'bun:sqlite' {
18246
20439
  activeStepIndex: this.activeStepIndex,
18247
20440
  completedSteps: completedArr,
18248
20441
  customFiles,
20442
+ hasSnapshot,
18249
20443
  openTabs: Array.isArray(this.openTabs) ? [...this.openTabs] : undefined,
18250
20444
  activeFile: this.activeFile,
18251
20445
  folders: Array.from(this.folders || []),
@@ -18255,22 +20449,49 @@ declare module 'bun:sqlite' {
18255
20449
  };
18256
20450
  this.savedState = state;
18257
20451
  if (this.options && this.options.persistState === false) {
20452
+ this.saveStatusState = 'saved';
20453
+ this.saveStatusError = null;
20454
+ this._updateStatusBar();
18258
20455
  return;
18259
20456
  }
20457
+ this._emitEvent('save-state', { status: 'saving', state: 'saving', labId: this.labId });
18260
20458
  const serialized = JSON.stringify(state);
20459
+ safeStorageSet._lastError = null;
20460
+ const recordErr = (err) => { safeStorageSet._lastError = err; };
18261
20461
  const persisted = [
18262
- safeStorageSet(this._storageKey(), serialized, this.logger),
20462
+ safeStorageSet(this._storageKey(), serialized, this.logger, recordErr),
18263
20463
  // Sync with host app sidebar & build overview progress trackers
18264
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
18265
- safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
20464
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
20465
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
18266
20466
  ];
18267
- if (persisted.includes(false)) this._reportPersistenceFailure();
20467
+ if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
20468
+ try {
20469
+ if (!this._idbStorage) {
20470
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
20471
+ }
20472
+ if (this._idbStorage && typeof this._idbStorage.save === 'function') {
20473
+ Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
20474
+ this.logger.debug('Async WorkspaceStorage save skipped.', err);
20475
+ });
20476
+ }
20477
+ } catch (err) {
20478
+ this.logger.debug('WorkspaceStorage initialization skipped.', err);
20479
+ }
20480
+ }
20481
+ if (persisted.includes(false)) {
20482
+ this._reportPersistenceFailure(safeStorageSet._lastError);
20483
+ } else {
20484
+ this.saveStatusState = 'saved';
20485
+ this.saveStatusError = null;
20486
+ this._updateStatusBar();
20487
+ this._emitEvent('save-state', { status: 'saved', state: 'saved', labId: this.labId });
20488
+ }
18268
20489
  } catch (err) {
18269
20490
  this.logger.error(
18270
20491
  'Failed to save workbench state.',
18271
20492
  err && err.message ? err.message : err
18272
20493
  );
18273
- this._reportPersistenceFailure();
20494
+ this._reportPersistenceFailure(err);
18274
20495
  }
18275
20496
  }
18276
20497
 
@@ -18293,7 +20514,9 @@ declare module 'bun:sqlite' {
18293
20514
  for (const [dep, ver] of Object.entries(pkgJsonDeps)) {
18294
20515
  npmSet.add(ver && ver !== '*' && ver !== 'latest' ? `${dep}@${String(ver).replace(/^[\^~]/, '')}` : dep);
18295
20516
  }
18296
- } catch (_) {}
20517
+ } catch (err) {
20518
+ this.logger.debug('Malformed package.json while detecting dependencies.', err);
20519
+ }
18297
20520
  }
18298
20521
 
18299
20522
  const reqRe = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -18340,6 +20563,7 @@ declare module 'bun:sqlite' {
18340
20563
  const dotEl = this.container.querySelector('#cl-status-dot');
18341
20564
  const textEl = this.container.querySelector('#cl-status-text');
18342
20565
  const fileEl = this.container.querySelector('#cl-status-file');
20566
+ const saveEl = this.container.querySelector('#cl-status-save');
18343
20567
  const durEl = this.container.querySelector('#cl-status-duration');
18344
20568
  const curEl = this.container.querySelector('#cl-status-cursor');
18345
20569
  const langEl = this.container.querySelector('#cl-status-lang');
@@ -18351,6 +20575,24 @@ declare module 'bun:sqlite' {
18351
20575
  }
18352
20576
  if (textEl) textEl.textContent = this.runtimeStatusText;
18353
20577
  if (fileEl) fileEl.textContent = this.activeFile || 'workspace';
20578
+ if (saveEl) {
20579
+ if (this.saveStatusState === 'failed') {
20580
+ saveEl.style.display = 'inline-flex';
20581
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save is-failed';
20582
+ saveEl.textContent = '⚠ Save failed (session-only)';
20583
+ const reason = this.saveStatusError && this.saveStatusError.message
20584
+ ? this.saveStatusError.message
20585
+ : 'localStorage is unavailable or quota exceeded';
20586
+ saveEl.setAttribute('title', `State is stored in memory only: ${reason}`);
20587
+ saveEl.setAttribute('data-save-state', 'failed');
20588
+ } else {
20589
+ saveEl.style.display = 'none';
20590
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save';
20591
+ saveEl.textContent = '';
20592
+ saveEl.removeAttribute('title');
20593
+ saveEl.setAttribute('data-save-state', 'saved');
20594
+ }
20595
+ }
18354
20596
  if (durEl) {
18355
20597
  if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
18356
20598
  durEl.style.display = 'inline-flex';
@@ -18388,6 +20630,9 @@ declare module 'bun:sqlite' {
18388
20630
  const key = `${this.mode}:${this.lang}`;
18389
20631
  const saved = this.savedState.customFiles?.[key];
18390
20632
  const base = this._getBaseFilesForModeAndLang(this.mode, this.lang);
20633
+ if (this.savedState && this.savedState.hasSnapshot && this.savedState.hasSnapshot[key] && saved && typeof saved === 'object') {
20634
+ return { ...saved };
20635
+ }
18391
20636
  if (saved && Object.keys(saved).length > 0) {
18392
20637
  return { ...base, ...saved };
18393
20638
  }
@@ -18600,6 +20845,10 @@ declare module 'bun:sqlite' {
18600
20845
  <div class="codelab-empty-editor" id="cl-empty-editor" style="display:none"></div>
18601
20846
  </div>
18602
20847
  </div>
20848
+
20849
+ <!-- Right-Hand Split Web Preview Pane -->
20850
+ <div class="codelab-splitter-preview" id="cl-splitter-preview" role="separator" aria-orientation="vertical" title="Drag to resize web preview (double-click to reset)" style="display:none"></div>
20851
+ <div class="codelab-preview-split" id="cl-preview-split" aria-label="In-Browser Web Preview" style="display:none"></div>
18603
20852
  </div>
18604
20853
 
18605
20854
  <!-- Interactive Horizontal Splitter -->
@@ -18658,6 +20907,7 @@ declare module 'bun:sqlite' {
18658
20907
  </span>
18659
20908
  <span class="codelab-statusbar__sep">·</span>
18660
20909
  <span class="codelab-statusbar__item" id="cl-status-file">${escapeHtml(this.activeFile || 'workspace')}</span>
20910
+ <span class="codelab-statusbar__item codelab-statusbar__save" id="cl-status-save" data-save-state="saved" style="display:none"></span>
18661
20911
  </div>
18662
20912
  <div class="codelab-statusbar__right">
18663
20913
  <span class="codelab-statusbar__item" id="cl-status-duration" style="display:none"></span>
@@ -19912,7 +22162,9 @@ declare module 'bun:sqlite' {
19912
22162
  if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
19913
22163
  try {
19914
22164
  this.ptyEngine.writeStreamChunk(rawText, type);
19915
- } catch (_) {}
22165
+ } catch (err) {
22166
+ this.logger.debug('ptyEngine.writeStreamChunk failed.', err);
22167
+ }
19916
22168
  }
19917
22169
 
19918
22170
  this._activeStreamType = type;
@@ -20044,14 +22296,18 @@ declare module 'bun:sqlite' {
20044
22296
  if (this._activeCommandAbortController) {
20045
22297
  try {
20046
22298
  this._activeCommandAbortController.abort('SIGINT');
20047
- } catch (_) {}
22299
+ } catch (err) {
22300
+ this.logger.debug('AbortController.abort failed.', err);
22301
+ }
20048
22302
  this._activeCommandAbortController = null;
20049
22303
  }
20050
22304
 
20051
22305
  if (typeof root.CodeLabRuntime?.cancelWorkerExecution === 'function') {
20052
22306
  try {
20053
22307
  root.CodeLabRuntime.cancelWorkerExecution('SIGINT: Interrupted by user (Ctrl+C)', this.instanceId);
20054
- } catch (_) {}
22308
+ } catch (err) {
22309
+ this.logger.debug('cancelWorkerExecution failed.', err);
22310
+ }
20055
22311
  }
20056
22312
 
20057
22313
  this.isRunning = false;
@@ -20620,7 +22876,9 @@ declare module 'bun:sqlite' {
20620
22876
  try {
20621
22877
  const parsed = JSON.parse(responseBody);
20622
22878
  formattedBody = JSON.stringify(parsed, null, 2);
20623
- } catch (_) {}
22879
+ } catch (_) {
22880
+ formattedBody = responseBody;
22881
+ }
20624
22882
 
20625
22883
  const traceId = 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
20626
22884
  const traceItem = {
@@ -20693,7 +22951,9 @@ declare module 'bun:sqlite' {
20693
22951
  if (this.drawerTab === 'ports') this._renderDrawerBody();
20694
22952
  this._dismissPortToast(port);
20695
22953
  }));
20696
- } catch (_) {}
22954
+ } catch (err) {
22955
+ this.logger.warn('Failed to attach portTable event listeners.', err);
22956
+ }
20697
22957
  }
20698
22958
 
20699
22959
  _updatePortsPill() {
@@ -20767,16 +23027,55 @@ declare module 'bun:sqlite' {
20767
23027
  const url = (this.options && this.options.previewSwUrl) || 'preview-sw.js';
20768
23028
  try {
20769
23029
  const onMessage = (event) => this._handleServiceWorkerMessage(event);
23030
+ this._swMessageHandler = onMessage;
20770
23031
  if (typeof navigator.serviceWorker.addEventListener === 'function') {
20771
23032
  navigator.serviceWorker.addEventListener('message', onMessage);
20772
23033
  } else {
20773
23034
  navigator.serviceWorker.onmessage = onMessage;
20774
23035
  }
20775
23036
  navigator.serviceWorker.register(url, { scope: (this.options && this.options.previewSwScope) || './' })
20776
- .then((reg) => { this._previewSwRegistration = reg; this._previewSwReady = true; })
20777
- .catch(() => { this._previewSwReady = false; });
20778
- } catch (_) {
23037
+ .then((reg) => {
23038
+ this._previewSwRegistration = reg;
23039
+ this._previewSwReady = true;
23040
+ this._pushPreviewCsp(reg);
23041
+ })
23042
+ .catch((err) => {
23043
+ this._previewSwReady = false;
23044
+ this.logger.warn('Preview service worker registration failed; using the srcdoc fallback.', err);
23045
+ });
23046
+ } catch (err) {
20779
23047
  this._previewSwReady = false;
23048
+ this.logger.warn('Preview service worker is unavailable in this context.', err);
23049
+ }
23050
+ }
23051
+
23052
+ /**
23053
+ * The service worker cannot read workbench options, so the resolved policy
23054
+ * is pushed to it. Without this, `previewCsp: 'strict'` would only change
23055
+ * the srcdoc fallback and silently not the served previews.
23056
+ */
23057
+ _pushPreviewCsp(registration) {
23058
+ const policy = this._previewPolicy();
23059
+ const send = (worker) => {
23060
+ if (!worker || typeof worker.postMessage !== 'function') return;
23061
+ try {
23062
+ worker.postMessage({ type: 'codelab:config', csp: policy });
23063
+ } catch (err) {
23064
+ this.logger.warn('Could not deliver the preview CSP to the service worker.', err);
23065
+ }
23066
+ };
23067
+
23068
+ if (registration) {
23069
+ send(registration.active);
23070
+ send(registration.installing);
23071
+ send(registration.waiting);
23072
+ }
23073
+
23074
+ const sw = (typeof navigator !== 'undefined' && navigator.serviceWorker) ? navigator.serviceWorker : null;
23075
+ if (sw && sw.ready && typeof sw.ready.then === 'function') {
23076
+ sw.ready
23077
+ .then((readyReg) => { if (readyReg) send(readyReg.active); })
23078
+ .catch((err) => this.logger.warn('Preview service worker never became ready.', err));
20780
23079
  }
20781
23080
  }
20782
23081
 
@@ -20809,11 +23108,15 @@ declare module 'bun:sqlite' {
20809
23108
  } else if (res && res.headers) {
20810
23109
  Object.assign(outHeaders, res.headers);
20811
23110
  }
20812
- } catch (_) {}
23111
+ } catch (err) {
23112
+ this.logger.debug('Could not copy response headers in _dispatchPreviewRequest.', err);
23113
+ }
20813
23114
  let bodyText = '';
20814
23115
  try {
20815
23116
  bodyText = res && typeof res.text === 'function' ? await res.text() : String((res && res.body) || '');
20816
- } catch (_) {}
23117
+ } catch (err) {
23118
+ this.logger.debug('Could not read response body in _dispatchPreviewRequest.', err);
23119
+ }
20817
23120
  return {
20818
23121
  status: (res && res.status) || 200,
20819
23122
  statusText: (res && res.statusText) || 'OK',
@@ -20840,48 +23143,240 @@ declare module 'bun:sqlite' {
20840
23143
  const p = Number(port) || 3000;
20841
23144
  const rawPath = pathAndQuery || '/';
20842
23145
  const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
20843
- const base = this.previewOrigin || '';
23146
+ // Same-origin loopback by default. `previewOrigin` is only honoured once a
23147
+ // relay exists on that origin; pretending otherwise yields a 503.
23148
+ const base = (PREVIEW_RELAY_AVAILABLE && this.previewOrigin) ? this.previewOrigin : '';
20844
23149
  return `${base}/__preview/${p}${path}`;
20845
23150
  }
20846
23151
 
23152
+ /** Resolved CSP for preview documents served by this workbench. */
23153
+ _previewPolicy() {
23154
+ const origin = (typeof location !== 'undefined' && location && location.origin) ? location.origin : '';
23155
+ if (!PreviewCsp || typeof PreviewCsp.buildPreviewPolicy !== 'function') {
23156
+ return "default-src 'self'; object-src 'none'";
23157
+ }
23158
+ return PreviewCsp.buildPreviewPolicy(
23159
+ Object.assign({ hostOrigin: origin }, this.previewCsp.allow, { mode: this.previewCsp.mode })
23160
+ );
23161
+ }
23162
+
23163
+ /** Remote origins the current policy allows, for the preview toolbar. */
23164
+ _previewNetworkHosts() {
23165
+ if (!PreviewCsp || typeof PreviewCsp.describePreviewNetwork !== 'function') return [];
23166
+ return PreviewCsp.describePreviewNetwork(this.previewCsp);
23167
+ }
23168
+
20847
23169
  _warnPreviewIsolation() {
20848
- if (this.previewOrigin || this._previewIsolationWarned) return;
23170
+ if (!this.previewOrigin || this._previewIsolationWarned) return;
20849
23171
  this._previewIsolationWarned = true;
20850
- if (typeof console !== 'undefined' && typeof console.warn === 'function') {
20851
- console.warn(
20852
- '[code-lab] Web Preview runs on the host origin and can read host storage. ' +
20853
- 'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
20854
- );
20855
- }
23172
+ if (PREVIEW_RELAY_AVAILABLE) return;
23173
+ this.logger.warn(
23174
+ '`previewOrigin` was ignored: cross-origin previews need the preview relay ' +
23175
+ '(apps/preview-origin), which has not shipped yet. Previews run sandboxed on ' +
23176
+ 'the host origin: no host DOM, no host storage.'
23177
+ );
20856
23178
  }
20857
23179
 
20858
23180
  _injectPreviewCsp(html, port) {
20859
23181
  if (typeof html !== 'string' || !html) return html;
20860
- if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
20861
23182
 
20862
- const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
20863
- (/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
23183
+ const tags = [];
23184
+ if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
23185
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
23186
+ }
23187
+ if (!/<base\b/i.test(html)) {
23188
+ tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
23189
+ }
23190
+ if (html.indexOf('data-codelab-preview-shims') === -1 &&
23191
+ PreviewCsp && typeof PreviewCsp.buildPreviewShims === 'function') {
23192
+ tags.push(PreviewCsp.buildPreviewShims());
23193
+ }
23194
+ if (tags.length === 0) return html;
20864
23195
 
23196
+ const injection = tags.join('');
20865
23197
  if (/<head\b[^>]*>/i.test(html)) {
20866
- return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
23198
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
20867
23199
  }
20868
23200
  if (/<html\b[^>]*>/i.test(html)) {
20869
- return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
23201
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
23202
+ }
23203
+ return `<head>${injection}</head>${html}`;
23204
+ }
23205
+
23206
+ /**
23207
+ * Preview documents are sandboxed (opaque origin), so `event.origin` is the
23208
+ * string `"null"` and cannot be used to authenticate the sender. Match the
23209
+ * message source against the preview frame instead.
23210
+ */
23211
+ _installPreviewViolationListener() {
23212
+ if (this._previewViolationHandler) return;
23213
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
23214
+
23215
+ this._previewViolationHandler = (event) => {
23216
+ const data = event && event.data;
23217
+ if (!data || typeof data.type !== 'string') return;
23218
+ const iframe = this.container ? this.container.querySelector('#cl-preview-iframe') : null;
23219
+ if (!iframe) return;
23220
+ // `contentWindow` is unavailable on the mock DOM used by unit tests.
23221
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
23222
+
23223
+ if (data.type === 'codelab:preview-violation') {
23224
+ this._reportPreviewViolation(data);
23225
+ } else if (data.type === 'codelab:preview-console') {
23226
+ const level = ['log', 'warn', 'error', 'info'].includes(data.level) ? data.level : 'log';
23227
+ const args = Array.isArray(data.args) ? data.args : [data.args];
23228
+ const text = args.map((a) => String(a ?? '')).join(' ');
23229
+ this.terminalLogs.push({
23230
+ type: level === 'error' ? 'stderr' : 'stdout',
23231
+ text: `[Preview ${level.toUpperCase()}] ${text}`
23232
+ });
23233
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23234
+ this.previewState.consoleLogs.push({ level, text, timestamp: new Date().toLocaleTimeString() });
23235
+ if (this.previewState.consoleLogs.length > 200) this.previewState.consoleLogs.shift();
23236
+ this._updatePreviewConsoleUI();
23237
+ this._emitEvent('preview-console', { level, text, args });
23238
+ } else if (data.type === 'codelab:preview-error') {
23239
+ const msg = String(data.message || 'Uncaught runtime error');
23240
+ this.previewState.runtimeError = {
23241
+ message: msg,
23242
+ file: data.file ? String(data.file) : null,
23243
+ line: typeof data.line === 'number' ? data.line : null,
23244
+ col: typeof data.col === 'number' ? data.col : null,
23245
+ stack: data.stack ? String(data.stack) : null
23246
+ };
23247
+ this.terminalLogs.push({
23248
+ type: 'stderr',
23249
+ text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
23250
+ });
23251
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23252
+ this.previewState.consoleLogs.push({
23253
+ level: 'error',
23254
+ text: `${msg}${data.stack ? '\n' + String(data.stack) : ''}`,
23255
+ timestamp: new Date().toLocaleTimeString()
23256
+ });
23257
+ this._updatePreviewConsoleUI();
23258
+ this._emitEvent('preview-error', this.previewState.runtimeError);
23259
+ } else if (data.type === 'codelab:preview-error-clear') {
23260
+ this.previewState.runtimeError = null;
23261
+ } else if (data.type === 'codelab:preview-fetch') {
23262
+ const reqId = data.reqId || data.id;
23263
+ const targetPort = Number(data.port) || this.previewState.port || this._firstListeningPort() || 3000;
23264
+ const reqPath = data.path ? (String(data.path).startsWith('/') ? String(data.path) : '/' + String(data.path)) : '/';
23265
+ const targetUrl = String(data.url || `http://127.0.0.1:${targetPort}${reqPath}`);
23266
+ this._dispatchPreviewRequest({
23267
+ port: targetPort,
23268
+ url: targetUrl,
23269
+ method: data.method || 'GET',
23270
+ headers: data.headers || {},
23271
+ body: data.body !== undefined ? data.body : null
23272
+ })
23273
+ .then((res) => {
23274
+ const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
23275
+ if (netPill) netPill.textContent = `${(this.lastHttpTrace || []).length} reqs`;
23276
+ if (this.drawerTab === 'network') this._renderDrawerBody();
23277
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23278
+ iframe.contentWindow.postMessage({
23279
+ type: 'codelab:preview-fetch-res',
23280
+ reqId,
23281
+ id: reqId,
23282
+ status: res.status || 200,
23283
+ statusText: res.statusText || 'OK',
23284
+ headers: res.headers || {},
23285
+ body: res.body || ''
23286
+ }, '*');
23287
+ }
23288
+ })
23289
+ .catch((err) => {
23290
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23291
+ iframe.contentWindow.postMessage({
23292
+ type: 'codelab:preview-fetch-res',
23293
+ reqId,
23294
+ id: reqId,
23295
+ error: String((err && err.message) || err)
23296
+ }, '*');
23297
+ }
23298
+ });
23299
+ } else if (data.type === 'codelab:preview-navigate') {
23300
+ const navHref = data.href || (data.path ? (data.port ? `http://127.0.0.1:${data.port}${data.path}` : String(data.path)) : '');
23301
+ if (navHref) {
23302
+ this._previewGo(String(navHref));
23303
+ }
23304
+ } else if (data.type === 'codelab:preview-url-change') {
23305
+ if (data.path && typeof data.path === 'string') {
23306
+ this.previewState.path = data.path.startsWith('/') ? data.path : '/' + data.path;
23307
+ this.previewState.url = this._previewUrl();
23308
+ const input = this.container ? this.container.querySelector('#cl-preview-url-input') : null;
23309
+ if (input) input.value = this.previewState.url;
23310
+ }
23311
+ }
23312
+ };
23313
+ window.addEventListener('message', this._previewViolationHandler);
23314
+ }
23315
+
23316
+ _reportPreviewViolation(violation) {
23317
+ const blockedURI = String((violation && violation.blockedURI) || 'unknown');
23318
+ const directive = String((violation && violation.directive) || '');
23319
+ const key = `${directive}|${blockedURI}`;
23320
+ const state = this.previewState;
23321
+ state.violations = state.violations || [];
23322
+ if (state.violations.length < 20 && !state.violations.some((v) => v.key === key)) {
23323
+ state.violations.push({ key, directive, blockedURI });
23324
+ this._showToast(`Blocked by Content-Security-Policy: ${this._shortPreviewUrl(blockedURI)}`, 'error');
23325
+ this._emitEvent('preview-violation', { directive, blockedURI, violations: state.violations.slice() });
23326
+ }
23327
+ this._updatePreviewCspStatus();
23328
+ }
23329
+
23330
+ _shortPreviewUrl(raw) {
23331
+ const value = String(raw || '');
23332
+ try {
23333
+ const parsed = new URL(value);
23334
+ const path = parsed.pathname.length > 32 ? `${parsed.pathname.slice(0, 32)}…` : parsed.pathname;
23335
+ return `${parsed.host}${path === '/' ? '' : path}`;
23336
+ } catch (_) {
23337
+ // Not a URL (e.g. "inline" or "eval"); show it verbatim, truncated.
23338
+ return value.length > 48 ? `${value.slice(0, 48)}…` : value;
23339
+ }
23340
+ }
23341
+
23342
+ /** Update (or create) the CSP status chip in the preview toolbar. */
23343
+ _updatePreviewCspStatus() {
23344
+ if (!this.container) return;
23345
+ const chip = this.container.querySelector('#cl-preview-csp-status');
23346
+ if (!chip) return;
23347
+ const violations = (this.previewState && this.previewState.violations) || [];
23348
+ if (!violations.length) {
23349
+ chip.hidden = true;
23350
+ chip.textContent = '';
23351
+ chip.removeAttribute('title');
23352
+ return;
20870
23353
  }
20871
- return `<head>${tags}</head>${html}`;
23354
+ const last = violations[violations.length - 1];
23355
+ chip.hidden = false;
23356
+ chip.textContent = `Blocked: ${this._shortPreviewUrl(last.blockedURI)}`;
23357
+ chip.title = violations
23358
+ .map((v) => `${v.directive} → ${v.blockedURI}`)
23359
+ .join('\n');
20872
23360
  }
20873
23361
 
20874
23362
  _openWebPreview(port, path = '/') {
20875
23363
  const p = Number(port) || this._firstListeningPort() || 3000;
20876
23364
  this._warnPreviewIsolation();
23365
+ this._installPreviewViolationListener();
20877
23366
  this.previewState.port = p;
20878
23367
  this.previewState.path = path || '/';
20879
23368
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
20880
23369
  this.previewState.error = null;
23370
+ this.previewState.violations = [];
20881
23371
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
20882
23372
  this.previewHistory.push(this.previewState.url);
20883
23373
  this.previewHistoryIdx = this.previewHistory.length - 1;
20884
- this.switchDrawerTab('preview');
23374
+ if (this.previewState.dockMode === 'split') {
23375
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23376
+ if (splitHost) this._renderWebPreview(splitHost);
23377
+ } else {
23378
+ this.switchDrawerTab('preview');
23379
+ }
20885
23380
  return this._previewLoadPromise || Promise.resolve();
20886
23381
  }
20887
23382
 
@@ -20968,7 +23463,7 @@ declare module 'bun:sqlite' {
20968
23463
  try {
20969
23464
  const win = window.open(url, '_blank');
20970
23465
  if (win) {
20971
- try { win.opener = null; } catch (_) {}
23466
+ try { win.opener = null; } catch (err) { this.logger.debug('Could not clear win.opener.', err); }
20972
23467
  opened = true;
20973
23468
  }
20974
23469
  } catch (_) { opened = false; }
@@ -20990,7 +23485,9 @@ declare module 'bun:sqlite' {
20990
23485
  const u = new URL(url);
20991
23486
  port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
20992
23487
  path = u.pathname + (u.search || '') + (u.hash || '');
20993
- } catch (_) {}
23488
+ } catch (err) {
23489
+ this.logger.debug('Failed to parse preview URL; using fallback port/path.', err);
23490
+ }
20994
23491
  this.previewState.port = port;
20995
23492
  this.previewState.path = path;
20996
23493
  this.previewState.url = url;
@@ -20998,7 +23495,12 @@ declare module 'bun:sqlite' {
20998
23495
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
20999
23496
  this.previewHistory.push(url);
21000
23497
  this.previewHistoryIdx = this.previewHistory.length - 1;
21001
- this.switchDrawerTab('preview');
23498
+ if (this.previewState.dockMode === 'split') {
23499
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23500
+ if (splitHost) this._renderWebPreview(splitHost);
23501
+ } else {
23502
+ this.switchDrawerTab('preview');
23503
+ }
21002
23504
  return this._previewLoadPromise || Promise.resolve();
21003
23505
  }
21004
23506
 
@@ -21022,7 +23524,9 @@ declare module 'bun:sqlite' {
21022
23524
  const u = new URL(url);
21023
23525
  this.previewState.port = Number(u.port || 80);
21024
23526
  this.previewState.path = u.pathname + (u.search || '');
21025
- } catch (_) {}
23527
+ } catch (err) {
23528
+ this.logger.debug('Failed to parse preview history URL.', err);
23529
+ }
21026
23530
  const input = this.container.querySelector('#cl-preview-url-input');
21027
23531
  if (input) input.value = url;
21028
23532
  this._renderWebPreviewControls();
@@ -21037,6 +23541,94 @@ declare module 'bun:sqlite' {
21037
23541
  if (!['desktop', 'tablet', 'mobile'].includes(mode)) return;
21038
23542
  this.previewState.frameMode = mode;
21039
23543
  this._renderDrawerBody();
23544
+ if (this.previewState.dockMode === 'split') {
23545
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23546
+ if (splitHost) this._renderWebPreview(splitHost);
23547
+ }
23548
+ }
23549
+
23550
+ _togglePreviewDock() {
23551
+ this.previewState.dockMode = this.previewState.dockMode === 'split' ? 'bottom' : 'split';
23552
+ this._previewRenderKey = null;
23553
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23554
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23555
+ if (this.previewState.dockMode === 'split') {
23556
+ if (splitBar) splitBar.style.display = 'block';
23557
+ if (splitHost) {
23558
+ splitHost.style.display = 'flex';
23559
+ this._renderWebPreview(splitHost);
23560
+ }
23561
+ if (this.drawerTab === 'preview') {
23562
+ this.switchDrawerTab('terminal');
23563
+ } else {
23564
+ this._renderDrawerBody();
23565
+ }
23566
+ } else {
23567
+ if (splitBar) splitBar.style.display = 'none';
23568
+ if (splitHost) {
23569
+ splitHost.style.display = 'none';
23570
+ splitHost.innerHTML = '';
23571
+ }
23572
+ this.switchDrawerTab('preview');
23573
+ }
23574
+ if (this.editor && typeof this.editor.layout === 'function') {
23575
+ setTimeout(() => {
23576
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
23577
+ }, 30);
23578
+ }
23579
+ }
23580
+
23581
+ _togglePreviewMaximize() {
23582
+ this.previewState.maximized = !this.previewState.maximized;
23583
+ const previewEl = this.container ? this.container.querySelector('.codelab-preview') : null;
23584
+ if (previewEl) {
23585
+ previewEl.classList.toggle('is-maximized', Boolean(this.previewState.maximized));
23586
+ }
23587
+ const maxBtn = this.container ? this.container.querySelector('[data-cl-action="preview-maximize"]') : null;
23588
+ if (maxBtn) {
23589
+ maxBtn.classList.toggle('active', Boolean(this.previewState.maximized));
23590
+ }
23591
+ }
23592
+
23593
+ _togglePreviewConsole() {
23594
+ this.previewState.consoleOpen = !this.previewState.consoleOpen;
23595
+ this._updatePreviewConsoleUI();
23596
+ }
23597
+
23598
+ _clearPreviewConsole() {
23599
+ this.previewState.consoleLogs = [];
23600
+ this._updatePreviewConsoleUI();
23601
+ }
23602
+
23603
+ _updatePreviewConsoleUI() {
23604
+ if (!this.container) return;
23605
+ const consoleDrawer = this.container.querySelector('#cl-preview-console');
23606
+ const consoleBody = this.container.querySelector('#cl-preview-console-body');
23607
+ const consolePill = this.container.querySelector('#cl-preview-console-pill');
23608
+ const consoleBtn = this.container.querySelector('[data-cl-action="preview-console-toggle"]');
23609
+ const logs = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs : [];
23610
+ if (consolePill) {
23611
+ consolePill.textContent = String(logs.length);
23612
+ }
23613
+ if (consoleBtn) {
23614
+ consoleBtn.classList.toggle('active', Boolean(this.previewState.consoleOpen));
23615
+ }
23616
+ if (consoleDrawer) {
23617
+ consoleDrawer.style.display = this.previewState.consoleOpen ? 'flex' : 'none';
23618
+ }
23619
+ if (consoleBody) {
23620
+ if (logs.length === 0) {
23621
+ consoleBody.innerHTML = `<div class="codelab-preview-console__empty">No console output from preview frame yet.</div>`;
23622
+ } else {
23623
+ consoleBody.innerHTML = logs.map((entry) => `
23624
+ <div class="codelab-preview-console__row codelab-preview-console__row--${escapeHtml(entry.level || 'log')}">
23625
+ <span class="codelab-preview-console__time">${escapeHtml(entry.timestamp || '')}</span>
23626
+ <span class="codelab-preview-console__text">${escapeHtml(entry.text || '')}</span>
23627
+ </div>
23628
+ `).join('');
23629
+ consoleBody.scrollTop = consoleBody.scrollHeight;
23630
+ }
23631
+ }
21040
23632
  }
21041
23633
 
21042
23634
  _renderWebPreviewControls() {
@@ -21048,6 +23640,7 @@ declare module 'bun:sqlite' {
21048
23640
  if (backBtn) backBtn.disabled = this.previewHistoryIdx <= 0;
21049
23641
  const fwdBtn = this.container.querySelector('[data-cl-action="preview-forward"]');
21050
23642
  if (fwdBtn) fwdBtn.disabled = this.previewHistoryIdx >= this.previewHistory.length - 1;
23643
+ this._updatePreviewConsoleUI();
21051
23644
  }
21052
23645
 
21053
23646
  _popoutPreview() {
@@ -21056,9 +23649,11 @@ declare module 'bun:sqlite' {
21056
23649
  try {
21057
23650
  const u = new URL(url);
21058
23651
  popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
21059
- } catch (_) {}
23652
+ } catch (err) {
23653
+ this.logger.debug('Failed to parse popout preview URL.', err);
23654
+ }
21060
23655
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
21061
- try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
23656
+ try { window.open(popout, '_blank', 'noopener'); } catch (err) { this.logger.warn('window.open failed for preview popout.', err); }
21062
23657
  }
21063
23658
  return popout;
21064
23659
  }
@@ -21066,8 +23661,32 @@ declare module 'bun:sqlite' {
21066
23661
  _renderWebPreview(bodyEl) {
21067
23662
  if (!bodyEl) return;
21068
23663
  this._warnPreviewIsolation();
21069
- const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
21070
- if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
23664
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23665
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23666
+
23667
+ let targetHost = bodyEl;
23668
+ if (this.previewState.dockMode === 'split' && splitHost) {
23669
+ if (splitBar) splitBar.style.display = 'block';
23670
+ splitHost.style.display = 'flex';
23671
+ if (bodyEl !== splitHost) {
23672
+ bodyEl.innerHTML = `
23673
+ <div class="codelab-preview-split-notice">
23674
+ <span>Web Preview is docked to the right split pane.</span>
23675
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-dock-toggle">Dock to Bottom Drawer</button>
23676
+ </div>
23677
+ `;
23678
+ }
23679
+ targetHost = splitHost;
23680
+ } else {
23681
+ if (splitBar) splitBar.style.display = 'none';
23682
+ if (splitHost && bodyEl !== splitHost) {
23683
+ splitHost.style.display = 'none';
23684
+ splitHost.innerHTML = '';
23685
+ }
23686
+ }
23687
+
23688
+ const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this.previewState.dockMode}|${this._previewSwReady}`;
23689
+ if (targetHost.querySelector && targetHost.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
21071
23690
  this._renderWebPreviewControls();
21072
23691
  return;
21073
23692
  }
@@ -21085,8 +23704,24 @@ declare module 'bun:sqlite' {
21085
23704
  ? servers.map(s => `<option value="${s.port}" ${Number(s.port) === Number(this.previewState.port) ? 'selected' : ''}>Port ${s.port} · ${escapeHtml(s.name || 'server')}</option>`).join('')
21086
23705
  : `<option value="${this.previewState.port || 3000}">Port ${this.previewState.port || 3000}</option>`;
21087
23706
 
21088
- bodyEl.innerHTML = `
21089
- <div class="codelab-preview">
23707
+ const cspMode = (this.previewCsp && this.previewCsp.mode) || 'balanced';
23708
+ const cspHosts = this._previewNetworkHosts();
23709
+ const cspBadge = cspMode === 'strict'
23710
+ ? 'CSP: strict'
23711
+ : !cspHosts.length
23712
+ ? 'CSP: custom'
23713
+ : cspHosts.length === 1
23714
+ ? `CSP: ${cspHosts[0]}`
23715
+ : `CSP: ${cspHosts[0]} +${cspHosts.length - 1}`;
23716
+ const cspBadgeTitle = cspMode === 'strict'
23717
+ ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
23718
+ : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
23719
+
23720
+ const logsCount = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs.length : 0;
23721
+ const isSplit = this.previewState.dockMode === 'split';
23722
+
23723
+ targetHost.innerHTML = `
23724
+ <div class="codelab-preview ${this.previewState.maximized ? 'is-maximized' : ''}">
21090
23725
  <div class="codelab-preview-chrome">
21091
23726
  <div class="codelab-preview-nav">
21092
23727
  <button type="button" class="codelab-preview-btn" data-cl-action="preview-back" title="Back" ${this.previewHistoryIdx <= 0 ? 'disabled' : ''}>${CL_ICONS.arrowLeft || '←'}</button>
@@ -21100,10 +23735,31 @@ declare module 'bun:sqlite' {
21100
23735
  <button type="button" class="codelab-preview-btn ${this.previewState.frameMode === 'tablet' ? 'active' : ''}" data-cl-action="preview-mode" data-mode="tablet" title="Tablet">${CL_ICONS.tablet || '▢'}</button>
21101
23736
  <button type="button" class="codelab-preview-btn ${this.previewState.frameMode === 'mobile' ? 'active' : ''}" data-cl-action="preview-mode" data-mode="mobile" title="Mobile">${CL_ICONS.smartphone || '▯'}</button>
21102
23737
  </div>
23738
+ <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
23739
+ <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
23740
+ <button type="button" class="codelab-preview-btn ${this.previewState.consoleOpen ? 'active' : ''}" data-cl-action="preview-console-toggle" title="Toggle Preview Console">
23741
+ ${CL_ICONS.terminal || '>_'} <span class="codelab-preview-console-pill" id="cl-preview-console-pill">${logsCount}</span>
23742
+ </button>
23743
+ <button type="button" class="codelab-preview-btn ${isSplit ? 'active' : ''}" data-cl-action="preview-dock-toggle" title="${isSplit ? 'Dock Preview to Bottom Drawer' : 'Dock Preview to Right Split Pane'}">
23744
+ ${CL_ICONS.layout || '◫'}
23745
+ </button>
23746
+ <button type="button" class="codelab-preview-btn ${this.previewState.maximized ? 'active' : ''}" data-cl-action="preview-maximize" title="Maximize / Restore Preview">
23747
+ ${CL_ICONS.maximize || '⛶'}
23748
+ </button>
21103
23749
  <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-popout" title="Open in a new browser tab">${CL_ICONS.externalLink || '↗'} <span>Pop Out</span></button>
21104
23750
  </div>
21105
23751
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
21106
- <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" allow="camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'; usb 'none'" referrerpolicy="same-origin" title="Web Preview"></iframe>
23752
+ <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-modals" allow="camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'; usb 'none'" referrerpolicy="no-referrer-when-downgrade" title="Web Preview"></iframe>
23753
+ </div>
23754
+ <div class="codelab-preview-console" id="cl-preview-console" style="display:${this.previewState.consoleOpen ? 'flex' : 'none'}">
23755
+ <div class="codelab-preview-console__bar">
23756
+ <span>Preview Console</span>
23757
+ <div style="display:flex;align-items:center;gap:6px;">
23758
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-clear">Clear</button>
23759
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-toggle">Close</button>
23760
+ </div>
23761
+ </div>
23762
+ <div class="codelab-preview-console__body" id="cl-preview-console-body"></div>
21107
23763
  </div>
21108
23764
  ${servers.length
21109
23765
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -21116,6 +23772,8 @@ declare module 'bun:sqlite' {
21116
23772
  </div>`}
21117
23773
  </div>
21118
23774
  `;
23775
+ this._updatePreviewCspStatus();
23776
+ this._updatePreviewConsoleUI();
21119
23777
  this._loadPreviewFrame();
21120
23778
  }
21121
23779
 
@@ -21132,22 +23790,25 @@ declare module 'bun:sqlite' {
21132
23790
  this.previewState.error = 'No port selected';
21133
23791
  return Promise.resolve();
21134
23792
  }
23793
+ this._syncFilesToShellVfs();
21135
23794
  const fullUrl = this._previewUrl();
21136
23795
  this.previewState.loading = true;
21137
23796
  this.previewState.error = null;
21138
23797
 
21139
- if (this._previewSwReady) {
23798
+ if (this.options && this.options.useServiceWorkerForIframe === true && this._previewSwReady) {
21140
23799
  try {
21141
23800
  const u = new URL(fullUrl);
21142
23801
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
21143
23802
  iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
21144
23803
  this.previewState.loading = false;
21145
23804
  return Promise.resolve();
21146
- } catch (_) {}
23805
+ } catch (err) {
23806
+ this.logger.warn('Failed to set Service Worker preview URL; falling back to srcdoc.', err);
23807
+ }
21147
23808
  }
21148
23809
 
21149
- // Fallback (no Service Worker): dispatch via the virtual port table and
21150
- // inline the response with an injected <base> for relative asset URLs.
23810
+ // Direct virtual dispatch + srcdoc injection guarantees zero Service Worker
23811
+ // race conditions and 100% deterministic loading inside sandboxed iframes.
21151
23812
  return this._dispatchPreviewRequest({ port, url: fullUrl, method: 'GET' })
21152
23813
  .then((res) => {
21153
23814
  let body = res.body || '';
@@ -21209,7 +23870,7 @@ declare module 'bun:sqlite' {
21209
23870
  const full = dir === '/' ? '/' + entry : dir + '/' + entry;
21210
23871
  const rel = relPrefix ? relPrefix + '/' + entry : entry;
21211
23872
  let isDir = false;
21212
- try { isDir = vfs.statSync(full).isDirectory(); } catch (_) {}
23873
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
21213
23874
  if (isDir) {
21214
23875
  shellWorkspaceFolders.add(rel);
21215
23876
  walk(full, rel);
@@ -21217,7 +23878,9 @@ declare module 'bun:sqlite' {
21217
23878
  try {
21218
23879
  const content = String(vfs.readFileSync(full, 'utf8') ?? '');
21219
23880
  shellWorkspaceFiles.set(rel, content);
21220
- } catch (_) {}
23881
+ } catch (err) {
23882
+ this.logger.debug(`Could not read VFS file "${full}" during snapshot sync.`, err);
23883
+ }
21221
23884
  }
21222
23885
  }
21223
23886
  };
@@ -21519,6 +24182,27 @@ declare module 'bun:sqlite' {
21519
24182
  }
21520
24183
 
21521
24184
  _notifyCodeChange(filename, code) {
24185
+ if (this.shell && this.shell.vfs && filename && typeof this.shell.vfs.writeFileSync === 'function') {
24186
+ try {
24187
+ const clean = String(filename).replace(/^\/+/, '');
24188
+ const parts = clean.split('/');
24189
+ if (parts.length > 1 && typeof this.shell.vfs.mkdirSync === 'function') {
24190
+ this.shell.vfs.mkdirSync('/workspace/' + parts.slice(0, -1).join('/'), { recursive: true });
24191
+ }
24192
+ this.shell.vfs.writeFileSync('/workspace/' + clean, String(code ?? ''));
24193
+ } catch (err) {
24194
+ this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
24195
+ }
24196
+ }
24197
+ if ((this.drawerTab === 'preview' || (this.previewState && this.previewState.dockMode === 'split')) && this.previewState && this.previewState.port) {
24198
+ if (this._previewReloadTimer) {
24199
+ clearTimeout(this._previewReloadTimer);
24200
+ }
24201
+ this._previewReloadTimer = setTimeout(() => {
24202
+ this._previewReloadTimer = null;
24203
+ this._previewReload();
24204
+ }, 300);
24205
+ }
21522
24206
  if (this.onCodeChange) {
21523
24207
  try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
21524
24208
  }
@@ -21576,7 +24260,7 @@ declare module 'bun:sqlite' {
21576
24260
  if (fallbackWrap) fallbackWrap.style.display = 'none';
21577
24261
  if (mdPreview) mdPreview.style.display = 'none';
21578
24262
  if (this.editor) {
21579
- try { this.editor.setModel(null); } catch (_) {}
24263
+ try { this.editor.setModel(null); } catch (err) { this.logger.debug('editor.setModel(null) failed.', err); }
21580
24264
  }
21581
24265
  if (emptyEl) {
21582
24266
  emptyEl.style.display = 'flex';
@@ -21686,6 +24370,16 @@ declare module 'bun:sqlite' {
21686
24370
  };
21687
24371
  if (typeof document !== 'undefined') {
21688
24372
  document.addEventListener('keydown', this._escHandler);
24373
+ this._beforeUnloadHandler = () => {
24374
+ if (document.visibilityState === 'hidden') {
24375
+ try {
24376
+ this._saveState();
24377
+ } catch (err) {
24378
+ void err;
24379
+ }
24380
+ }
24381
+ };
24382
+ document.addEventListener('visibilitychange', this._beforeUnloadHandler);
21689
24383
  }
21690
24384
 
21691
24385
  this.container.addEventListener('keydown', e => {
@@ -21888,7 +24582,9 @@ declare module 'bun:sqlite' {
21888
24582
  textarea.select();
21889
24583
  document.execCommand('copy');
21890
24584
  document.body.removeChild(textarea);
21891
- } catch (_) {}
24585
+ } catch (err) {
24586
+ this.logger.warn('Clipboard fallback (execCommand) failed.', err);
24587
+ }
21892
24588
  };
21893
24589
 
21894
24590
  if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
@@ -22130,15 +24826,29 @@ declare module 'bun:sqlite' {
22130
24826
  this._previewSetFrameMode(actionBtn.dataset.mode);
22131
24827
  } else if (action === 'preview-popout') {
22132
24828
  this._popoutPreview();
24829
+ } else if (action === 'preview-dock-toggle') {
24830
+ this._togglePreviewDock();
24831
+ } else if (action === 'preview-maximize') {
24832
+ this._togglePreviewMaximize();
24833
+ } else if (action === 'preview-console-toggle') {
24834
+ this._togglePreviewConsole();
24835
+ } else if (action === 'preview-console-clear') {
24836
+ this._clearPreviewConsole();
22133
24837
  } else if (action === 'open-port-client') {
22134
- const port = actionBtn.dataset.port;
24838
+ const port = actionBtn.dataset.port || actionBtn.dataset.clPort;
22135
24839
  if (port) {
22136
24840
  this.httpClientUrl = `http://localhost:${port}/`;
24841
+ if (this.httpClientState) {
24842
+ this.httpClientState.url = `http://localhost:${port}/`;
24843
+ }
22137
24844
  this._renderDrawerBody();
22138
24845
  }
22139
24846
  } else if (action === 'stop-port') {
22140
- const port = Number(actionBtn.dataset.port);
24847
+ const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
22141
24848
  if (port) {
24849
+ if (this.portTable && typeof this.portTable.closeServer === 'function') {
24850
+ this.portTable.closeServer(port);
24851
+ }
22142
24852
  if (this.shell && this.shell.portTable && typeof this.shell.portTable.unregister === 'function') {
22143
24853
  this.shell.portTable.unregister(port);
22144
24854
  }
@@ -22148,18 +24858,32 @@ declare module 'bun:sqlite' {
22148
24858
  } else if (action === 'http-send') {
22149
24859
  this._sendHttpClientRequest();
22150
24860
  } else if (action === 'http-tab') {
22151
- this.httpActiveTab = actionBtn.dataset.httpTab || 'headers';
24861
+ const nextTab = actionBtn.dataset.tab || actionBtn.dataset.clHttpTab || actionBtn.dataset.httpTab || 'preview';
24862
+ this.httpActiveTab = nextTab;
24863
+ if (this.httpClientState) {
24864
+ this.httpClientState.activeResponseTab = nextTab;
24865
+ }
22152
24866
  this._renderDrawerBody();
22153
24867
  } else if (action === 'clear-net-traces') {
22154
24868
  this.lastHttpTrace = [];
22155
24869
  this.selectedNetTraceIdx = null;
24870
+ if (this.networkFilter) {
24871
+ this.networkFilter.selectedTraceId = null;
24872
+ }
22156
24873
  this._renderDrawerBody();
22157
24874
  } else if (action === 'select-net-trace') {
24875
+ const traceId = actionBtn.dataset.traceId || actionBtn.dataset.clTraceId || null;
22158
24876
  const idx = Number(actionBtn.dataset.traceIdx);
22159
24877
  this.selectedNetTraceIdx = Number.isNaN(idx) ? null : idx;
24878
+ if (this.networkFilter) {
24879
+ this.networkFilter.selectedTraceId = traceId;
24880
+ }
22160
24881
  this._renderDrawerBody();
22161
24882
  } else if (action === 'close-net-detail') {
22162
24883
  this.selectedNetTraceIdx = null;
24884
+ if (this.networkFilter) {
24885
+ this.networkFilter.selectedTraceId = null;
24886
+ }
22163
24887
  this._renderDrawerBody();
22164
24888
  }
22165
24889
  return;
@@ -22246,6 +24970,7 @@ declare module 'bun:sqlite' {
22246
24970
  { id: 'rename-active', label: 'File: Rename Active File...', shortcut: 'F2', action: () => { if (this.activeFile) this.startInlineRename('file', this.activeFile); } },
22247
24971
  { id: 'delete-active', label: 'File: Delete Active File', action: () => { if (this.activeFile) this.deleteFile(this.activeFile); } },
22248
24972
  { id: 'export-workspace', label: 'Workspace: Export Workspace as JSON', action: () => this.exportWorkspace({ download: true }) },
24973
+ { id: 'export-workspace-zip', label: 'Workspace: Export Project as ZIP Archive', action: () => this.exportProjectZip({ download: true }) },
22249
24974
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
22250
24975
  { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
22251
24976
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
@@ -22256,6 +24981,9 @@ declare module 'bun:sqlite' {
22256
24981
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
22257
24982
  } },
22258
24983
  { id: 'toggle-fullscreen', label: 'View: Toggle Fullscreen Workbench', action: () => this.toggleFullscreen() },
24984
+ { id: 'search-workspace', label: 'Search: Find & Replace Across Files...', shortcut: '⇧⌘F', action: () => this.showSearchModal() },
24985
+ { id: 'open-scm', label: 'Git: Source Control (Status, Stage & Commit)...', action: () => this.showScmModal() },
24986
+ { id: 'open-problems', label: 'View: Show Problems & Diagnostics...', action: () => this.showProblemsModal() },
22259
24987
  { id: 'open-packages', label: 'Packages: Manage NPM Dependencies & Runtime', action: () => this.showPackagesModal() },
22260
24988
  { id: 'git-clone', label: 'Git: Clone Public GitHub Repository...', action: () => this.showCloneRepoModal() }
22261
24989
  ];
@@ -22288,7 +25016,9 @@ declare module 'bun:sqlite' {
22288
25016
  input.focus();
22289
25017
  try {
22290
25018
  input.setSelectionRange(initialVal.length, initialVal.length);
22291
- } catch (_) {}
25019
+ } catch (err) {
25020
+ this.logger.debug('input.setSelectionRange failed in command palette.', err);
25021
+ }
22292
25022
 
22293
25023
  input.addEventListener('input', () => {
22294
25024
  this.paletteSelectedIndex = 0;
@@ -22561,7 +25291,7 @@ declare module 'bun:sqlite' {
22561
25291
  const onUp = ev => {
22562
25292
  vSplitter.classList.remove('is-dragging');
22563
25293
  shell.classList.remove('is-resizing');
22564
- try { vSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
25294
+ try { vSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22565
25295
  vSplitter.removeEventListener('pointermove', onMove);
22566
25296
  vSplitter.removeEventListener('pointerup', onUp);
22567
25297
  };
@@ -22602,7 +25332,7 @@ declare module 'bun:sqlite' {
22602
25332
  const onUp = ev => {
22603
25333
  hSplitter.classList.remove('is-dragging');
22604
25334
  shell.classList.remove('is-resizing-row');
22605
- try { hSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
25335
+ try { hSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22606
25336
  hSplitter.removeEventListener('pointermove', onMove);
22607
25337
  hSplitter.removeEventListener('pointerup', onUp);
22608
25338
  };
@@ -22629,7 +25359,7 @@ declare module 'bun:sqlite' {
22629
25359
  e.preventDefault();
22630
25360
  fSplitter.classList.add('is-dragging');
22631
25361
  shell.classList.add('is-resizing');
22632
- try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
25362
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
22633
25363
 
22634
25364
  const onMove = ev => {
22635
25365
  const ws = this.container.querySelector('.codelab-workspace');
@@ -22643,7 +25373,7 @@ declare module 'bun:sqlite' {
22643
25373
  const onUp = ev => {
22644
25374
  fSplitter.classList.remove('is-dragging');
22645
25375
  shell.classList.remove('is-resizing');
22646
- try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
25376
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22647
25377
  fSplitter.removeEventListener('pointermove', onMove);
22648
25378
  fSplitter.removeEventListener('pointerup', onUp);
22649
25379
  this._saveState();
@@ -22653,6 +25383,42 @@ declare module 'bun:sqlite' {
22653
25383
  fSplitter.addEventListener('pointerup', onUp);
22654
25384
  });
22655
25385
  }
25386
+
25387
+ const pSplitter = this.container.querySelector('#cl-splitter-preview');
25388
+ if (pSplitter) {
25389
+ pSplitter.addEventListener('dblclick', () => {
25390
+ shell.style.setProperty('--cl-preview-split-width', '44%');
25391
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25392
+ });
25393
+
25394
+ pSplitter.addEventListener('pointerdown', e => {
25395
+ e.preventDefault();
25396
+ pSplitter.classList.add('is-dragging');
25397
+ shell.classList.add('is-resizing');
25398
+ try { pSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
25399
+
25400
+ const onMove = ev => {
25401
+ const ws = this.container.querySelector('.codelab-workspace');
25402
+ const rect = (ws || shell).getBoundingClientRect();
25403
+ const minW = 240;
25404
+ const maxW = Math.max(minW, Math.floor(rect.width * 0.65));
25405
+ const nextW = Math.min(maxW, Math.max(minW, Math.round(rect.right - ev.clientX)));
25406
+ shell.style.setProperty('--cl-preview-split-width', `${nextW}px`);
25407
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25408
+ };
25409
+
25410
+ const onUp = ev => {
25411
+ pSplitter.classList.remove('is-dragging');
25412
+ shell.classList.remove('is-resizing');
25413
+ try { pSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
25414
+ pSplitter.removeEventListener('pointermove', onMove);
25415
+ pSplitter.removeEventListener('pointerup', onUp);
25416
+ };
25417
+
25418
+ pSplitter.addEventListener('pointermove', onMove);
25419
+ pSplitter.addEventListener('pointerup', onUp);
25420
+ });
25421
+ }
22656
25422
  }
22657
25423
 
22658
25424
  selectStep(idx, shouldJump = true) {
@@ -22881,6 +25647,9 @@ declare module 'bun:sqlite' {
22881
25647
  if (this.savedState.customFiles) {
22882
25648
  delete this.savedState.customFiles[key];
22883
25649
  }
25650
+ if (this.savedState.hasSnapshot) {
25651
+ delete this.savedState.hasSnapshot[key];
25652
+ }
22884
25653
  this._saveState();
22885
25654
  this._syncAllModels();
22886
25655
  this._syncActiveFileToView();
@@ -22986,7 +25755,9 @@ declare module 'bun:sqlite' {
22986
25755
  if (this.files['package.json']) {
22987
25756
  try {
22988
25757
  pkgJson = JSON.parse(this.files['package.json']);
22989
- } catch (_) {}
25758
+ } catch (err) {
25759
+ this.logger.warn('Malformed package.json when adding dependency; reinitializing.', err);
25760
+ }
22990
25761
  }
22991
25762
  if (!pkgJson.dependencies || typeof pkgJson.dependencies !== 'object') {
22992
25763
  pkgJson.dependencies = {};
@@ -23647,6 +26418,219 @@ declare module 'bun:sqlite' {
23647
26418
  return true;
23648
26419
  }
23649
26420
 
26421
+ exportProjectZip(options = {}) {
26422
+ const zipMod = root.CodeLabZip;
26423
+ if (!zipMod || typeof zipMod.createZip !== 'function') {
26424
+ throw new Error('CodeLabZip engine is not loaded');
26425
+ }
26426
+ const bytes = zipMod.createZip(this.files || {});
26427
+ if (options && options.download) {
26428
+ try {
26429
+ if (typeof Blob !== 'undefined' && typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function' && typeof document !== 'undefined') {
26430
+ const blob = new Blob([bytes], { type: 'application/zip' });
26431
+ const url = URL.createObjectURL(blob);
26432
+ const a = document.createElement('a');
26433
+ a.href = url;
26434
+ a.download = `${this.labId || 'workspace'}.zip`;
26435
+ a.click();
26436
+ setTimeout(() => URL.revokeObjectURL(url), 500);
26437
+ }
26438
+ } catch (err) {
26439
+ this.logger.error('Failed to download project ZIP export.', err);
26440
+ }
26441
+ }
26442
+ return bytes;
26443
+ }
26444
+
26445
+ importProjectZip(zipBytes) {
26446
+ const zipMod = root.CodeLabZip;
26447
+ if (!zipMod || typeof zipMod.extractZip !== 'function') {
26448
+ throw new Error('CodeLabZip engine is not loaded');
26449
+ }
26450
+ const extracted = zipMod.extractZip(zipBytes);
26451
+ if (!extracted || typeof extracted !== 'object') return false;
26452
+ this.setFiles(extracted);
26453
+ this._syncFilesToShellVfs();
26454
+ return true;
26455
+ }
26456
+
26457
+ searchWorkspace(options) {
26458
+ const searchMod = root.CodeLabSearch;
26459
+ if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
26460
+ throw new Error('CodeLabSearch engine is not loaded');
26461
+ }
26462
+ return searchMod.searchInFiles(this.files || {}, options);
26463
+ }
26464
+
26465
+ replaceInWorkspace(options) {
26466
+ const searchMod = root.CodeLabSearch;
26467
+ if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
26468
+ throw new Error('CodeLabSearch engine is not loaded');
26469
+ }
26470
+ const res = searchMod.replaceInFiles(this.files || {}, options);
26471
+ if (res && res.files && res.filesModified > 0) {
26472
+ this.setFiles(res.files);
26473
+ this._syncFilesToShellVfs();
26474
+ }
26475
+ return res;
26476
+ }
26477
+
26478
+ getGitStatus() {
26479
+ const scmMod = root.CodeLabScm;
26480
+ if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
26481
+ return [];
26482
+ }
26483
+ const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
26484
+ return scmMod.computeGitStatus(gs, this.files || {});
26485
+ }
26486
+
26487
+ getDiagnostics() {
26488
+ const diagMod = root.CodeLabDiagnostics;
26489
+ if (!this._diagnosticsStore && diagMod && typeof diagMod.createDiagnosticsStore === 'function') {
26490
+ this._diagnosticsStore = diagMod.createDiagnosticsStore();
26491
+ }
26492
+ if (this._diagnosticsStore && typeof this._diagnosticsStore.getAll === 'function') {
26493
+ return this._diagnosticsStore.getAll();
26494
+ }
26495
+ return [];
26496
+ }
26497
+
26498
+ showSearchModal(initialQuery = '') {
26499
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
26500
+ if (!slot) return;
26501
+ const q = String(initialQuery || '');
26502
+ const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
26503
+ const rowsHtml = (results.matches || []).map((m) => `
26504
+ <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
26505
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
26506
+ </div>
26507
+ `).join('');
26508
+ slot.innerHTML = `
26509
+ <div class="codelab-modal-backdrop">
26510
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
26511
+ <div class="codelab-modal__header">
26512
+ <span>Search &amp; Replace Across Workspace</span>
26513
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
26514
+ </div>
26515
+ <div class="codelab-modal__body">
26516
+ <div style="display:flex;gap:8px;margin-bottom:8px;">
26517
+ <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
26518
+ <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
26519
+ </div>
26520
+ <div id="cl-search-results-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>'}</div>
26521
+ </div>
26522
+ </div>
26523
+ </div>
26524
+ `;
26525
+ }
26526
+
26527
+ showScmModal() {
26528
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
26529
+ if (!slot) return;
26530
+ const statusList = this.getGitStatus();
26531
+ const rowsHtml = statusList.map((entry) => `
26532
+ <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
26533
+ <span>${escapeHtml(entry.path)}</span>
26534
+ <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
26535
+ </div>
26536
+ `).join('');
26537
+ slot.innerHTML = `
26538
+ <div class="codelab-modal-backdrop">
26539
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
26540
+ <div class="codelab-modal__header">
26541
+ <span>Source Control (Git Status)</span>
26542
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
26543
+ </div>
26544
+ <div class="codelab-modal__body">
26545
+ <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
26546
+ </div>
26547
+ </div>
26548
+ </div>
26549
+ `;
26550
+ }
26551
+
26552
+ showProblemsModal() {
26553
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
26554
+ if (!slot) return;
26555
+ const items = this.getDiagnostics();
26556
+ const rowsHtml = items.map((d) => `
26557
+ <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
26558
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
26559
+ </div>
26560
+ `).join('');
26561
+ slot.innerHTML = `
26562
+ <div class="codelab-modal-backdrop">
26563
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
26564
+ <div class="codelab-modal__header">
26565
+ <span>Problems (${items.length})</span>
26566
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
26567
+ </div>
26568
+ <div class="codelab-modal__body">
26569
+ <div id="cl-problems-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">No problems have been detected in the workspace.</div>'}</div>
26570
+ </div>
26571
+ </div>
26572
+ </div>
26573
+ `;
26574
+ }
26575
+
26576
+ _ensureTerminalSessions() {
26577
+ if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
26578
+ this._terminalSessions = [
26579
+ { id: 'session-1', name: 'bash-1', logs: this.terminalLogs || [] }
26580
+ ];
26581
+ this._activeTerminalSessionId = 'session-1';
26582
+ }
26583
+ return this._terminalSessions;
26584
+ }
26585
+
26586
+ listTerminalSessions() {
26587
+ const sessions = this._ensureTerminalSessions();
26588
+ return sessions.map((s) => ({
26589
+ id: s.id,
26590
+ name: s.name,
26591
+ active: s.id === this._activeTerminalSessionId,
26592
+ logCount: Array.isArray(s.logs) ? s.logs.length : 0
26593
+ }));
26594
+ }
26595
+
26596
+ createTerminalSession(name) {
26597
+ const sessions = this._ensureTerminalSessions();
26598
+ const nextNum = sessions.length + 1;
26599
+ const id = `session-${Date.now()}-${nextNum}`;
26600
+ const label = name ? String(name).trim() : `bash-${nextNum}`;
26601
+ const newLogs = [];
26602
+ sessions.push({ id, name: label, logs: newLogs });
26603
+ this._activeTerminalSessionId = id;
26604
+ this.terminalLogs = newLogs;
26605
+ this._renderDrawerBody();
26606
+ return id;
26607
+ }
26608
+
26609
+ switchTerminalSession(id) {
26610
+ const sessions = this._ensureTerminalSessions();
26611
+ const target = sessions.find((s) => s.id === id || s.name === id);
26612
+ if (!target) return false;
26613
+ this._activeTerminalSessionId = target.id;
26614
+ this.terminalLogs = target.logs;
26615
+ this._renderDrawerBody();
26616
+ return true;
26617
+ }
26618
+
26619
+ closeTerminalSession(id) {
26620
+ const sessions = this._ensureTerminalSessions();
26621
+ if (sessions.length <= 1) return false;
26622
+ const idx = sessions.findIndex((s) => s.id === id || s.name === id);
26623
+ if (idx === -1) return false;
26624
+ const removed = sessions.splice(idx, 1)[0];
26625
+ if (this._activeTerminalSessionId === removed.id) {
26626
+ const next = sessions[Math.max(0, idx - 1)] || sessions[0];
26627
+ this._activeTerminalSessionId = next.id;
26628
+ this.terminalLogs = next.logs;
26629
+ }
26630
+ this._renderDrawerBody();
26631
+ return true;
26632
+ }
26633
+
23650
26634
  getFiles() {
23651
26635
  return { ...this.files };
23652
26636
  }
@@ -23654,7 +26638,7 @@ declare module 'bun:sqlite' {
23654
26638
  setFiles(filesMap) {
23655
26639
  if (!filesMap || typeof filesMap !== 'object') return;
23656
26640
  for (const model of this.models.values()) {
23657
- try { model.dispose(); } catch (_) {}
26641
+ try { model.dispose(); } catch (err) { this.logger.debug('model.dispose failed during setFiles.', err); }
23658
26642
  }
23659
26643
  this.models.clear();
23660
26644
  this.files = {};
@@ -23744,7 +26728,9 @@ declare module 'bun:sqlite' {
23744
26728
  if (this.shell && this.shell.vfs && typeof this.shell.vfs.writeFile === 'function') {
23745
26729
  try {
23746
26730
  this.shell.vfs.writeFile('/workspace/' + clean, updated);
23747
- } catch (_) {}
26731
+ } catch (err) {
26732
+ this.logger.warn(`Failed to sync markdown task toggle for "${clean}" to VFS.`, err);
26733
+ }
23748
26734
  }
23749
26735
  this._notifyCodeChange(clean, updated);
23750
26736
  }
@@ -23964,9 +26950,26 @@ declare module 'bun:sqlite' {
23964
26950
 
23965
26951
  destroy() {
23966
26952
  this.stopExecution();
26953
+ if (this._previewReloadTimer) {
26954
+ clearTimeout(this._previewReloadTimer);
26955
+ this._previewReloadTimer = null;
26956
+ }
23967
26957
  if (this._escHandler && typeof document !== 'undefined') {
23968
26958
  document.removeEventListener('keydown', this._escHandler);
23969
26959
  }
26960
+ if (this._beforeUnloadHandler && typeof document !== 'undefined') {
26961
+ document.removeEventListener('visibilitychange', this._beforeUnloadHandler);
26962
+ }
26963
+ this._beforeUnloadHandler = null;
26964
+ if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
26965
+ window.removeEventListener('message', this._previewViolationHandler);
26966
+ }
26967
+ this._previewViolationHandler = null;
26968
+ if (this._swMessageHandler && typeof navigator !== 'undefined' && navigator.serviceWorker &&
26969
+ typeof navigator.serviceWorker.removeEventListener === 'function') {
26970
+ navigator.serviceWorker.removeEventListener('message', this._swMessageHandler);
26971
+ }
26972
+ this._swMessageHandler = null;
23970
26973
  if (this._themeObserver) {
23971
26974
  this._themeObserver.disconnect();
23972
26975
  }
@@ -24027,7 +27030,9 @@ declare module 'bun:sqlite' {
24027
27030
  if (jsonScript && jsonScript.textContent) {
24028
27031
  try {
24029
27032
  inlineConfig = JSON.parse(jsonScript.textContent);
24030
- } catch (_) {}
27033
+ } catch (err) {
27034
+ DEFAULT_LOGGER.warn('Failed to parse <script type="application/json"> inside <code-lab>.', err);
27035
+ }
24031
27036
  }
24032
27037
 
24033
27038
  // Parse optional files JSON attribute
@@ -24036,7 +27041,9 @@ declare module 'bun:sqlite' {
24036
27041
  if (filesAttr) {
24037
27042
  try {
24038
27043
  attrFiles = JSON.parse(filesAttr);
24039
- } catch (_) {}
27044
+ } catch (err) {
27045
+ DEFAULT_LOGGER.warn('Failed to parse files="" attribute on <code-lab>.', err);
27046
+ }
24040
27047
  }
24041
27048
 
24042
27049
  const labId = this.getAttribute('lab-id') || this.getAttribute('build-id') || this.dataset.labId || this.dataset.buildId || inlineConfig.id || inlineConfig.labId || 'custom-lab';
@@ -24079,6 +27086,19 @@ declare module 'bun:sqlite' {
24079
27086
  reset() { if (this._instance) this._instance.reset(); }
24080
27087
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
24081
27088
  importWorkspace(snap) { return this._instance ? this._instance.importWorkspace(snap) : false; }
27089
+ exportProjectZip(opts) { return this._instance ? this._instance.exportProjectZip(opts) : null; }
27090
+ importProjectZip(bytes) { return this._instance ? this._instance.importProjectZip(bytes) : false; }
27091
+ searchWorkspace(opts) { return this._instance ? this._instance.searchWorkspace(opts) : null; }
27092
+ replaceInWorkspace(opts) { return this._instance ? this._instance.replaceInWorkspace(opts) : null; }
27093
+ getGitStatus() { return this._instance ? this._instance.getGitStatus() : []; }
27094
+ getDiagnostics() { return this._instance ? this._instance.getDiagnostics() : []; }
27095
+ showSearchModal(q) { if (this._instance) this._instance.showSearchModal(q); }
27096
+ showScmModal() { if (this._instance) this._instance.showScmModal(); }
27097
+ showProblemsModal() { if (this._instance) this._instance.showProblemsModal(); }
27098
+ listTerminalSessions() { return this._instance ? this._instance.listTerminalSessions() : []; }
27099
+ createTerminalSession(name) { return this._instance ? this._instance.createTerminalSession(name) : null; }
27100
+ switchTerminalSession(id) { return this._instance ? this._instance.switchTerminalSession(id) : false; }
27101
+ closeTerminalSession(id) { return this._instance ? this._instance.closeTerminalSession(id) : false; }
24082
27102
  on(ev, fn) { return this._instance ? this._instance.on(ev, fn) : () => {}; }
24083
27103
  off(ev, fn) { if (this._instance) this._instance.off(ev, fn); }
24084
27104
  use(plugin, opts) { if (this._instance) this._instance.use(plugin, opts); return this; }
@@ -24113,9 +27133,42 @@ declare module 'bun:sqlite' {
24113
27133
  Workbench: CodeLabWorkbench,
24114
27134
  CodeLabWorkbench,
24115
27135
  CodeLabElement: CodeLabElementClass,
27136
+ CodeLabError,
27137
+ isCodeLabError,
27138
+ createLogger,
27139
+ Logger: _sharedLoggerMod || { LOG_PREFIX, CodeLabError, isCodeLabError, createLogger, DEFAULT_LOGGER },
27140
+ html,
27141
+ raw,
27142
+ isSafeHtml,
27143
+ escapeHtml,
27144
+ Html: _sharedHtmlMod || { html, raw, isSafeHtml, escapeHtml },
24116
27145
  Runtime: root.CodeLabRuntime,
24117
27146
  Shell: root.CodeLabShell,
24118
27147
  Terminal: root.CodeLabTerminal,
27148
+ zip: root.CodeLabZip || null,
27149
+ createZip: root.CodeLabZip ? root.CodeLabZip.createZip : null,
27150
+ extractZip: root.CodeLabZip ? root.CodeLabZip.extractZip : null,
27151
+ computeCrc32: root.CodeLabZip ? root.CodeLabZip.computeCrc32 : null,
27152
+ sanitizeZipPath: root.CodeLabZip ? root.CodeLabZip.sanitizeZipPath : null,
27153
+ storage: root.CodeLabStorage || null,
27154
+ WorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.WorkspaceStorage : null,
27155
+ createWorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.createWorkspaceStorage : null,
27156
+ search: root.CodeLabSearch || null,
27157
+ searchInFiles: root.CodeLabSearch ? root.CodeLabSearch.searchInFiles : null,
27158
+ replaceInFiles: root.CodeLabSearch ? root.CodeLabSearch.replaceInFiles : null,
27159
+ matchesGlob: root.CodeLabSearch ? root.CodeLabSearch.matchesGlob : null,
27160
+ escapeRegex: root.CodeLabSearch ? root.CodeLabSearch.escapeRegex : null,
27161
+ normalizeSearchPath: root.CodeLabSearch ? root.CodeLabSearch.normalizeSearchPath : null,
27162
+ diagnostics: root.CodeLabDiagnostics || null,
27163
+ DiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.DiagnosticsStore : null,
27164
+ createDiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.createDiagnosticsStore : null,
27165
+ scm: root.CodeLabScm || null,
27166
+ createGitState: root.CodeLabScm ? root.CodeLabScm.createGitState : null,
27167
+ computeGitStatus: root.CodeLabScm ? root.CodeLabScm.computeGitStatus : null,
27168
+ stageFile: root.CodeLabScm ? root.CodeLabScm.stageFile : null,
27169
+ unstageFile: root.CodeLabScm ? root.CodeLabScm.unstageFile : null,
27170
+ commitChanges: root.CodeLabScm ? root.CodeLabScm.commitChanges : null,
27171
+ computeShortCommitHash: root.CodeLabScm ? root.CodeLabScm.computeShortCommitHash : null,
24119
27172
  renderMarkdown: renderSimpleMarkdown,
24120
27173
  renderSimpleMarkdown: renderSimpleMarkdown,
24121
27174
  extensions: {
@@ -24166,6 +27219,7 @@ const createVirtualFs = CodeLabRuntime.createVirtualFs;
24166
27219
  const createVirtualHttp = CodeLabRuntime.createVirtualHttp;
24167
27220
  const createVirtualNet = CodeLabRuntime.createVirtualNet;
24168
27221
  const createVirtualPortTable = CodeLabRuntime.createVirtualPortTable;
27222
+ const createWorkerRuntimeSource = CodeLabRuntime.createWorkerRuntimeSource;
24169
27223
  const createPosixShell = CodeLabShell ? CodeLabShell.createPosixShell : null;
24170
27224
  const cloneGitHubRepository = CodeLabShell ? CodeLabShell.cloneGitHubRepository : null;
24171
27225
  const parseGitHubRepoUrl = CodeLabShell ? CodeLabShell.parseGitHubRepoUrl : null;
@@ -24176,11 +27230,46 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
24176
27230
  const mount = CodeLab ? CodeLab.mount : null;
24177
27231
  const create = CodeLab ? CodeLab.create : null;
24178
27232
  const unmount = CodeLab ? CodeLab.unmount : null;
24179
- const version = CodeLab ? CodeLab.version : '0.1.7';
27233
+ const version = CodeLab ? CodeLab.version : '0.1.9';
24180
27234
  const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
24181
27235
  const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
24182
27236
  const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;
24183
27237
  const extensions = CodeLab ? CodeLab.extensions : null;
27238
+ const CodeLabError = CodeLabLogger.CodeLabError;
27239
+ const isCodeLabError = CodeLabLogger.isCodeLabError;
27240
+ const createLogger = CodeLabLogger.createLogger;
27241
+ const DEFAULT_LOGGER = CodeLabLogger.DEFAULT_LOGGER;
27242
+ const LOG_PREFIX = CodeLabLogger.LOG_PREFIX;
27243
+ const Logger = CodeLab ? CodeLab.Logger : CodeLabLogger;
27244
+ const html = CodeLabHtml.html;
27245
+ const raw = CodeLabHtml.raw;
27246
+ const isSafeHtml = CodeLabHtml.isSafeHtml;
27247
+ const escapeHtml = CodeLabHtml.escapeHtml;
27248
+ const Html = CodeLab ? CodeLab.Html : CodeLabHtml;
27249
+ const zip = CodeLabZip;
27250
+ const createZip = CodeLabZip.createZip;
27251
+ const extractZip = CodeLabZip.extractZip;
27252
+ const computeCrc32 = CodeLabZip.computeCrc32;
27253
+ const sanitizeZipPath = CodeLabZip.sanitizeZipPath;
27254
+ const storage = CodeLabStorage;
27255
+ const WorkspaceStorage = CodeLabStorage.WorkspaceStorage;
27256
+ const createWorkspaceStorage = CodeLabStorage.createWorkspaceStorage;
27257
+ const search = CodeLabSearch;
27258
+ const searchInFiles = CodeLabSearch.searchInFiles;
27259
+ const replaceInFiles = CodeLabSearch.replaceInFiles;
27260
+ const matchesGlob = CodeLabSearch.matchesGlob;
27261
+ const escapeRegex = CodeLabSearch.escapeRegex;
27262
+ const normalizeSearchPath = CodeLabSearch.normalizeSearchPath;
27263
+ const diagnostics = CodeLabDiagnostics;
27264
+ const DiagnosticsStore = CodeLabDiagnostics.DiagnosticsStore;
27265
+ const createDiagnosticsStore = CodeLabDiagnostics.createDiagnosticsStore;
27266
+ const scm = CodeLabScm;
27267
+ const createGitState = CodeLabScm.createGitState;
27268
+ const computeGitStatus = CodeLabScm.computeGitStatus;
27269
+ const stageFile = CodeLabScm.stageFile;
27270
+ const unstageFile = CodeLabScm.unstageFile;
27271
+ const commitChanges = CodeLabScm.commitChanges;
27272
+ const computeShortCommitHash = CodeLabScm.computeShortCommitHash;
24184
27273
 
24185
27274
  export {
24186
27275
  CodeLab,
@@ -24201,6 +27290,49 @@ export {
24201
27290
  renderSimpleMarkdown,
24202
27291
  cloneRepo,
24203
27292
  extensions,
27293
+ CodeLabCsp,
27294
+ CodeLabLogger,
27295
+ Logger,
27296
+ CodeLabHtml,
27297
+ Html,
27298
+ html,
27299
+ raw,
27300
+ isSafeHtml,
27301
+ escapeHtml,
27302
+ CodeLabError,
27303
+ isCodeLabError,
27304
+ createLogger,
27305
+ DEFAULT_LOGGER,
27306
+ LOG_PREFIX,
27307
+ CodeLabZip,
27308
+ zip,
27309
+ createZip,
27310
+ extractZip,
27311
+ computeCrc32,
27312
+ sanitizeZipPath,
27313
+ CodeLabStorage,
27314
+ storage,
27315
+ WorkspaceStorage,
27316
+ createWorkspaceStorage,
27317
+ CodeLabSearch,
27318
+ search,
27319
+ searchInFiles,
27320
+ replaceInFiles,
27321
+ matchesGlob,
27322
+ escapeRegex,
27323
+ normalizeSearchPath,
27324
+ CodeLabDiagnostics,
27325
+ diagnostics,
27326
+ DiagnosticsStore,
27327
+ createDiagnosticsStore,
27328
+ CodeLabScm,
27329
+ scm,
27330
+ createGitState,
27331
+ computeGitStatus,
27332
+ stageFile,
27333
+ unstageFile,
27334
+ commitChanges,
27335
+ computeShortCommitHash,
24204
27336
  createPosixShell,
24205
27337
  cloneGitHubRepository,
24206
27338
  parseGitHubRepoUrl,
@@ -24216,6 +27348,7 @@ export {
24216
27348
  createVirtualFs,
24217
27349
  createVirtualHttp,
24218
27350
  createVirtualNet,
24219
- createVirtualPortTable
27351
+ createVirtualPortTable,
27352
+ createWorkerRuntimeSource
24220
27353
  };
24221
27354
  export default CodeLab;