@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.
package/dist/code-lab.js CHANGED
@@ -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
@@ -17,6 +17,1870 @@
17
17
  (function (root) {
18
18
  'use strict';
19
19
 
20
+ // --- Module 0: Preview CSP, Structured Logger, Safe HTML & Leaf Engines ---
21
+ var CodeLabCsp = (() => {
22
+ var __defProp = Object.defineProperty;
23
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
24
+ var __getOwnPropNames = Object.getOwnPropertyNames;
25
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
26
+ var __export = (target, all) => {
27
+ for (var name in all)
28
+ __defProp(target, name, { get: all[name], enumerable: true });
29
+ };
30
+ var __copyProps = (to, from, except, desc) => {
31
+ if (from && typeof from === "object" || typeof from === "function") {
32
+ for (let key of __getOwnPropNames(from))
33
+ if (!__hasOwnProp.call(to, key) && key !== except)
34
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
35
+ }
36
+ return to;
37
+ };
38
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
39
+
40
+ // src/csp.ts
41
+ var csp_exports = {};
42
+ __export(csp_exports, {
43
+ PREVIEW_SHIM_MARKER: () => PREVIEW_SHIM_MARKER,
44
+ buildPreviewPolicy: () => buildPreviewPolicy,
45
+ buildPreviewShims: () => buildPreviewShims,
46
+ default: () => csp_default,
47
+ describePreviewNetwork: () => describePreviewNetwork,
48
+ normalizeOrigin: () => normalizeOrigin,
49
+ normalizePreviewCspConfig: () => normalizePreviewCspConfig
50
+ });
51
+ var IMPORT_MAP_CDNS = ["https://cdn.jsdelivr.net", "https://esm.sh"];
52
+ var FONT_CDNS = ["https://cdn.jsdelivr.net", "https://fonts.gstatic.com"];
53
+ var PRESETS = {
54
+ strict: {},
55
+ balanced: {
56
+ scriptSrc: IMPORT_MAP_CDNS.slice(),
57
+ styleSrc: ["https://cdn.jsdelivr.net", "https://fonts.googleapis.com"],
58
+ fontSrc: FONT_CDNS.slice(),
59
+ connectSrc: IMPORT_MAP_CDNS.slice(),
60
+ imgSrc: ["https://cdn.jsdelivr.net"]
61
+ }
62
+ };
63
+ var SOURCE_KEYS = [
64
+ "scriptSrc",
65
+ "styleSrc",
66
+ "imgSrc",
67
+ "fontSrc",
68
+ "connectSrc",
69
+ "mediaSrc",
70
+ "workerSrc",
71
+ "frameSrc"
72
+ ];
73
+ var MAX_SOURCES = 64;
74
+ var MAX_SOURCE_LENGTH = 512;
75
+ var PREVIEW_SHIM_MARKER = "data-codelab-preview-shims";
76
+ function normalizeOrigin(raw) {
77
+ if (raw === null || raw === void 0 || raw === "") return null;
78
+ try {
79
+ const parsed = new URL(String(raw));
80
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
81
+ return parsed.origin;
82
+ } catch (_) {
83
+ return null;
84
+ }
85
+ }
86
+ function normalizeMode(raw) {
87
+ if (raw === "strict" || raw === "custom") return raw;
88
+ return "balanced";
89
+ }
90
+ var ALLOWED_KEYWORDS = [
91
+ "'self'",
92
+ "'none'",
93
+ "'unsafe-inline'",
94
+ "'unsafe-eval'",
95
+ "'wasm-unsafe-eval'",
96
+ "'strict-dynamic'",
97
+ "'unsafe-hashes'"
98
+ ];
99
+ var SOURCE_PATTERN = /^(?:https?:\/\/[A-Za-z0-9._~%-]+(?::\d{1,5})?(?:\/[^\s;,'"]*)?|data:|blob:|filesystem:)$/;
100
+ function isSafeSource(source) {
101
+ return ALLOWED_KEYWORDS.indexOf(source) !== -1 || SOURCE_PATTERN.test(source);
102
+ }
103
+ function cleanSources(raw) {
104
+ if (!Array.isArray(raw)) return [];
105
+ const out = [];
106
+ for (const value of raw.slice(0, MAX_SOURCES)) {
107
+ if (typeof value !== "string") continue;
108
+ const source = value.trim();
109
+ if (!source || source.length > MAX_SOURCE_LENGTH) continue;
110
+ if (!isSafeSource(source)) continue;
111
+ if (out.indexOf(source) === -1) out.push(source);
112
+ }
113
+ return out;
114
+ }
115
+ function unique(...lists) {
116
+ const out = [];
117
+ for (const list of lists) {
118
+ if (!list) continue;
119
+ for (const value of list) {
120
+ if (value && out.indexOf(value) === -1) out.push(value);
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ function normalizePreviewCspConfig(raw) {
126
+ if (typeof raw === "string") return { mode: normalizeMode(raw), allow: {} };
127
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
128
+ return { mode: "balanced", allow: {} };
129
+ }
130
+ const input = raw;
131
+ const nested = input.allow;
132
+ const sources = nested && typeof nested === "object" && !Array.isArray(nested) ? nested : input;
133
+ const allow = {};
134
+ for (const key of SOURCE_KEYS) {
135
+ const list = cleanSources(sources[key]);
136
+ if (list.length) allow[key] = list;
137
+ }
138
+ return { mode: normalizeMode(input.mode), allow };
139
+ }
140
+ function sourcesFor(mode, allow, key) {
141
+ const preset = mode === "custom" ? {} : PRESETS[mode];
142
+ return unique(preset[key], cleanSources(allow[key]));
143
+ }
144
+ function buildPreviewPolicy(options = {}) {
145
+ const mode = normalizeMode(options.mode);
146
+ const allow = options;
147
+ const host = normalizeOrigin(options.hostOrigin);
148
+ const self = host || "'self'";
149
+ const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
150
+ const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
151
+ const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
152
+ const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
153
+ return [
154
+ directive("default-src", [self, "data:", "blob:"]),
155
+ directive("base-uri", [self]),
156
+ "object-src 'none'",
157
+ directive("script-src", script()),
158
+ directive("style-src", style()),
159
+ directive("img-src", withData("imgSrc")),
160
+ directive("font-src", [self, "data:"].concat(sourcesFor(mode, allow, "fontSrc"))),
161
+ directive("connect-src", withData("connectSrc")),
162
+ directive("media-src", withData("mediaSrc")),
163
+ directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
164
+ directive("frame-src", withData("frameSrc")),
165
+ directive("form-action", [self]),
166
+ directive("frame-ancestors", [options.frameAncestors || "'self'"])
167
+ ].join("; ");
168
+ }
169
+ function describePreviewNetwork(config) {
170
+ const normalized = normalizePreviewCspConfig(config);
171
+ if (normalized.mode === "strict") return [];
172
+ const preset = normalized.mode === "custom" ? {} : PRESETS[normalized.mode];
173
+ const hosts = [];
174
+ for (const key of ["scriptSrc", "connectSrc", "imgSrc", "styleSrc", "fontSrc"]) {
175
+ for (const source of unique(preset[key], normalized.allow[key])) {
176
+ if (!/^https?:\/\//i.test(source)) continue;
177
+ let host;
178
+ try {
179
+ host = new URL(source).host;
180
+ } catch (_) {
181
+ continue;
182
+ }
183
+ if (hosts.indexOf(host) === -1) hosts.push(host);
184
+ }
185
+ }
186
+ return hosts;
187
+ }
188
+ function buildPreviewShims() {
189
+ return `<script ${PREVIEW_SHIM_MARKER}>
190
+ (function () {
191
+ 'use strict';
192
+ function memoryStorage() {
193
+ var data = new Map();
194
+ return {
195
+ getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
196
+ setItem: function (k, v) { data.set(String(k), String(v)); },
197
+ removeItem: function (k) { data.delete(String(k)); },
198
+ clear: function () { data.clear(); },
199
+ key: function (i) { return Array.from(data.keys())[i] || null; },
200
+ get length() { return data.size; }
201
+ };
202
+ }
203
+ function shim(name) {
204
+ var blocked = false;
205
+ try {
206
+ var existing = window[name];
207
+ if (existing) { existing.getItem('__codelab_probe__'); return; }
208
+ } catch (err) {
209
+ // Expected on an opaque origin: the accessor itself throws.
210
+ blocked = Boolean(err);
211
+ }
212
+ void blocked;
213
+ try {
214
+ Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
215
+ } catch (err) {
216
+ console.warn('[code-lab] preview: unable to shim ' + name, err);
217
+ }
218
+ }
219
+ shim('localStorage');
220
+ shim('sessionStorage');
221
+ document.addEventListener('securitypolicyviolation', function (event) {
222
+ try {
223
+ parent.postMessage({
224
+ type: 'codelab:preview-violation',
225
+ directive: event.effectiveDirective || event.violatedDirective || '',
226
+ blockedURI: event.blockedURI || '',
227
+ sourceFile: event.sourceFile || '',
228
+ line: event.lineNumber || 0
229
+ }, '*');
230
+ } catch (err) {
231
+ console.warn('[code-lab] preview: could not report CSP violation', err);
232
+ }
233
+ });
234
+ function serializeArg(arg) {
235
+ if (typeof arg !== 'object' || arg === null) return String(arg);
236
+ try {
237
+ return JSON.stringify(arg);
238
+ } catch (err) {
239
+ void err;
240
+ return '[Circular/Unserializable]';
241
+ }
242
+ }
243
+ ['log', 'warn', 'error', 'info'].forEach(function (level) {
244
+ var orig = console[level];
245
+ if (typeof orig !== 'function') return;
246
+ console[level] = function () {
247
+ var args = Array.prototype.slice.call(arguments);
248
+ try {
249
+ parent.postMessage({
250
+ type: 'codelab:preview-console',
251
+ level: level,
252
+ args: args.map(serializeArg)
253
+ }, '*');
254
+ } catch (err) {
255
+ void err;
256
+ }
257
+ return orig.apply(console, args);
258
+ };
259
+ });
260
+ function showPreviewErrorOverlay(msg, stack) {
261
+ try {
262
+ if (!document || !document.body) return;
263
+ var existing = document.getElementById('codelab-preview-error-overlay');
264
+ if (!existing) {
265
+ existing = document.createElement('div');
266
+ existing.id = 'codelab-preview-error-overlay';
267
+ 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;';
268
+ document.body.appendChild(existing);
269
+ }
270
+ existing.textContent = '';
271
+ var topBar = document.createElement('div');
272
+ 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);';
273
+ var header = document.createElement('div');
274
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
275
+ header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
276
+ var closeBtn = document.createElement('button');
277
+ closeBtn.type = 'button';
278
+ closeBtn.textContent = 'Dismiss \xD7';
279
+ 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;';
280
+ closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
281
+ topBar.appendChild(header);
282
+ topBar.appendChild(closeBtn);
283
+ var pre = document.createElement('pre');
284
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
285
+ pre.textContent = String(stack || msg || '');
286
+ existing.appendChild(topBar);
287
+ existing.appendChild(pre);
288
+ } catch (err) {
289
+ void err;
290
+ }
291
+ }
292
+ window.addEventListener('error', function (event) {
293
+ var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
294
+ var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
295
+ showPreviewErrorOverlay(msg, stack);
296
+ try {
297
+ parent.postMessage({
298
+ type: 'codelab:preview-error',
299
+ message: msg,
300
+ file: (event && event.filename) || null,
301
+ line: (event && event.lineno) || null,
302
+ col: (event && event.colno) || null,
303
+ stack: stack || null
304
+ }, '*');
305
+ } catch (err) {
306
+ void err;
307
+ }
308
+ });
309
+ window.addEventListener('unhandledrejection', function (event) {
310
+ var reason = event ? event.reason : null;
311
+ var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
312
+ var stack = reason && reason.stack ? String(reason.stack) : '';
313
+ showPreviewErrorOverlay(msg, stack);
314
+ try {
315
+ parent.postMessage({
316
+ type: 'codelab:preview-error',
317
+ message: msg,
318
+ file: null,
319
+ line: null,
320
+ col: null,
321
+ stack: stack || null
322
+ }, '*');
323
+ } catch (err) {
324
+ void err;
325
+ }
326
+ });
327
+
328
+ // Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
329
+ var pendingFetches = new Map();
330
+ var fetchSeq = 0;
331
+ function parseLoopbackTarget(rawUrl) {
332
+ if (!rawUrl || typeof rawUrl !== 'string') return null;
333
+ var trimmed = rawUrl.trim();
334
+ if (!trimmed) return null;
335
+ var lower = trimmed.toLowerCase();
336
+ 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;
337
+ if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
338
+ try {
339
+ var u = new URL(trimmed);
340
+ if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
341
+ return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
342
+ }
343
+ if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
344
+ var rest = u.pathname.slice('/__preview/'.length);
345
+ var slashIdx = rest.indexOf('/');
346
+ var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
347
+ var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
348
+ var portNum = Number(portStr);
349
+ if (portNum > 0) {
350
+ return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
351
+ }
352
+ }
353
+ } catch (e) { void e; }
354
+ return null;
355
+ }
356
+ if (trimmed.indexOf('/__preview/') === 0) {
357
+ var restRel = trimmed.slice('/__preview/'.length);
358
+ var sIdx = restRel.indexOf('/');
359
+ var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
360
+ var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
361
+ var pNum = Number(pStr);
362
+ if (pNum > 0) {
363
+ return { port: pNum, path: sPath || '/' };
364
+ }
365
+ }
366
+ var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
367
+ var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
368
+ return { port: null, path: pathPart };
369
+ }
370
+
371
+ window.addEventListener('message', function (event) {
372
+ var data = event && event.data;
373
+ if (!data || typeof data !== 'object') return;
374
+ if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
375
+ var entry = pendingFetches.get(data.reqId);
376
+ if (!entry) return;
377
+ pendingFetches.delete(data.reqId);
378
+ entry.resolve(data);
379
+ }
380
+ });
381
+
382
+ if (typeof window.fetch === 'function') {
383
+ var origFetch = window.fetch.bind(window);
384
+ window.fetch = function (input, init) {
385
+ var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
386
+ var target = parseLoopbackTarget(urlStr);
387
+ // Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
388
+ var isOpaque = false;
389
+ try {
390
+ var lowerUrl = urlStr.toLowerCase();
391
+ var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
392
+ isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
393
+ } catch (e) { isOpaque = true; void e; }
394
+ if (!target || !isOpaque || window.parent === window) {
395
+ return origFetch(input, init);
396
+ }
397
+ return new Promise(function (resolve, reject) {
398
+ var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
399
+ var method = (init && init.method) || (input && input.method) || 'GET';
400
+ var headersObj = {};
401
+ try {
402
+ var rawH = (init && init.headers) || (input && input.headers);
403
+ if (rawH) {
404
+ if (typeof rawH.forEach === 'function') {
405
+ rawH.forEach(function (v, k) { headersObj[k] = v; });
406
+ } else if (Array.isArray(rawH)) {
407
+ rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
408
+ } else if (typeof rawH === 'object') {
409
+ Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
410
+ }
411
+ }
412
+ } catch (e) { void e; }
413
+ var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
414
+ var timer = setTimeout(function () {
415
+ if (pendingFetches.has(reqId)) {
416
+ pendingFetches.delete(reqId);
417
+ origFetch(input, init).then(resolve, reject);
418
+ }
419
+ }, 5000);
420
+ pendingFetches.set(reqId, {
421
+ resolve: function (payload) {
422
+ clearTimeout(timer);
423
+ if (payload && payload.error) {
424
+ reject(new TypeError(String(payload.error)));
425
+ return;
426
+ }
427
+ var status = Number(payload && payload.status) || 200;
428
+ var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
429
+ var body = payload && payload.body !== undefined ? String(payload.body) : '';
430
+ try {
431
+ resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
432
+ } catch (err) {
433
+ void err;
434
+ resolve({
435
+ ok: status >= 200 && status < 300,
436
+ status: status,
437
+ headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
438
+ text: function () { return Promise.resolve(body); },
439
+ json: function () { return Promise.resolve(JSON.parse(body)); }
440
+ });
441
+ }
442
+ }
443
+ });
444
+ try {
445
+ parent.postMessage({
446
+ type: 'codelab:preview-fetch',
447
+ reqId: reqId,
448
+ port: target.port,
449
+ path: target.path,
450
+ method: String(method).toUpperCase(),
451
+ headers: headersObj,
452
+ body: bodyStr
453
+ }, '*');
454
+ } catch (err) {
455
+ clearTimeout(timer);
456
+ pendingFetches.delete(reqId);
457
+ origFetch(input, init).then(resolve, reject);
458
+ }
459
+ });
460
+ };
461
+ }
462
+
463
+ // Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
464
+ document.addEventListener('click', function (event) {
465
+ if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
466
+ var el = event.target;
467
+ while (el && el.tagName !== 'A') el = el.parentElement;
468
+ if (!el || !el.getAttribute) return;
469
+ var href = el.getAttribute('href');
470
+ var targetAttr = el.getAttribute('target');
471
+ if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
472
+ var lowerHref = href.toLowerCase();
473
+ 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;
474
+ var parsed = parseLoopbackTarget(href);
475
+ if (!parsed) return;
476
+ event.preventDefault();
477
+ try {
478
+ parent.postMessage({
479
+ type: 'codelab:preview-navigate',
480
+ port: parsed.port,
481
+ path: parsed.path
482
+ }, '*');
483
+ } catch (e) { void e; }
484
+ });
485
+
486
+ // Sync SPA history.pushState / replaceState with the preview omni-address bar
487
+ try {
488
+ ['pushState', 'replaceState'].forEach(function (method) {
489
+ var orig = history[method];
490
+ if (typeof orig !== 'function') return;
491
+ history[method] = function (state, title, url) {
492
+ var ret;
493
+ try { ret = orig.apply(history, arguments); } catch (e) { void e; }
494
+ if (url !== undefined && url !== null) {
495
+ var parsed = parseLoopbackTarget(String(url));
496
+ if (parsed) {
497
+ try {
498
+ parent.postMessage({
499
+ type: 'codelab:preview-url-change',
500
+ path: parsed.path,
501
+ replace: method === 'replaceState'
502
+ }, '*');
503
+ } catch (e) { void e; }
504
+ }
505
+ }
506
+ return ret;
507
+ };
508
+ });
509
+ } catch (e) { void e; }
510
+ })();
511
+ <\/script>`;
512
+ }
513
+ var csp_default = {
514
+ buildPreviewPolicy,
515
+ buildPreviewShims,
516
+ describePreviewNetwork,
517
+ normalizePreviewCspConfig,
518
+ normalizeOrigin,
519
+ PREVIEW_SHIM_MARKER
520
+ };
521
+ return __toCommonJS(csp_exports);
522
+ })();
523
+
524
+ var CodeLabLogger = (() => {
525
+ var __defProp = Object.defineProperty;
526
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
527
+ var __getOwnPropNames = Object.getOwnPropertyNames;
528
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
529
+ var __export = (target, all) => {
530
+ for (var name in all)
531
+ __defProp(target, name, { get: all[name], enumerable: true });
532
+ };
533
+ var __copyProps = (to, from, except, desc) => {
534
+ if (from && typeof from === "object" || typeof from === "function") {
535
+ for (let key of __getOwnPropNames(from))
536
+ if (!__hasOwnProp.call(to, key) && key !== except)
537
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
538
+ }
539
+ return to;
540
+ };
541
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
542
+
543
+ // src/logger.ts
544
+ var logger_exports = {};
545
+ __export(logger_exports, {
546
+ CodeLabError: () => CodeLabError,
547
+ DEFAULT_LOGGER: () => DEFAULT_LOGGER,
548
+ LOG_PREFIX: () => LOG_PREFIX,
549
+ createLogger: () => createLogger,
550
+ default: () => logger_default,
551
+ isCodeLabError: () => isCodeLabError
552
+ });
553
+ var LOG_PREFIX = "[code-lab]";
554
+ var CodeLabError = class extends Error {
555
+ code;
556
+ options;
557
+ cause;
558
+ recoverable;
559
+ details;
560
+ context;
561
+ constructor(code, message, options = {}) {
562
+ super(message);
563
+ this.name = "CodeLabError";
564
+ this.code = code;
565
+ this.options = options;
566
+ this.cause = options.cause;
567
+ this.recoverable = options.recoverable !== false;
568
+ const meta = options.details ?? options.context;
569
+ if (meta !== void 0) {
570
+ this.details = meta;
571
+ this.context = meta;
572
+ }
573
+ Object.setPrototypeOf(this, new.target.prototype);
574
+ }
575
+ };
576
+ function isCodeLabError(value) {
577
+ return Boolean(
578
+ value && typeof value === "object" && (value instanceof CodeLabError || value.name === "CodeLabError" && typeof value.code === "string")
579
+ );
580
+ }
581
+ function createLogger(options = {}) {
582
+ const sink = options.logger ?? null;
583
+ const debugEnabled = options.debug === true;
584
+ const prefix = options.prefix || LOG_PREFIX;
585
+ const write = (level, args) => {
586
+ if (level === "debug" && !debugEnabled) return;
587
+ if (sink && typeof sink[level] === "function") {
588
+ let sinkError = null;
589
+ try {
590
+ sink[level](...args);
591
+ return;
592
+ } catch (err) {
593
+ sinkError = err;
594
+ }
595
+ }
596
+ const consoleObj = typeof console !== "undefined" ? console : null;
597
+ const fn = consoleObj ? consoleObj[level] : null;
598
+ if (typeof fn === "function") {
599
+ fn.call(consoleObj, prefix, ...args);
600
+ }
601
+ };
602
+ return {
603
+ debug: (...args) => write("debug", args),
604
+ info: (...args) => write("info", args),
605
+ warn: (...args) => write("warn", args),
606
+ error: (...args) => write("error", args)
607
+ };
608
+ }
609
+ var DEFAULT_LOGGER = createLogger();
610
+ var _loggerNamespace = {
611
+ LOG_PREFIX,
612
+ CodeLabError,
613
+ isCodeLabError,
614
+ createLogger,
615
+ DEFAULT_LOGGER
616
+ };
617
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
618
+ if (_globalRoot && !_globalRoot.CodeLabLogger) {
619
+ _globalRoot.CodeLabLogger = _loggerNamespace;
620
+ }
621
+ var logger_default = _loggerNamespace;
622
+ return __toCommonJS(logger_exports);
623
+ })();
624
+
625
+ var CodeLabHtml = (() => {
626
+ var __defProp = Object.defineProperty;
627
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
628
+ var __getOwnPropNames = Object.getOwnPropertyNames;
629
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
630
+ var __export = (target, all) => {
631
+ for (var name in all)
632
+ __defProp(target, name, { get: all[name], enumerable: true });
633
+ };
634
+ var __copyProps = (to, from, except, desc) => {
635
+ if (from && typeof from === "object" || typeof from === "function") {
636
+ for (let key of __getOwnPropNames(from))
637
+ if (!__hasOwnProp.call(to, key) && key !== except)
638
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
639
+ }
640
+ return to;
641
+ };
642
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
643
+
644
+ // src/html.ts
645
+ var html_exports = {};
646
+ __export(html_exports, {
647
+ default: () => html_default,
648
+ escapeHtml: () => escapeHtml,
649
+ html: () => html,
650
+ isSafeHtml: () => isSafeHtml,
651
+ raw: () => raw
652
+ });
653
+ var SAFE_HTML_BRAND = Symbol.for("codelab.SafeHtml");
654
+ var SafeHtmlImpl = class {
655
+ [SAFE_HTML_BRAND] = true;
656
+ __html;
657
+ constructor(trusted) {
658
+ this.__html = String(trusted);
659
+ }
660
+ toString() {
661
+ return this.__html;
662
+ }
663
+ };
664
+ function isSafeHtml(value) {
665
+ return Boolean(
666
+ value && typeof value === "object" && value[SAFE_HTML_BRAND] === true && typeof value.__html === "string"
667
+ );
668
+ }
669
+ function escapeHtml(value) {
670
+ if (value === null || value === void 0) return "";
671
+ if (isSafeHtml(value)) return value.__html;
672
+ return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
673
+ }
674
+ function raw(trustedHtml) {
675
+ return new SafeHtmlImpl(trustedHtml);
676
+ }
677
+ function renderInterpolation(value) {
678
+ if (value === null || value === void 0 || value === false) return "";
679
+ if (isSafeHtml(value)) return value.__html;
680
+ if (Array.isArray(value)) {
681
+ let out = "";
682
+ for (let i = 0; i < value.length; i++) {
683
+ out += renderInterpolation(value[i]);
684
+ }
685
+ return out;
686
+ }
687
+ return escapeHtml(value);
688
+ }
689
+ function html(strings, ...values) {
690
+ let out = strings[0] ?? "";
691
+ for (let i = 0; i < values.length; i++) {
692
+ out += renderInterpolation(values[i]);
693
+ out += strings[i + 1] ?? "";
694
+ }
695
+ return new SafeHtmlImpl(out);
696
+ }
697
+ var _htmlNamespace = {
698
+ escapeHtml,
699
+ raw,
700
+ isSafeHtml,
701
+ html
702
+ };
703
+ var _globalRoot = typeof globalThis !== "undefined" ? globalThis : null;
704
+ if (_globalRoot && !_globalRoot.CodeLabHtml) {
705
+ _globalRoot.CodeLabHtml = _htmlNamespace;
706
+ }
707
+ var html_default = _htmlNamespace;
708
+ return __toCommonJS(html_exports);
709
+ })();
710
+
711
+ var CodeLabZip = (() => {
712
+ var __defProp = Object.defineProperty;
713
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
714
+ var __getOwnPropNames = Object.getOwnPropertyNames;
715
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
716
+ var __export = (target, all) => {
717
+ for (var name in all)
718
+ __defProp(target, name, { get: all[name], enumerable: true });
719
+ };
720
+ var __copyProps = (to, from, except, desc) => {
721
+ if (from && typeof from === "object" || typeof from === "function") {
722
+ for (let key of __getOwnPropNames(from))
723
+ if (!__hasOwnProp.call(to, key) && key !== except)
724
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
725
+ }
726
+ return to;
727
+ };
728
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
729
+
730
+ // src/zip.ts
731
+ var zip_exports = {};
732
+ __export(zip_exports, {
733
+ computeCrc32: () => computeCrc32,
734
+ createZip: () => createZip,
735
+ default: () => zip_default,
736
+ extractZip: () => extractZip,
737
+ sanitizeZipPath: () => sanitizeZipPath,
738
+ toUint8Array: () => toUint8Array
739
+ });
740
+ var LOCAL_FILE_HEADER_SIG = 67324752;
741
+ var CENTRAL_DIR_HEADER_SIG = 33639248;
742
+ var END_OF_CENTRAL_DIR_SIG = 101010256;
743
+ var UTF8_FLAG = 2048;
744
+ var CRC32_TABLE = new Uint32Array(256);
745
+ for (let i = 0; i < 256; i++) {
746
+ let c = i;
747
+ for (let k = 0; k < 8; k++) {
748
+ c = (c & 1) !== 0 ? 3988292384 ^ c >>> 1 : c >>> 1;
749
+ }
750
+ CRC32_TABLE[i] = c >>> 0;
751
+ }
752
+ var textEncoder = new TextEncoder();
753
+ var textDecoder = new TextDecoder("utf-8");
754
+ function toUint8Array(input) {
755
+ if (typeof input === "string") {
756
+ return textEncoder.encode(input);
757
+ }
758
+ if (input instanceof Uint8Array) {
759
+ return input;
760
+ }
761
+ if (input instanceof ArrayBuffer) {
762
+ return new Uint8Array(input);
763
+ }
764
+ return new Uint8Array(0);
765
+ }
766
+ function computeCrc32(data) {
767
+ const bytes = toUint8Array(data);
768
+ let crc = 4294967295;
769
+ for (let i = 0; i < bytes.length; i++) {
770
+ const index = (crc ^ bytes[i]) & 255;
771
+ crc = crc >>> 8 ^ CRC32_TABLE[index];
772
+ }
773
+ return (crc ^ 4294967295) >>> 0;
774
+ }
775
+ function sanitizeZipPath(rawPath) {
776
+ const normalized = String(rawPath || "").replace(/\\/g, "/").replace(/^[A-Za-z]:/, "");
777
+ const parts = normalized.split("/");
778
+ const safeParts = [];
779
+ for (const part of parts) {
780
+ const trimmed = part.trim();
781
+ if (!trimmed || trimmed === ".") continue;
782
+ if (trimmed === "..") {
783
+ if (safeParts.length > 0) {
784
+ safeParts.pop();
785
+ }
786
+ continue;
787
+ }
788
+ safeParts.push(trimmed);
789
+ }
790
+ return safeParts.join("/");
791
+ }
792
+ function writeUInt16LE(buf, offset, value) {
793
+ buf[offset] = value & 255;
794
+ buf[offset + 1] = value >>> 8 & 255;
795
+ }
796
+ function writeUInt32LE(buf, offset, value) {
797
+ buf[offset] = value & 255;
798
+ buf[offset + 1] = value >>> 8 & 255;
799
+ buf[offset + 2] = value >>> 16 & 255;
800
+ buf[offset + 3] = value >>> 24 & 255;
801
+ }
802
+ function readUInt16LE(buf, offset) {
803
+ return (buf[offset] | buf[offset + 1] << 8) >>> 0;
804
+ }
805
+ function readUInt32LE(buf, offset) {
806
+ return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
807
+ }
808
+ async function createZip(files) {
809
+ const entries = [];
810
+ let localSectionSize = 0;
811
+ let centralDirSize = 0;
812
+ const rawKeys = Object.keys(files || {});
813
+ for (const rawKey of rawKeys) {
814
+ const safePath = sanitizeZipPath(rawKey);
815
+ if (!safePath) continue;
816
+ const rawContent = files[rawKey];
817
+ const dataBytes = toUint8Array(rawContent);
818
+ const nameBytes = textEncoder.encode(safePath);
819
+ const crc = computeCrc32(dataBytes);
820
+ entries.push({
821
+ nameBytes,
822
+ dataBytes,
823
+ crc32: crc,
824
+ offset: localSectionSize
825
+ });
826
+ localSectionSize += 30 + nameBytes.length + dataBytes.length;
827
+ centralDirSize += 46 + nameBytes.length;
828
+ }
829
+ const totalSize = localSectionSize + centralDirSize + 22;
830
+ const out = new Uint8Array(totalSize);
831
+ let cursor = 0;
832
+ for (const entry of entries) {
833
+ writeUInt32LE(out, cursor, LOCAL_FILE_HEADER_SIG);
834
+ writeUInt16LE(out, cursor + 4, 20);
835
+ writeUInt16LE(out, cursor + 6, UTF8_FLAG);
836
+ writeUInt16LE(out, cursor + 8, 0);
837
+ writeUInt16LE(out, cursor + 10, 0);
838
+ writeUInt16LE(out, cursor + 12, 8448);
839
+ writeUInt32LE(out, cursor + 14, entry.crc32);
840
+ writeUInt32LE(out, cursor + 18, entry.dataBytes.length);
841
+ writeUInt32LE(out, cursor + 22, entry.dataBytes.length);
842
+ writeUInt16LE(out, cursor + 26, entry.nameBytes.length);
843
+ writeUInt16LE(out, cursor + 28, 0);
844
+ cursor += 30;
845
+ out.set(entry.nameBytes, cursor);
846
+ cursor += entry.nameBytes.length;
847
+ out.set(entry.dataBytes, cursor);
848
+ cursor += entry.dataBytes.length;
849
+ }
850
+ const centralDirOffset = cursor;
851
+ for (const entry of entries) {
852
+ writeUInt32LE(out, cursor, CENTRAL_DIR_HEADER_SIG);
853
+ writeUInt16LE(out, cursor + 4, 20);
854
+ writeUInt16LE(out, cursor + 6, 20);
855
+ writeUInt16LE(out, cursor + 8, UTF8_FLAG);
856
+ writeUInt16LE(out, cursor + 10, 0);
857
+ writeUInt16LE(out, cursor + 12, 0);
858
+ writeUInt16LE(out, cursor + 14, 8448);
859
+ writeUInt32LE(out, cursor + 16, entry.crc32);
860
+ writeUInt32LE(out, cursor + 20, entry.dataBytes.length);
861
+ writeUInt32LE(out, cursor + 24, entry.dataBytes.length);
862
+ writeUInt16LE(out, cursor + 28, entry.nameBytes.length);
863
+ writeUInt16LE(out, cursor + 30, 0);
864
+ writeUInt16LE(out, cursor + 32, 0);
865
+ writeUInt16LE(out, cursor + 34, 0);
866
+ writeUInt16LE(out, cursor + 36, 0);
867
+ writeUInt32LE(out, cursor + 38, 0);
868
+ writeUInt32LE(out, cursor + 42, entry.offset);
869
+ cursor += 46;
870
+ out.set(entry.nameBytes, cursor);
871
+ cursor += entry.nameBytes.length;
872
+ }
873
+ writeUInt32LE(out, cursor, END_OF_CENTRAL_DIR_SIG);
874
+ writeUInt16LE(out, cursor + 4, 0);
875
+ writeUInt16LE(out, cursor + 6, 0);
876
+ writeUInt16LE(out, cursor + 8, entries.length);
877
+ writeUInt16LE(out, cursor + 10, entries.length);
878
+ writeUInt32LE(out, cursor + 12, centralDirSize);
879
+ writeUInt32LE(out, cursor + 16, centralDirOffset);
880
+ writeUInt16LE(out, cursor + 20, 0);
881
+ return out;
882
+ }
883
+ async function extractZip(data) {
884
+ const bytes = toUint8Array(data);
885
+ if (bytes.length < 22) {
886
+ throw new Error("Invalid or truncated ZIP archive: buffer shorter than minimum 22-byte EOCD record");
887
+ }
888
+ let eocdOffset = -1;
889
+ const minSearchOffset = Math.max(0, bytes.length - 65557);
890
+ for (let i = bytes.length - 22; i >= minSearchOffset; i--) {
891
+ if (readUInt32LE(bytes, i) === END_OF_CENTRAL_DIR_SIG) {
892
+ eocdOffset = i;
893
+ break;
894
+ }
895
+ }
896
+ if (eocdOffset === -1) {
897
+ throw new Error("Invalid ZIP archive: End of Central Directory (PK\\x05\\x06) signature not found");
898
+ }
899
+ const totalEntries = readUInt16LE(bytes, eocdOffset + 10);
900
+ const centralDirSize = readUInt32LE(bytes, eocdOffset + 12);
901
+ const centralDirOffset = readUInt32LE(bytes, eocdOffset + 16);
902
+ if (centralDirOffset + centralDirSize > bytes.length) {
903
+ throw new Error("Corrupted ZIP archive: Central Directory extends past end of buffer");
904
+ }
905
+ const result = {};
906
+ let cdCursor = centralDirOffset;
907
+ for (let i = 0; i < totalEntries; i++) {
908
+ if (cdCursor + 46 > bytes.length) {
909
+ throw new Error("Corrupted ZIP archive: truncated Central Directory header");
910
+ }
911
+ const sig = readUInt32LE(bytes, cdCursor);
912
+ if (sig !== CENTRAL_DIR_HEADER_SIG) {
913
+ throw new Error(`Corrupted ZIP archive: invalid Central Directory signature 0x${sig.toString(16)}`);
914
+ }
915
+ const compressionMethod = readUInt16LE(bytes, cdCursor + 10);
916
+ const expectedCrc = readUInt32LE(bytes, cdCursor + 16);
917
+ const compressedSize = readUInt32LE(bytes, cdCursor + 20);
918
+ const fileNameLen = readUInt16LE(bytes, cdCursor + 28);
919
+ const extraLen = readUInt16LE(bytes, cdCursor + 30);
920
+ const commentLen = readUInt16LE(bytes, cdCursor + 32);
921
+ const localHeaderOffset = readUInt32LE(bytes, cdCursor + 42);
922
+ const nameStart = cdCursor + 46;
923
+ const nameEnd = nameStart + fileNameLen;
924
+ if (nameEnd > bytes.length) {
925
+ throw new Error("Corrupted ZIP archive: file name exceeds buffer");
926
+ }
927
+ const rawName = textDecoder.decode(bytes.subarray(nameStart, nameEnd));
928
+ cdCursor = nameEnd + extraLen + commentLen;
929
+ if (rawName.endsWith("/")) continue;
930
+ const safeName = sanitizeZipPath(rawName);
931
+ if (!safeName) continue;
932
+ if (localHeaderOffset + 30 > bytes.length) {
933
+ throw new Error(`Corrupted ZIP archive: local header offset out of bounds for ${safeName}`);
934
+ }
935
+ const localSig = readUInt32LE(bytes, localHeaderOffset);
936
+ if (localSig !== LOCAL_FILE_HEADER_SIG) {
937
+ throw new Error(`Corrupted ZIP archive: invalid Local File Header signature for ${safeName}`);
938
+ }
939
+ const localNameLen = readUInt16LE(bytes, localHeaderOffset + 26);
940
+ const localExtraLen = readUInt16LE(bytes, localHeaderOffset + 28);
941
+ const dataStart = localHeaderOffset + 30 + localNameLen + localExtraLen;
942
+ const dataEnd = dataStart + compressedSize;
943
+ if (dataEnd > bytes.length) {
944
+ throw new Error(`Corrupted ZIP archive: file data truncated for ${safeName}`);
945
+ }
946
+ const rawFileBytes = bytes.subarray(dataStart, dataEnd);
947
+ if (compressionMethod !== 0) {
948
+ throw new Error(`Unsupported ZIP compression method ${compressionMethod} for ${safeName} (only Store=0 is supported)`);
949
+ }
950
+ const actualCrc = computeCrc32(rawFileBytes);
951
+ if (actualCrc !== expectedCrc) {
952
+ throw new Error(
953
+ `CRC32 integrity mismatch for ${safeName}: expected 0x${expectedCrc.toString(16)}, got 0x${actualCrc.toString(16)}`
954
+ );
955
+ }
956
+ result[safeName] = textDecoder.decode(rawFileBytes);
957
+ }
958
+ return result;
959
+ }
960
+ var zip_default = {
961
+ createZip,
962
+ extractZip,
963
+ computeCrc32,
964
+ sanitizeZipPath,
965
+ toUint8Array
966
+ };
967
+ return __toCommonJS(zip_exports);
968
+ })();
969
+
970
+ var CodeLabStorage = (() => {
971
+ var __defProp = Object.defineProperty;
972
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
973
+ var __getOwnPropNames = Object.getOwnPropertyNames;
974
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
975
+ var __export = (target, all) => {
976
+ for (var name in all)
977
+ __defProp(target, name, { get: all[name], enumerable: true });
978
+ };
979
+ var __copyProps = (to, from, except, desc) => {
980
+ if (from && typeof from === "object" || typeof from === "function") {
981
+ for (let key of __getOwnPropNames(from))
982
+ if (!__hasOwnProp.call(to, key) && key !== except)
983
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
984
+ }
985
+ return to;
986
+ };
987
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
988
+
989
+ // src/storage.ts
990
+ var storage_exports = {};
991
+ __export(storage_exports, {
992
+ WorkspaceStorage: () => WorkspaceStorage,
993
+ createWorkspaceStorage: () => createWorkspaceStorage,
994
+ default: () => storage_default
995
+ });
996
+ var DEFAULT_DB_NAME = "codelab_workspace_db";
997
+ var DEFAULT_STORE_NAME = "projects";
998
+ var DEFAULT_LS_PREFIX = "codelab:project:";
999
+ function cloneProject(project) {
1000
+ const filesCopy = {};
1001
+ if (project.files && typeof project.files === "object") {
1002
+ for (const [k, v] of Object.entries(project.files)) {
1003
+ filesCopy[k] = String(v);
1004
+ }
1005
+ }
1006
+ return {
1007
+ id: String(project.id),
1008
+ name: String(project.name || project.id),
1009
+ files: filesCopy,
1010
+ updatedAt: typeof project.updatedAt === "number" ? project.updatedAt : Date.now(),
1011
+ ...project.createdAt !== void 0 ? { createdAt: project.createdAt } : {},
1012
+ ...project.entry !== void 0 ? { entry: project.entry } : {},
1013
+ ...project.testEntry !== void 0 ? { testEntry: project.testEntry } : {},
1014
+ ...project.version !== void 0 ? { version: project.version } : {}
1015
+ };
1016
+ }
1017
+ function isLocalStorageAvailable(prefix) {
1018
+ try {
1019
+ if (typeof globalThis === "undefined" || !("localStorage" in globalThis)) {
1020
+ return false;
1021
+ }
1022
+ const ls = globalThis.localStorage;
1023
+ if (!ls || typeof ls.getItem !== "function" || typeof ls.setItem !== "function") {
1024
+ return false;
1025
+ }
1026
+ const probeKey = `${prefix}__probe__`;
1027
+ ls.setItem(probeKey, "1");
1028
+ ls.removeItem(probeKey);
1029
+ return true;
1030
+ } catch (err) {
1031
+ const _ignored = err;
1032
+ return false;
1033
+ }
1034
+ }
1035
+ function isIndexedDbAvailable() {
1036
+ try {
1037
+ if (typeof globalThis === "undefined" || !("indexedDB" in globalThis)) {
1038
+ return false;
1039
+ }
1040
+ return Boolean(globalThis.indexedDB && typeof globalThis.indexedDB.open === "function");
1041
+ } catch (err) {
1042
+ const _ignored = err;
1043
+ return false;
1044
+ }
1045
+ }
1046
+ var WorkspaceStorage = class {
1047
+ dbName;
1048
+ storeName;
1049
+ storagePrefix;
1050
+ backendType;
1051
+ memoryStore = /* @__PURE__ */ new Map();
1052
+ dbPromise = null;
1053
+ constructor(options = {}) {
1054
+ this.dbName = options.dbName || DEFAULT_DB_NAME;
1055
+ this.storeName = options.storeName || DEFAULT_STORE_NAME;
1056
+ this.storagePrefix = options.storagePrefix || DEFAULT_LS_PREFIX;
1057
+ if (options.preferredBackend) {
1058
+ this.backendType = options.preferredBackend;
1059
+ } else if (isIndexedDbAvailable()) {
1060
+ this.backendType = "indexeddb";
1061
+ } else if (isLocalStorageAvailable(this.storagePrefix)) {
1062
+ this.backendType = "localstorage";
1063
+ } else {
1064
+ this.backendType = "memory";
1065
+ }
1066
+ }
1067
+ getBackendType() {
1068
+ return this.backendType;
1069
+ }
1070
+ openIdb() {
1071
+ if (this.dbPromise) return this.dbPromise;
1072
+ this.dbPromise = new Promise((resolve) => {
1073
+ try {
1074
+ const req = globalThis.indexedDB.open(this.dbName, 1);
1075
+ req.onupgradeneeded = () => {
1076
+ const db = req.result;
1077
+ if (!db.objectStoreNames.contains(this.storeName)) {
1078
+ db.createObjectStore(this.storeName, { keyPath: "id" });
1079
+ }
1080
+ };
1081
+ req.onsuccess = () => {
1082
+ resolve(req.result);
1083
+ };
1084
+ req.onerror = () => {
1085
+ resolve(null);
1086
+ };
1087
+ } catch (err) {
1088
+ const _ignored = err;
1089
+ resolve(null);
1090
+ }
1091
+ });
1092
+ return this.dbPromise;
1093
+ }
1094
+ downgradeFromIdb() {
1095
+ if (isLocalStorageAvailable(this.storagePrefix)) {
1096
+ this.backendType = "localstorage";
1097
+ } else {
1098
+ this.backendType = "memory";
1099
+ }
1100
+ }
1101
+ async saveProject(project) {
1102
+ if (!project || typeof project.id !== "string" || !project.id.trim()) {
1103
+ return false;
1104
+ }
1105
+ const normalized = cloneProject(project);
1106
+ this.memoryStore.set(normalized.id, normalized);
1107
+ if (this.backendType === "indexeddb") {
1108
+ const db = await this.openIdb();
1109
+ if (!db) {
1110
+ this.downgradeFromIdb();
1111
+ } else {
1112
+ const ok = await new Promise((resolve) => {
1113
+ try {
1114
+ const tx = db.transaction(this.storeName, "readwrite");
1115
+ const store = tx.objectStore(this.storeName);
1116
+ const req = store.put(normalized);
1117
+ req.onsuccess = () => resolve(true);
1118
+ req.onerror = () => resolve(false);
1119
+ } catch (err) {
1120
+ const _ignored = err;
1121
+ resolve(false);
1122
+ }
1123
+ });
1124
+ if (ok) return true;
1125
+ this.downgradeFromIdb();
1126
+ }
1127
+ }
1128
+ if (this.backendType === "localstorage") {
1129
+ try {
1130
+ const key = `${this.storagePrefix}${normalized.id}`;
1131
+ globalThis.localStorage.setItem(key, JSON.stringify(normalized));
1132
+ return true;
1133
+ } catch (err) {
1134
+ const _ignored = err;
1135
+ this.backendType = "memory";
1136
+ }
1137
+ }
1138
+ return true;
1139
+ }
1140
+ async loadProject(id) {
1141
+ if (!id || typeof id !== "string") return null;
1142
+ if (this.backendType === "indexeddb") {
1143
+ const db = await this.openIdb();
1144
+ if (!db) {
1145
+ this.downgradeFromIdb();
1146
+ } else {
1147
+ const found = await new Promise((resolve) => {
1148
+ try {
1149
+ const tx = db.transaction(this.storeName, "readonly");
1150
+ const store = tx.objectStore(this.storeName);
1151
+ const req = store.get(id);
1152
+ req.onsuccess = () => {
1153
+ const res = req.result;
1154
+ resolve(res ? cloneProject(res) : null);
1155
+ };
1156
+ req.onerror = () => resolve(null);
1157
+ } catch (err) {
1158
+ const _ignored = err;
1159
+ resolve(null);
1160
+ }
1161
+ });
1162
+ if (found) return found;
1163
+ }
1164
+ }
1165
+ if (this.backendType === "localstorage") {
1166
+ try {
1167
+ const raw = globalThis.localStorage.getItem(`${this.storagePrefix}${id}`);
1168
+ if (raw) {
1169
+ const parsed = JSON.parse(raw);
1170
+ if (parsed && typeof parsed.id === "string" && parsed.files && typeof parsed.files === "object") {
1171
+ return cloneProject(parsed);
1172
+ }
1173
+ }
1174
+ } catch (err) {
1175
+ const _ignored = err;
1176
+ }
1177
+ }
1178
+ const fromMem = this.memoryStore.get(id);
1179
+ return fromMem ? cloneProject(fromMem) : null;
1180
+ }
1181
+ async listProjects() {
1182
+ const byId = /* @__PURE__ */ new Map();
1183
+ const recordSummary = (proj) => {
1184
+ if (!proj || typeof proj.id !== "string") return;
1185
+ byId.set(proj.id, {
1186
+ id: proj.id,
1187
+ name: proj.name || proj.id,
1188
+ updatedAt: typeof proj.updatedAt === "number" ? proj.updatedAt : Date.now(),
1189
+ fileCount: proj.files && typeof proj.files === "object" ? Object.keys(proj.files).length : 0
1190
+ });
1191
+ };
1192
+ for (const p of this.memoryStore.values()) {
1193
+ recordSummary(p);
1194
+ }
1195
+ if (this.backendType === "indexeddb") {
1196
+ const db = await this.openIdb();
1197
+ if (db) {
1198
+ await new Promise((resolve) => {
1199
+ try {
1200
+ const tx = db.transaction(this.storeName, "readonly");
1201
+ const store = tx.objectStore(this.storeName);
1202
+ const req = store.getAll();
1203
+ req.onsuccess = () => {
1204
+ const items = Array.isArray(req.result) ? req.result : [];
1205
+ for (const item of items) {
1206
+ recordSummary(item);
1207
+ }
1208
+ resolve();
1209
+ };
1210
+ req.onerror = () => resolve();
1211
+ } catch (err) {
1212
+ const _ignored = err;
1213
+ resolve();
1214
+ }
1215
+ });
1216
+ }
1217
+ } else if (this.backendType === "localstorage") {
1218
+ try {
1219
+ const ls = globalThis.localStorage;
1220
+ for (let i = 0; i < ls.length; i++) {
1221
+ const key = ls.key(i);
1222
+ if (key && key.startsWith(this.storagePrefix)) {
1223
+ const raw = ls.getItem(key);
1224
+ if (raw) {
1225
+ try {
1226
+ const parsed = JSON.parse(raw);
1227
+ recordSummary(parsed);
1228
+ } catch (parseErr) {
1229
+ const _ignored = parseErr;
1230
+ }
1231
+ }
1232
+ }
1233
+ }
1234
+ } catch (err) {
1235
+ const _ignored = err;
1236
+ }
1237
+ }
1238
+ return Array.from(byId.values()).sort((a, b) => b.updatedAt - a.updatedAt);
1239
+ }
1240
+ async deleteProject(id) {
1241
+ if (!id || typeof id !== "string") return false;
1242
+ let existed = this.memoryStore.delete(id);
1243
+ if (this.backendType === "indexeddb") {
1244
+ const db = await this.openIdb();
1245
+ if (db) {
1246
+ const idbDeleted = await new Promise((resolve) => {
1247
+ try {
1248
+ const tx = db.transaction(this.storeName, "readwrite");
1249
+ const store = tx.objectStore(this.storeName);
1250
+ const checkReq = store.get(id);
1251
+ checkReq.onsuccess = () => {
1252
+ if (!checkReq.result) {
1253
+ resolve(false);
1254
+ return;
1255
+ }
1256
+ const delReq = store.delete(id);
1257
+ delReq.onsuccess = () => resolve(true);
1258
+ delReq.onerror = () => resolve(false);
1259
+ };
1260
+ checkReq.onerror = () => resolve(false);
1261
+ } catch (err) {
1262
+ const _ignored = err;
1263
+ resolve(false);
1264
+ }
1265
+ });
1266
+ existed = existed || idbDeleted;
1267
+ }
1268
+ }
1269
+ if (this.backendType === "localstorage") {
1270
+ try {
1271
+ const key = `${this.storagePrefix}${id}`;
1272
+ if (globalThis.localStorage.getItem(key) !== null) {
1273
+ globalThis.localStorage.removeItem(key);
1274
+ existed = true;
1275
+ }
1276
+ } catch (err) {
1277
+ const _ignored = err;
1278
+ }
1279
+ }
1280
+ return existed;
1281
+ }
1282
+ };
1283
+ function createWorkspaceStorage(options = {}) {
1284
+ return new WorkspaceStorage(options);
1285
+ }
1286
+ var storage_default = {
1287
+ WorkspaceStorage,
1288
+ createWorkspaceStorage
1289
+ };
1290
+ return __toCommonJS(storage_exports);
1291
+ })();
1292
+
1293
+ var CodeLabSearch = (() => {
1294
+ var __defProp = Object.defineProperty;
1295
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1296
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1297
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1298
+ var __export = (target, all) => {
1299
+ for (var name in all)
1300
+ __defProp(target, name, { get: all[name], enumerable: true });
1301
+ };
1302
+ var __copyProps = (to, from, except, desc) => {
1303
+ if (from && typeof from === "object" || typeof from === "function") {
1304
+ for (let key of __getOwnPropNames(from))
1305
+ if (!__hasOwnProp.call(to, key) && key !== except)
1306
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1307
+ }
1308
+ return to;
1309
+ };
1310
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1311
+
1312
+ // src/search.ts
1313
+ var search_exports = {};
1314
+ __export(search_exports, {
1315
+ escapeRegex: () => escapeRegex,
1316
+ matchesGlob: () => matchesGlob,
1317
+ normalizeSearchPath: () => normalizeSearchPath,
1318
+ replaceInFiles: () => replaceInFiles,
1319
+ searchInFiles: () => searchInFiles
1320
+ });
1321
+ function escapeRegex(text) {
1322
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1323
+ }
1324
+ function normalizeSearchPath(filePath) {
1325
+ let p = filePath.replace(/\\/g, "/");
1326
+ while (p.startsWith("./")) {
1327
+ p = p.slice(2);
1328
+ }
1329
+ while (p.startsWith("/")) {
1330
+ p = p.slice(1);
1331
+ }
1332
+ return p;
1333
+ }
1334
+ function matchesGlob(filePath, pattern) {
1335
+ if (!pattern || pattern === "*" || pattern === "**") return true;
1336
+ const normPath = normalizeSearchPath(filePath);
1337
+ const normPattern = normalizeSearchPath(pattern);
1338
+ if (normPattern === normPath) return true;
1339
+ if (!normPattern.includes("*") && !normPattern.includes("?")) {
1340
+ return normPath.includes(normPattern) || normPath.endsWith(normPattern);
1341
+ }
1342
+ let regexStr = "^";
1343
+ let i = 0;
1344
+ while (i < normPattern.length) {
1345
+ const c = normPattern[i];
1346
+ if (c === "*") {
1347
+ if (normPattern[i + 1] === "*") {
1348
+ regexStr += ".*";
1349
+ i += 2;
1350
+ if (normPattern[i] === "/") {
1351
+ i++;
1352
+ }
1353
+ continue;
1354
+ } else {
1355
+ regexStr += "[^/]*";
1356
+ i++;
1357
+ continue;
1358
+ }
1359
+ } else if (c === "?") {
1360
+ regexStr += "[^/]";
1361
+ i++;
1362
+ continue;
1363
+ } else if ("./+^$()|[]{}\\".includes(c)) {
1364
+ regexStr += "\\" + c;
1365
+ i++;
1366
+ continue;
1367
+ } else {
1368
+ regexStr += c;
1369
+ i++;
1370
+ }
1371
+ }
1372
+ regexStr += "$";
1373
+ try {
1374
+ const re = new RegExp(regexStr);
1375
+ return re.test(normPath);
1376
+ } catch (err) {
1377
+ return normPath.includes(normPattern.replace(/[*?]/g, ""));
1378
+ }
1379
+ }
1380
+ function checkFilter(path, filter) {
1381
+ if (!filter) return true;
1382
+ if (Array.isArray(filter)) {
1383
+ return filter.some((f) => matchesGlob(path, f));
1384
+ }
1385
+ return matchesGlob(path, filter);
1386
+ }
1387
+ function createSearchResult(groups, totalMatches, fileCount, query, error) {
1388
+ const arr = [...groups];
1389
+ const result = Object.assign(arr, {
1390
+ matches: groups,
1391
+ totalMatches,
1392
+ fileCount,
1393
+ filesCount: fileCount,
1394
+ query,
1395
+ durationMs: 0,
1396
+ error
1397
+ });
1398
+ return result;
1399
+ }
1400
+ function searchInFiles(files, queryOrOptions, optionsOrUndefined) {
1401
+ let query = "";
1402
+ let opts = {};
1403
+ if (typeof queryOrOptions === "string") {
1404
+ query = queryOrOptions;
1405
+ opts = optionsOrUndefined || {};
1406
+ } else if (queryOrOptions && typeof queryOrOptions === "object") {
1407
+ opts = queryOrOptions;
1408
+ query = opts.query || "";
1409
+ }
1410
+ if (!query) {
1411
+ return createSearchResult([], 0, 0, query);
1412
+ }
1413
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1414
+ const isWholeWord = Boolean(opts.wholeWord);
1415
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1416
+ const maxMatches = opts.maxMatches ?? 1e4;
1417
+ const maxMatchesPerFile = opts.maxMatchesPerFile ?? 1e3;
1418
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1419
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1420
+ let patternStr = isRegex ? query : escapeRegex(query);
1421
+ if (isWholeWord) {
1422
+ patternStr = `\\b${patternStr}\\b`;
1423
+ }
1424
+ let regex = /(?:)/;
1425
+ try {
1426
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1427
+ } catch (err) {
1428
+ const _err = err;
1429
+ const msg = typeof _err === "object" && _err && "message" in _err ? String(_err.message) : "Invalid regular expression";
1430
+ return createSearchResult([], 0, 0, query, msg);
1431
+ }
1432
+ const matchedGroups = [];
1433
+ let totalMatches = 0;
1434
+ for (const [filePath, content] of Object.entries(files)) {
1435
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1436
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1437
+ if (opts.targetFiles && !opts.targetFiles.includes(filePath)) continue;
1438
+ const fileMatches = [];
1439
+ const lines = content.split("\n");
1440
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
1441
+ const lineText = lines[lineIndex];
1442
+ regex.lastIndex = 0;
1443
+ let m = null;
1444
+ while ((m = regex.exec(lineText)) !== null) {
1445
+ const matchLen = m[0].length;
1446
+ const col = m.index + 1;
1447
+ fileMatches.push({
1448
+ line: lineIndex + 1,
1449
+ col,
1450
+ column: col,
1451
+ length: matchLen,
1452
+ matchText: m[0],
1453
+ lineText,
1454
+ beforeSnippet: lineText.slice(0, m.index),
1455
+ afterSnippet: lineText.slice(m.index + matchLen),
1456
+ matchIndex: m.index,
1457
+ matchEndIndex: m.index + matchLen
1458
+ });
1459
+ totalMatches++;
1460
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1461
+ break;
1462
+ }
1463
+ if (matchLen === 0) {
1464
+ regex.lastIndex++;
1465
+ if (regex.lastIndex > lineText.length) {
1466
+ break;
1467
+ }
1468
+ }
1469
+ }
1470
+ if (fileMatches.length >= maxMatchesPerFile || totalMatches >= maxMatches) {
1471
+ break;
1472
+ }
1473
+ }
1474
+ if (fileMatches.length > 0) {
1475
+ matchedGroups.push({
1476
+ file: filePath,
1477
+ matches: fileMatches
1478
+ });
1479
+ }
1480
+ if (totalMatches >= maxMatches) {
1481
+ break;
1482
+ }
1483
+ }
1484
+ return createSearchResult(matchedGroups, totalMatches, matchedGroups.length, query);
1485
+ }
1486
+ function replaceInFiles(files, arg2, arg3, arg4) {
1487
+ let query = "";
1488
+ const replacement = typeof arg3 === "string" ? arg3 : "";
1489
+ let opts = {};
1490
+ let targetFiles = void 0;
1491
+ if (typeof arg2 === "string") {
1492
+ query = arg2;
1493
+ if (Array.isArray(arg4)) {
1494
+ targetFiles = arg4;
1495
+ } else if (arg4 && typeof arg4 === "object") {
1496
+ opts = arg4;
1497
+ targetFiles = opts.targetFiles;
1498
+ }
1499
+ } else if (arg2 && typeof arg2 === "object") {
1500
+ opts = arg2;
1501
+ query = opts.query || "";
1502
+ if (Array.isArray(arg4)) {
1503
+ targetFiles = arg4;
1504
+ } else {
1505
+ targetFiles = opts.targetFiles;
1506
+ }
1507
+ }
1508
+ if (!query) {
1509
+ return {
1510
+ updatedFiles: { ...files },
1511
+ replacedCount: 0,
1512
+ filesAffected: []
1513
+ };
1514
+ }
1515
+ const isCaseSensitive = Boolean(opts.caseSensitive);
1516
+ const isWholeWord = Boolean(opts.wholeWord);
1517
+ const isRegex = Boolean(opts.regex || opts.isRegex);
1518
+ const includeFilter = opts.include || opts.includeGlob || opts.includePattern;
1519
+ const excludeFilter = opts.exclude || opts.excludeGlob || opts.excludePattern;
1520
+ let patternStr = isRegex ? query : escapeRegex(query);
1521
+ if (isWholeWord) {
1522
+ patternStr = `\\b${patternStr}\\b`;
1523
+ }
1524
+ let regex = /(?:)/;
1525
+ try {
1526
+ regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1527
+ } catch (err) {
1528
+ return {
1529
+ updatedFiles: { ...files },
1530
+ replacedCount: 0,
1531
+ filesAffected: []
1532
+ };
1533
+ }
1534
+ const updatedFiles = { ...files };
1535
+ const filesAffected = [];
1536
+ let replacedCount = 0;
1537
+ for (const [filePath, content] of Object.entries(files)) {
1538
+ if (targetFiles && !targetFiles.includes(filePath)) continue;
1539
+ if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1540
+ if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1541
+ regex.lastIndex = 0;
1542
+ let countInFile = 0;
1543
+ let m;
1544
+ while ((m = regex.exec(content)) !== null) {
1545
+ countInFile++;
1546
+ if (m[0].length === 0) {
1547
+ regex.lastIndex++;
1548
+ if (regex.lastIndex > content.length) {
1549
+ break;
1550
+ }
1551
+ }
1552
+ }
1553
+ if (countInFile > 0) {
1554
+ regex.lastIndex = 0;
1555
+ let newContent;
1556
+ if (isRegex) {
1557
+ newContent = content.replace(regex, replacement);
1558
+ } else {
1559
+ newContent = content.replace(regex, () => replacement);
1560
+ }
1561
+ updatedFiles[filePath] = newContent;
1562
+ filesAffected.push(filePath);
1563
+ replacedCount += countInFile;
1564
+ }
1565
+ }
1566
+ return {
1567
+ updatedFiles,
1568
+ replacedCount,
1569
+ filesAffected
1570
+ };
1571
+ }
1572
+ return __toCommonJS(search_exports);
1573
+ })();
1574
+
1575
+ var CodeLabDiagnostics = (() => {
1576
+ var __defProp = Object.defineProperty;
1577
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1578
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1579
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1580
+ var __export = (target, all) => {
1581
+ for (var name in all)
1582
+ __defProp(target, name, { get: all[name], enumerable: true });
1583
+ };
1584
+ var __copyProps = (to, from, except, desc) => {
1585
+ if (from && typeof from === "object" || typeof from === "function") {
1586
+ for (let key of __getOwnPropNames(from))
1587
+ if (!__hasOwnProp.call(to, key) && key !== except)
1588
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1589
+ }
1590
+ return to;
1591
+ };
1592
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1593
+
1594
+ // src/diagnostics.ts
1595
+ var diagnostics_exports = {};
1596
+ __export(diagnostics_exports, {
1597
+ DiagnosticsStore: () => DiagnosticsStore,
1598
+ createDiagnosticsStore: () => createDiagnosticsStore,
1599
+ default: () => diagnostics_default
1600
+ });
1601
+ var DiagnosticsStore = class {
1602
+ items = /* @__PURE__ */ new Map();
1603
+ listeners = /* @__PURE__ */ new Set();
1604
+ add(item) {
1605
+ if (!item || typeof item.id !== "string" || !item.id) return;
1606
+ const normalized = {
1607
+ ...item,
1608
+ file: String(item.file || ""),
1609
+ line: typeof item.line === "number" && item.line > 0 ? Math.floor(item.line) : 1,
1610
+ col: typeof item.col === "number" && item.col > 0 ? Math.floor(item.col) : typeof item.column === "number" && item.column > 0 ? Math.floor(item.column) : 1,
1611
+ message: String(item.message || ""),
1612
+ severity: item.severity || "error"
1613
+ };
1614
+ this.items.set(normalized.id, normalized);
1615
+ this.notify();
1616
+ }
1617
+ remove(id) {
1618
+ if (this.items.delete(id)) {
1619
+ this.notify();
1620
+ }
1621
+ }
1622
+ clear(source) {
1623
+ if (source !== void 0 && source !== "") {
1624
+ let changed = false;
1625
+ for (const [id, item] of this.items.entries()) {
1626
+ if (item.source === source) {
1627
+ this.items.delete(id);
1628
+ changed = true;
1629
+ }
1630
+ }
1631
+ if (changed) {
1632
+ this.notify();
1633
+ }
1634
+ } else if (this.items.size > 0) {
1635
+ this.items.clear();
1636
+ this.notify();
1637
+ }
1638
+ }
1639
+ getAll() {
1640
+ return Array.from(this.items.values());
1641
+ }
1642
+ getByFile(file) {
1643
+ const out = [];
1644
+ for (const item of this.items.values()) {
1645
+ if (item.file === file) {
1646
+ out.push(item);
1647
+ }
1648
+ }
1649
+ return out;
1650
+ }
1651
+ subscribe(listener) {
1652
+ this.listeners.add(listener);
1653
+ return () => {
1654
+ this.listeners.delete(listener);
1655
+ };
1656
+ }
1657
+ notify() {
1658
+ if (this.listeners.size === 0) return;
1659
+ const snapshot = this.getAll();
1660
+ for (const listener of this.listeners) {
1661
+ try {
1662
+ listener(snapshot);
1663
+ } catch (err) {
1664
+ console.warn("[code-lab] diagnostics subscriber error:", err);
1665
+ }
1666
+ }
1667
+ }
1668
+ };
1669
+ function createDiagnosticsStore() {
1670
+ return new DiagnosticsStore();
1671
+ }
1672
+ var diagnostics_default = {
1673
+ DiagnosticsStore,
1674
+ createDiagnosticsStore
1675
+ };
1676
+ return __toCommonJS(diagnostics_exports);
1677
+ })();
1678
+
1679
+ var CodeLabScm = (() => {
1680
+ var __defProp = Object.defineProperty;
1681
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1682
+ var __getOwnPropNames = Object.getOwnPropertyNames;
1683
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
1684
+ var __export = (target, all) => {
1685
+ for (var name in all)
1686
+ __defProp(target, name, { get: all[name], enumerable: true });
1687
+ };
1688
+ var __copyProps = (to, from, except, desc) => {
1689
+ if (from && typeof from === "object" || typeof from === "function") {
1690
+ for (let key of __getOwnPropNames(from))
1691
+ if (!__hasOwnProp.call(to, key) && key !== except)
1692
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1693
+ }
1694
+ return to;
1695
+ };
1696
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1697
+
1698
+ // src/scm.ts
1699
+ var scm_exports = {};
1700
+ __export(scm_exports, {
1701
+ commitChanges: () => commitChanges,
1702
+ computeGitStatus: () => computeGitStatus,
1703
+ computeShortCommitHash: () => computeShortCommitHash,
1704
+ createGitState: () => createGitState,
1705
+ default: () => scm_default,
1706
+ stageFile: () => stageFile,
1707
+ unstageFile: () => unstageFile
1708
+ });
1709
+ function computeShortCommitHash(input) {
1710
+ let h1 = 3735928559 ^ input.length;
1711
+ let h2 = 1103547991 ^ input.length;
1712
+ for (let i = 0; i < input.length; i++) {
1713
+ const ch = input.charCodeAt(i);
1714
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1715
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1716
+ }
1717
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1718
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1719
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
1720
+ return combined.toString(16).padStart(7, "0").slice(0, 7);
1721
+ }
1722
+ function createGitState(initialFiles = {}, branch = "main") {
1723
+ const headFiles = { ...initialFiles };
1724
+ const initialHash = computeShortCommitHash(JSON.stringify(headFiles) + ":init");
1725
+ return {
1726
+ branch,
1727
+ branches: [branch],
1728
+ headCommit: initialHash,
1729
+ headFiles,
1730
+ staged: /* @__PURE__ */ new Map(),
1731
+ commits: [
1732
+ {
1733
+ hash: initialHash,
1734
+ message: "Initial commit",
1735
+ timestamp: Date.now(),
1736
+ files: { ...headFiles }
1737
+ }
1738
+ ]
1739
+ };
1740
+ }
1741
+ function computeGitStatus(vfsFiles, _repoRoot = "/workspace", gitState) {
1742
+ const state = gitState || createGitState({});
1743
+ const headFiles = state.headFiles || {};
1744
+ const currentStaged = state.staged instanceof Map ? state.staged : /* @__PURE__ */ new Map();
1745
+ const untracked = [];
1746
+ const modified = [];
1747
+ const deleted = [];
1748
+ const staged = [];
1749
+ for (const [filePath, stagedContent] of currentStaged.entries()) {
1750
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
1751
+ if (stagedContent === null) {
1752
+ staged.push({
1753
+ path: filePath,
1754
+ status: "deleted",
1755
+ staged: true,
1756
+ oldContent: headFiles[filePath]
1757
+ });
1758
+ } else {
1759
+ staged.push({
1760
+ path: filePath,
1761
+ status: inHead ? "modified" : "added",
1762
+ staged: true,
1763
+ oldContent: inHead ? headFiles[filePath] : void 0,
1764
+ newContent: stagedContent
1765
+ });
1766
+ }
1767
+ }
1768
+ for (const [filePath, content] of Object.entries(vfsFiles || {})) {
1769
+ if (currentStaged.has(filePath)) {
1770
+ const stagedVal = currentStaged.get(filePath);
1771
+ if (stagedVal !== content) {
1772
+ modified.push({
1773
+ path: filePath,
1774
+ status: "modified",
1775
+ staged: false,
1776
+ oldContent: stagedVal ?? void 0,
1777
+ newContent: content
1778
+ });
1779
+ }
1780
+ } else if (Object.prototype.hasOwnProperty.call(headFiles, filePath)) {
1781
+ if (headFiles[filePath] !== content) {
1782
+ modified.push({
1783
+ path: filePath,
1784
+ status: "modified",
1785
+ staged: false,
1786
+ oldContent: headFiles[filePath],
1787
+ newContent: content
1788
+ });
1789
+ }
1790
+ } else {
1791
+ untracked.push({
1792
+ path: filePath,
1793
+ status: "untracked",
1794
+ staged: false,
1795
+ newContent: content
1796
+ });
1797
+ }
1798
+ }
1799
+ for (const filePath of Object.keys(headFiles)) {
1800
+ if (!Object.prototype.hasOwnProperty.call(vfsFiles, filePath) && !currentStaged.has(filePath)) {
1801
+ deleted.push({
1802
+ path: filePath,
1803
+ status: "deleted",
1804
+ staged: false,
1805
+ oldContent: headFiles[filePath]
1806
+ });
1807
+ }
1808
+ }
1809
+ const unstaged = [...modified, ...deleted];
1810
+ const isClean = untracked.length === 0 && modified.length === 0 && deleted.length === 0 && staged.length === 0;
1811
+ return {
1812
+ branch: state.branch || "main",
1813
+ headCommit: state.headCommit || "",
1814
+ untracked,
1815
+ modified,
1816
+ deleted,
1817
+ staged,
1818
+ unstaged,
1819
+ hasChanges: !isClean,
1820
+ isClean
1821
+ };
1822
+ }
1823
+ function stageFile(gitState, relativePath, currentContent) {
1824
+ if (!gitState) return;
1825
+ if (!(gitState.staged instanceof Map)) {
1826
+ gitState.staged = /* @__PURE__ */ new Map();
1827
+ }
1828
+ gitState.staged.set(relativePath, currentContent === void 0 ? null : currentContent);
1829
+ }
1830
+ function unstageFile(gitState, relativePath) {
1831
+ if (!gitState || !(gitState.staged instanceof Map)) return;
1832
+ gitState.staged.delete(relativePath);
1833
+ }
1834
+ function commitChanges(gitState, message) {
1835
+ const trimmed = typeof message === "string" ? message.trim() : "";
1836
+ if (!trimmed) {
1837
+ throw new Error("Commit message cannot be empty");
1838
+ }
1839
+ if (!gitState || !(gitState.staged instanceof Map) || gitState.staged.size === 0) {
1840
+ throw new Error("Nothing to commit (staging area is empty)");
1841
+ }
1842
+ const newHeadFiles = { ...gitState.headFiles || {} };
1843
+ for (const [filePath, content] of gitState.staged.entries()) {
1844
+ if (content === null) {
1845
+ delete newHeadFiles[filePath];
1846
+ } else {
1847
+ newHeadFiles[filePath] = content;
1848
+ }
1849
+ }
1850
+ const timestamp = Date.now();
1851
+ const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
1852
+ const commit = {
1853
+ hash,
1854
+ message: trimmed,
1855
+ timestamp,
1856
+ files: newHeadFiles
1857
+ };
1858
+ if (!Array.isArray(gitState.commits)) {
1859
+ gitState.commits = [];
1860
+ }
1861
+ gitState.commits.push(commit);
1862
+ gitState.headCommit = hash;
1863
+ gitState.headFiles = newHeadFiles;
1864
+ gitState.staged.clear();
1865
+ return hash;
1866
+ }
1867
+ var scm_default = {
1868
+ createGitState,
1869
+ computeGitStatus,
1870
+ stageFile,
1871
+ unstageFile,
1872
+ commitChanges,
1873
+ computeShortCommitHash
1874
+ };
1875
+ return __toCommonJS(scm_exports);
1876
+ })();
1877
+
1878
+ root.CodeLabZip = CodeLabZip;
1879
+ root.CodeLabStorage = CodeLabStorage;
1880
+ root.CodeLabSearch = CodeLabSearch;
1881
+ root.CodeLabDiagnostics = CodeLabDiagnostics;
1882
+ root.CodeLabScm = CodeLabScm;
1883
+
20
1884
  // --- Module 1: Runtime Engine ---
21
1885
  (function () {
22
1886
  // @ts-nocheck
@@ -41,6 +1905,14 @@ if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined')
41
1905
  */
42
1906
 
43
1907
  function __initVirtualRuntime(rootScope) {
1908
+ const _runtimeLogger = (rootScope && rootScope.CodeLabLogger && typeof rootScope.CodeLabLogger.createLogger === 'function')
1909
+ ? rootScope.CodeLabLogger.createLogger()
1910
+ : {
1911
+ debug() {},
1912
+ info() {},
1913
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
1914
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
1915
+ };
44
1916
  // =========================================================================
45
1917
  // 1. UTF-8 / HEX / BASE64 / BASE64URL CODECS & VIRTUAL BUFFER
46
1918
  // =========================================================================
@@ -1600,7 +3472,7 @@ function __initVirtualRuntime(rootScope) {
1600
3472
  },
1601
3473
  final(cb) {
1602
3474
  if (fd !== null) {
1603
- try { fsShim.closeSync(fd); } catch (_) {}
3475
+ try { fsShim.closeSync(fd); } catch (err) { _runtimeLogger.debug('vfs writeStream closeSync failed', err); }
1604
3476
  fd = null;
1605
3477
  }
1606
3478
  cb(null);
@@ -2120,7 +3992,9 @@ function __initVirtualRuntime(rootScope) {
2120
3992
  return pathname + search + hash;
2121
3993
  }
2122
3994
  return resolvedUrl.href;
2123
- } catch (_) {}
3995
+ } catch (err) {
3996
+ _runtimeLogger.debug('url.resolve fallback used', err);
3997
+ }
2124
3998
  }
2125
3999
  if (toStr.startsWith('/')) {
2126
4000
  const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(fromStr);
@@ -2559,10 +4433,10 @@ function __initVirtualRuntime(rootScope) {
2559
4433
  for (const [port, entry] of Array.from(table.entries())) {
2560
4434
  if (entry.pid !== undefined && String(entry.pid) === pStr) {
2561
4435
  if (entry.server && typeof entry.server.close === 'function') {
2562
- try { entry.server.close(); } catch (_) {}
4436
+ try { entry.server.close(); } catch (err) { _runtimeLogger.debug('portTable server.close failed', err); }
2563
4437
  }
2564
4438
  if (typeof entry.stop === 'function') {
2565
- try { entry.stop(); } catch (_) {}
4439
+ try { entry.stop(); } catch (err) { _runtimeLogger.debug('portTable entry.stop failed', err); }
2566
4440
  }
2567
4441
  // Avoid a double 'close' emission when entry.server.close() already
2568
4442
  // unregistered the port through unregisterServer().
@@ -3199,7 +5073,7 @@ function __initVirtualRuntime(rootScope) {
3199
5073
  },
3200
5074
  closeAllServers() {
3201
5075
  for (const s of Array.from(activeServers.values())) {
3202
- try { s.close(); } catch (_) {}
5076
+ try { s.close(); } catch (err) { _runtimeLogger.debug('vhttp closeAllServers close failed', err); }
3203
5077
  }
3204
5078
  activeServers.clear();
3205
5079
  }
@@ -4025,7 +5899,7 @@ function __initVirtualRuntime(rootScope) {
4025
5899
 
4026
5900
  function closeAllServers() {
4027
5901
  for (const srv of servers.values()) {
4028
- try { srv.close(); } catch (_) {}
5902
+ try { srv.close(); } catch (err) { _runtimeLogger.debug('vnet closeAllServers close failed', err); }
4029
5903
  }
4030
5904
  servers.clear();
4031
5905
  }
@@ -5105,7 +6979,9 @@ function __initVirtualRuntime(rootScope) {
5105
6979
  try {
5106
6980
  const pkgJson = JSON.parse(content);
5107
6981
  for (const dep of Object.keys(pkgJson.dependencies || {})) addSpec(dep);
5108
- } catch (_) {}
6982
+ } catch (err) {
6983
+ _runtimeLogger.debug('preloadNpmPackages invalid package.json', err);
6984
+ }
5109
6985
  continue;
5110
6986
  }
5111
6987
  const reqRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
@@ -5134,7 +7010,9 @@ function __initVirtualRuntime(rootScope) {
5134
7010
  const meta = await res.json();
5135
7011
  deps = Object.keys((meta && meta.dependencies) || {});
5136
7012
  }
5137
- } catch (_) {}
7013
+ } catch (err) {
7014
+ _runtimeLogger.debug('preloadNpmPackages metadata fetch failed', { pkg, err });
7015
+ }
5138
7016
  _npmMetadataCache.set(pkg, deps);
5139
7017
  }));
5140
7018
  for (const pkg of pending) {
@@ -5152,7 +7030,7 @@ function __initVirtualRuntime(rootScope) {
5152
7030
  continue;
5153
7031
  }
5154
7032
  if (typeof onProgress === 'function') {
5155
- try { onProgress(pkg); } catch (_) {}
7033
+ try { onProgress(pkg); } catch (err) { _runtimeLogger.debug('preloadNpmPackages onProgress callback failed', err); }
5156
7034
  }
5157
7035
  if (typeof fetch === 'function') {
5158
7036
  try {
@@ -5162,7 +7040,9 @@ function __initVirtualRuntime(rootScope) {
5162
7040
  if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
5163
7041
  loaded[pkg] = text;
5164
7042
  }
5165
- } catch (_) {}
7043
+ } catch (err) {
7044
+ _runtimeLogger.debug('preloadNpmPackages package fetch failed', { pkg, err });
7045
+ }
5166
7046
  }
5167
7047
  }
5168
7048
  return loaded;
@@ -5354,7 +7234,9 @@ function __initVirtualRuntime(rootScope) {
5354
7234
  const dir = VirtualPath.dirname(abs);
5355
7235
  if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
5356
7236
  vfs.writeFileSync(abs, content);
5357
- } catch (_) {}
7237
+ } catch (err) {
7238
+ _runtimeLogger.warn('vfs initial file seed failed', { abs, err });
7239
+ }
5358
7240
  }
5359
7241
  }
5360
7242
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
@@ -5799,7 +7681,7 @@ function __initVirtualRuntime(rootScope) {
5799
7681
  exitCode = Number(code) || 0;
5800
7682
  if (!hasExited) {
5801
7683
  hasExited = true;
5802
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
7684
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('process exit listener threw', err); }
5803
7685
  }
5804
7686
  if (syncExecDepth > 0) {
5805
7687
  throw new ProcessExitSignal(exitCode);
@@ -5832,8 +7714,8 @@ function __initVirtualRuntime(rootScope) {
5832
7714
  resourceTracker.inFlightHttp.clear();
5833
7715
 
5834
7716
  if (!isBackground) {
5835
- try { vhttp.closeAllServers(); } catch (_) {}
5836
- try { vnet.closeAllServers(); } catch (_) {}
7717
+ try { vhttp.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vhttp closeAllServers failed', err); }
7718
+ try { vnet.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vnet closeAllServers failed', err); }
5837
7719
  }
5838
7720
  };
5839
7721
 
@@ -5943,10 +7825,10 @@ function __initVirtualRuntime(rootScope) {
5943
7825
  sandboxConsole.log(`✗ ${fullName}\n ${e && e.stack ? e.stack : e}`);
5944
7826
  } finally {
5945
7827
  for (const ae of hooksSnapshot.afterEachList) {
5946
- try { await ae(); } catch (_) {}
7828
+ try { await ae(); } catch (err) { _runtimeLogger.debug('node:test afterEach hook failed', err); }
5947
7829
  }
5948
7830
  for (const af of hooksSnapshot.afterToRun) {
5949
- try { await af(); } catch (_) {}
7831
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test after hook failed', err); }
5950
7832
  }
5951
7833
  hooksSnapshot.afterToRun.length = 0;
5952
7834
  }
@@ -5994,7 +7876,7 @@ function __initVirtualRuntime(rootScope) {
5994
7876
  const afters = [...suiteCtx.afterCallbacks];
5995
7877
  const cleanupTask = nodeTestChain.then(async () => {
5996
7878
  for (const af of afters) {
5997
- try { await af(); } catch (_) {}
7879
+ try { await af(); } catch (err) { _runtimeLogger.debug('node:test suite after hook failed', err); }
5998
7880
  }
5999
7881
  });
6000
7882
  nodeTestChain = cleanupTask.catch(() => {});
@@ -6040,7 +7922,7 @@ function __initVirtualRuntime(rootScope) {
6040
7922
  getEntriesByName: (n, t) => (entry.name === n && (!t || entry.entryType === t) ? [entry] : []),
6041
7923
  getEntriesByType: (t) => (entry.entryType === t ? [entry] : [])
6042
7924
  };
6043
- try { obs._cb(list, obs); } catch (_) {}
7925
+ try { obs._cb(list, obs); } catch (err) { _runtimeLogger.debug('PerformanceObserver callback failed', err); }
6044
7926
  }
6045
7927
  }
6046
7928
  }
@@ -6145,7 +8027,7 @@ function __initVirtualRuntime(rootScope) {
6145
8027
  getEntriesByName: (n, t) => buffered.filter((e) => e.name === n && (!t || e.entryType === t)),
6146
8028
  getEntriesByType: (t) => buffered.filter((e) => e.entryType === t)
6147
8029
  };
6148
- queueMicrotask(() => { try { this._cb(list, this); } catch (_) {} });
8030
+ queueMicrotask(() => { try { this._cb(list, this); } catch (err) { _runtimeLogger.debug('PerformanceObserver buffered callback failed', err); } });
6149
8031
  }
6150
8032
  }
6151
8033
  }
@@ -7416,7 +9298,9 @@ function __initVirtualRuntime(rootScope) {
7416
9298
  const resolvedEntry = resolveFileOrDirCandidates(VirtualPath.resolve(base, entryRel));
7417
9299
  if (resolvedEntry) return resolvedEntry;
7418
9300
  }
7419
- } catch (_) {}
9301
+ } catch (err) {
9302
+ _runtimeLogger.debug('resolveFileOrDirCandidates package.json parse failed', err);
9303
+ }
7420
9304
  }
7421
9305
  const indexCandidates = ['index.js', 'index.ts', 'index.mjs', 'index.cjs', 'index.json'];
7422
9306
  for (const idx of indexCandidates) {
@@ -7486,7 +9370,9 @@ function __initVirtualRuntime(rootScope) {
7486
9370
  if (found) return found;
7487
9371
  }
7488
9372
  }
7489
- } catch (_) {}
9373
+ } catch (err) {
9374
+ _runtimeLogger.debug('resolveModulePath subpath package.json parse failed', err);
9375
+ }
7490
9376
  }
7491
9377
  const foundSub = resolveFileOrDirCandidates(VirtualPath.join(pkgRoot, subpath));
7492
9378
  if (foundSub) return foundSub;
@@ -7528,7 +9414,9 @@ function __initVirtualRuntime(rootScope) {
7528
9414
  if (isLocal && activePortTable) {
7529
9415
  return await activePortTable.dispatchRequest(urlStr, finalInit);
7530
9416
  }
7531
- } catch (_) {}
9417
+ } catch (err) {
9418
+ _runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
9419
+ }
7532
9420
 
7533
9421
  if (typeof globalThis.fetch === 'function') {
7534
9422
  return await globalThis.fetch(urlOrReq, init);
@@ -7695,7 +9583,9 @@ function __initVirtualRuntime(rootScope) {
7695
9583
  if (err instanceof SyntaxError && (/\bawait\b/.test(body) || /await/i.test(err.message))) {
7696
9584
  try {
7697
9585
  return new AsyncFunction(...argNames, body);
7698
- } catch (_) {}
9586
+ } catch (asyncErr) {
9587
+ _runtimeLogger.debug('AsyncFunction compilation fallback failed', asyncErr);
9588
+ }
7699
9589
  }
7700
9590
  if (
7701
9591
  err &&
@@ -7749,7 +9639,9 @@ function __initVirtualRuntime(rootScope) {
7749
9639
  if (signal && onAbort) {
7750
9640
  try {
7751
9641
  signal.removeEventListener('abort', onAbort);
7752
- } catch (_) {}
9642
+ } catch (err) {
9643
+ _runtimeLogger.debug('raceWithAbort removeEventListener failed', err);
9644
+ }
7753
9645
  }
7754
9646
  };
7755
9647
 
@@ -7908,11 +9800,11 @@ function __initVirtualRuntime(rootScope) {
7908
9800
  }
7909
9801
  } finally {
7910
9802
  if (signal && signalListener) {
7911
- try { signal.removeEventListener('abort', signalListener); } catch (_) {}
9803
+ try { signal.removeEventListener('abort', signalListener); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime removeEventListener failed', err); }
7912
9804
  }
7913
9805
  if (!hasExited) {
7914
9806
  hasExited = true;
7915
- try { sandboxProcess.emit('exit', exitCode); } catch (_) {}
9807
+ try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
7916
9808
  }
7917
9809
  for (const rawId of resourceTracker.allTimers) {
7918
9810
  clearTimeout(rawId);
@@ -8020,7 +9912,16 @@ function createWorkerRuntimeSource() {
8020
9912
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
8021
9913
  }
8022
9914
 
8023
- const _hostRuntime = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
9915
+ const _hostScope = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global);
9916
+ const _hostLogger = (_hostScope && _hostScope.CodeLabLogger && typeof _hostScope.CodeLabLogger.createLogger === 'function')
9917
+ ? _hostScope.CodeLabLogger.createLogger()
9918
+ : {
9919
+ debug() {},
9920
+ info() {},
9921
+ warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
9922
+ error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
9923
+ };
9924
+ const _hostRuntime = __initVirtualRuntime(_hostScope);
8024
9925
  _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
8025
9926
 
8026
9927
  let _cachedWorkerUrl = null;
@@ -8044,7 +9945,7 @@ function _ensureWarmWorker() {
8044
9945
 
8045
9946
  function _destroyWarmWorker() {
8046
9947
  if (_warmWorker) {
8047
- try { _warmWorker.terminate(); } catch (_) {}
9948
+ try { _warmWorker.terminate(); } catch (err) { _hostLogger.debug('warmWorker.terminate failed', err); }
8048
9949
  _warmWorker = null;
8049
9950
  }
8050
9951
  _warmWorkerBusy = false;
@@ -8099,7 +10000,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8099
10000
 
8100
10001
  function releaseWorker(terminateWorker) {
8101
10002
  if (options.signal && abortListener) {
8102
- try { options.signal.removeEventListener('abort', abortListener); } catch (_) {}
10003
+ try { options.signal.removeEventListener('abort', abortListener); } catch (err) { _hostLogger.debug('executeInWorker removeEventListener failed', err); }
8103
10004
  abortListener = null;
8104
10005
  }
8105
10006
  _activeWorkerJobs.delete(requestId);
@@ -8114,7 +10015,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
8114
10015
  }
8115
10016
  }
8116
10017
  } else {
8117
- try { worker.terminate(); } catch (_) {}
10018
+ try { worker.terminate(); } catch (err) { _hostLogger.debug('worker.terminate failed', err); }
8118
10019
  }
8119
10020
  }
8120
10021
 
@@ -8304,12 +10205,23 @@ if (typeof module !== 'undefined' && module.exports) {
8304
10205
  })(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
8305
10206
  'use strict';
8306
10207
 
10208
+ const _shellLogger = (root && root.CodeLabLogger && typeof root.CodeLabLogger.createLogger === 'function')
10209
+ ? root.CodeLabLogger.createLogger()
10210
+ : {
10211
+ debug() {},
10212
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
10213
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
10214
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
10215
+ };
10216
+
8307
10217
  function getRuntimeModule() {
8308
10218
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
8309
10219
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
8310
10220
  try {
8311
10221
  if (typeof require !== 'undefined') return require('./runtime.js');
8312
- } catch (_) {}
10222
+ } catch (err) {
10223
+ _shellLogger.debug('Optional ./runtime.js require skipped in shell.', err);
10224
+ }
8313
10225
  return null;
8314
10226
  }
8315
10227
 
@@ -8901,7 +10813,9 @@ if (typeof module !== 'undefined' && module.exports) {
8901
10813
  if (typeof vfs.statSync === 'function') {
8902
10814
  isDir = vfs.statSync(full).isDirectory();
8903
10815
  }
8904
- } catch (_) {}
10816
+ } catch (err) {
10817
+ _shellLogger.debug('Glob statSync failed.', full, err);
10818
+ }
8905
10819
 
8906
10820
  if (isDir) {
8907
10821
  traverse(full, rel);
@@ -10223,7 +12137,9 @@ if (typeof module !== 'undefined' && module.exports) {
10223
12137
  : name;
10224
12138
  try {
10225
12139
  snap[rel] = String(vfs.readFileSync(full, 'utf8'));
10226
- } catch (_) {}
12140
+ } catch (err) {
12141
+ _shellLogger.debug('Skipped unreadable VFS file in snapshot.', full, err);
12142
+ }
10227
12143
  }
10228
12144
  }
10229
12145
  }
@@ -10327,8 +12243,9 @@ if (typeof module !== 'undefined' && module.exports) {
10327
12243
  }
10328
12244
  }
10329
12245
  }
10330
- } catch (_) {
12246
+ } catch (err) {
10331
12247
  // Network or rate limit error on api.github.com; proceed to Strategy B
12248
+ _shellLogger.debug('GitHub REST API tree fetch failed; falling back to jsDelivr.', err);
10332
12249
  }
10333
12250
 
10334
12251
  // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
@@ -10355,7 +12272,9 @@ if (typeof module !== 'undefined' && module.exports) {
10355
12272
  }
10356
12273
  }
10357
12274
  }
10358
- } catch (_) {}
12275
+ } catch (err) {
12276
+ _shellLogger.debug('jsDelivr flat tree fetch failed.', err);
12277
+ }
10359
12278
  }
10360
12279
 
10361
12280
  if (repoNotFound || !rawTreeEntries) {
@@ -10503,7 +12422,9 @@ if (typeof module !== 'undefined' && module.exports) {
10503
12422
  }));
10504
12423
  }
10505
12424
  }
10506
- } catch (_) {}
12425
+ } catch (err) {
12426
+ _shellLogger.debug('Optional commit history fetch skipped.', err);
12427
+ }
10507
12428
 
10508
12429
  if (commits.length === 0) {
10509
12430
  commits = [
@@ -10569,7 +12490,9 @@ if (typeof module !== 'undefined' && module.exports) {
10569
12490
  try {
10570
12491
  const parsed = JSON.parse(vfs.readFileSync(p, 'utf8'));
10571
12492
  return { path: p, data: parsed };
10572
- } catch (_) {}
12493
+ } catch (err) {
12494
+ _shellLogger.warn(`Invalid JSON in ${p}; falling back to default package metadata.`, err);
12495
+ }
10573
12496
  }
10574
12497
  return { path: p, data: { name: 'app', dependencies: {}, devDependencies: {}, scripts: {} } };
10575
12498
  }
@@ -10610,13 +12533,20 @@ if (typeof module !== 'undefined' && module.exports) {
10610
12533
  vfs.rmdirSync(dirPath);
10611
12534
  }
10612
12535
  if (typeof emitMutation === 'function') emitMutation('delete', dirPath);
10613
- } catch (_) {}
12536
+ } catch (err) {
12537
+ _shellLogger.debug('removeDirRecursive failed.', dirPath, err);
12538
+ }
10614
12539
  }
10615
12540
 
10616
12541
  // ---------------------------------------------------------------------------
10617
12542
  // Real npm package installation via the jsDelivr CDN
10618
12543
  // ---------------------------------------------------------------------------
10619
12544
  const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
12545
+ const CDN_NPM_BASES = [
12546
+ 'https://cdn.jsdelivr.net/npm',
12547
+ 'https://unpkg.com',
12548
+ 'https://esm.sh'
12549
+ ];
10620
12550
 
10621
12551
  // Minimal offline registry, used only when the CDN is unreachable so common
10622
12552
  // demos still resolve without network access.
@@ -10762,16 +12692,23 @@ if (typeof module !== 'undefined' && module.exports) {
10762
12692
  }
10763
12693
 
10764
12694
  async function resolvePackageMetadata(fetchImpl, name, range) {
10765
- const urls = range
10766
- ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
10767
- : [`${CDN_NPM_BASE}/${name}/package.json`];
10768
- for (const url of urls) {
10769
- const text = await fetchTextFromCdn(fetchImpl, url);
10770
- if (!text) continue;
10771
- try {
10772
- const parsed = JSON.parse(text);
10773
- if (parsed && parsed.version) return parsed;
10774
- } catch (_) {}
12695
+ for (const base of CDN_NPM_BASES) {
12696
+ const urls = range
12697
+ ? [`${base}/${name}@${range}/package.json`, `${base}/${name}/package.json`]
12698
+ : [`${base}/${name}/package.json`];
12699
+ for (const url of urls) {
12700
+ const text = await fetchTextFromCdn(fetchImpl, url);
12701
+ if (!text) continue;
12702
+ try {
12703
+ const parsed = JSON.parse(text);
12704
+ if (parsed && parsed.version) {
12705
+ parsed._resolvedCdnBase = base;
12706
+ return parsed;
12707
+ }
12708
+ } catch (err) {
12709
+ _shellLogger.debug('Invalid package.json metadata from CDN.', url, err);
12710
+ }
12711
+ }
10775
12712
  }
10776
12713
  return null;
10777
12714
  }
@@ -10789,6 +12726,7 @@ if (typeof module !== 'undefined' && module.exports) {
10789
12726
  return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
10790
12727
  }
10791
12728
 
12729
+ const activeCdnBase = meta._resolvedCdnBase || CDN_NPM_BASE;
10792
12730
  const version = meta.version;
10793
12731
  const key = `${name}@${version}`;
10794
12732
  if (seen.has(key)) {
@@ -10836,7 +12774,7 @@ if (typeof module !== 'undefined' && module.exports) {
10836
12774
  frontier = [];
10837
12775
  if (batch.length === 0) break;
10838
12776
  const texts = await Promise.all(
10839
- batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
12777
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/${rel}`))
10840
12778
  );
10841
12779
  for (let idx = 0; idx < batch.length; idx++) {
10842
12780
  const rel = batch[idx];
@@ -10860,7 +12798,7 @@ if (typeof module !== 'undefined' && module.exports) {
10860
12798
  }
10861
12799
  // The declared entry may be missing on the CDN; fall back to index.js.
10862
12800
  if (!files.some(f => f.rel === entry)) {
10863
- const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
12801
+ const idxText = await fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/index.js`);
10864
12802
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10865
12803
  }
10866
12804
 
@@ -10907,7 +12845,9 @@ if (typeof module !== 'undefined' && module.exports) {
10907
12845
  // directory target would otherwise raise EISDIR).
10908
12846
  try {
10909
12847
  if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
10910
- } catch (_) {}
12848
+ } catch (err) {
12849
+ _shellLogger.debug('Package install statSync check skipped.', full, err);
12850
+ }
10911
12851
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10912
12852
  ctx.vfs.writeFileSync(full, f.content);
10913
12853
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -10985,6 +12925,32 @@ if (typeof module !== 'undefined' && module.exports) {
10985
12925
  pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
10986
12926
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10987
12927
 
12928
+ // Also maintain package-lock.json in the same directory for deterministic lockfile verification
12929
+ try {
12930
+ const lockPath = PosixPath.join(PosixPath.dirname(pkgPath), 'package-lock.json');
12931
+ let lockData = { name: pkgData.name || 'workspace', version: pkgData.version || '1.0.0', lockfileVersion: 3, packages: {} };
12932
+ if (ctx.vfs.existsSync(lockPath)) {
12933
+ const rawLock = String(ctx.vfs.readFileSync(lockPath, 'utf8') || '');
12934
+ const parsedLock = JSON.parse(rawLock);
12935
+ if (parsedLock && typeof parsedLock === 'object') {
12936
+ lockData = parsedLock;
12937
+ if (!lockData.packages || typeof lockData.packages !== 'object') lockData.packages = {};
12938
+ }
12939
+ }
12940
+ for (const inst of installed) {
12941
+ if (inst && inst.name) {
12942
+ lockData.packages[`node_modules/${inst.name}`] = {
12943
+ version: inst.version || '1.0.0',
12944
+ resolved: `${CDN_NPM_BASE}/${inst.name}@${inst.version || '1.0.0'}`
12945
+ };
12946
+ }
12947
+ }
12948
+ ctx.vfs.writeFileSync(lockPath, JSON.stringify(lockData, null, 2) + '\n');
12949
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('modify', lockPath);
12950
+ } catch (err) {
12951
+ _shellLogger.debug('Could not write package-lock.json during installPackage.', err);
12952
+ }
12953
+
10988
12954
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
10989
12955
  }
10990
12956
 
@@ -11182,7 +13148,9 @@ if (typeof module !== 'undefined' && module.exports) {
11182
13148
  const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
11183
13149
  if (parsed && parsed.version) return parsed.version;
11184
13150
  }
11185
- } catch (_) {}
13151
+ } catch (err) {
13152
+ _shellLogger.debug('Could not read installed module package.json.', pkgName, err);
13153
+ }
11186
13154
  try {
11187
13155
  for (const dir of [rootDir, '/workspace']) {
11188
13156
  const pkgPath = PosixPath.join(dir, 'package.json');
@@ -11191,7 +13159,9 @@ if (typeof module !== 'undefined' && module.exports) {
11191
13159
  const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
11192
13160
  if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
11193
13161
  }
11194
- } catch (_) {}
13162
+ } catch (err) {
13163
+ _shellLogger.debug('Could not read workspace package.json for version resolution.', pkgName, err);
13164
+ }
11195
13165
  return 'latest';
11196
13166
  }
11197
13167
 
@@ -11214,10 +13184,10 @@ if (typeof module !== 'undefined' && module.exports) {
11214
13184
  return imports;
11215
13185
  }
11216
13186
 
11217
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
11218
- const scripts = [];
13187
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
13188
+ const files = [];
11219
13189
  const walk = (dir, depth) => {
11220
- if (depth > 8 || scripts.length >= maxFiles) return;
13190
+ if (depth > 8 || files.length >= maxFiles) return;
11221
13191
  let entries = [];
11222
13192
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
11223
13193
  for (const name of entries) {
@@ -11228,13 +13198,23 @@ if (typeof module !== 'undefined' && module.exports) {
11228
13198
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
11229
13199
  if (dirFlag) {
11230
13200
  walk(full, depth + 1);
11231
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
11232
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
13201
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
13202
+ try {
13203
+ const content = vfs.readFileSync(full, 'utf8');
13204
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
13205
+ files.push({ full, rel, content });
13206
+ } catch (err) {
13207
+ _shellLogger.debug('Preview script read skipped.', full, err);
13208
+ }
11233
13209
  }
11234
13210
  }
11235
13211
  };
11236
13212
  walk(rootDir, 0);
11237
- return scripts;
13213
+ return files;
13214
+ }
13215
+
13216
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
13217
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
11238
13218
  }
11239
13219
 
11240
13220
  function injectPreviewExtras(html, importMap) {
@@ -11259,12 +13239,6 @@ if (typeof module !== 'undefined' && module.exports) {
11259
13239
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
11260
13240
  while (taken.has(port)) port++;
11261
13241
 
11262
- const specifiers = new Set();
11263
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
11264
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
11265
- }
11266
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
11267
-
11268
13242
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
11269
13243
  const isDir = (p) => {
11270
13244
  try {
@@ -11272,11 +13246,112 @@ if (typeof module !== 'undefined' && module.exports) {
11272
13246
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
11273
13247
  } catch (_) { return false; }
11274
13248
  };
13249
+ const isFile = (p) => exists(p) && !isDir(p);
11275
13250
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
11276
13251
 
13252
+ const resolveLocalTarget = (baseDir, rawSpec) => {
13253
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
13254
+ const clean = rawSpec.split(/[?#]/)[0].trim();
13255
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
13256
+ const candidateBase = clean.startsWith('/')
13257
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
13258
+ : PosixPath.join(baseDir, clean);
13259
+ if (isFile(candidateBase)) return candidateBase;
13260
+ const cands = [
13261
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
13262
+ candidateBase + '.mjs', candidateBase + '.cjs',
13263
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
13264
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
13265
+ ];
13266
+ for (const c of cands) {
13267
+ if (isFile(c)) return c;
13268
+ }
13269
+ return null;
13270
+ };
13271
+
13272
+ const toLocalImportKey = (fullPath) => {
13273
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
13274
+ return `@codelab-local/${rel}`;
13275
+ };
13276
+
13277
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
13278
+ let out = code;
13279
+ try {
13280
+ const rm = getRuntimeModule();
13281
+ if (rm && typeof rm.transpileForBrowser === 'function') {
13282
+ out = rm.transpileForBrowser(out, sourcePath);
13283
+ }
13284
+ } catch (err) {
13285
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
13286
+ }
13287
+ const fromDir = PosixPath.dirname(sourcePath);
13288
+ const rewriteSpec = (spec) => {
13289
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
13290
+ const resolved = resolveLocalTarget(fromDir, spec);
13291
+ return resolved ? toLocalImportKey(resolved) : spec;
13292
+ };
13293
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13294
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13295
+ return out;
13296
+ };
13297
+
13298
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
13299
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
13300
+ const specifiers = new Set();
13301
+ for (const f of scriptFiles) {
13302
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
13303
+ }
13304
+ // Also scan inline module scripts in HTML for bare specifiers
13305
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
13306
+ let inlineMatch;
13307
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
13308
+ if (inlineMatch[1]) {
13309
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
13310
+ }
13311
+ }
13312
+
13313
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
13314
+ for (const f of scriptFiles) {
13315
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
13316
+ const key = toLocalImportKey(f.full);
13317
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
13318
+ }
13319
+
13320
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
13321
+ let transformedHtml = htmlBody;
13322
+
13323
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
13324
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
13325
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
13326
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
13327
+ if (!hrefMatch) return fullTag;
13328
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
13329
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
13330
+ const cssContent = readText(cssTarget);
13331
+ if (cssContent === null) return fullTag;
13332
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
13333
+ });
13334
+
13335
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
13336
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
13337
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
13338
+ if (!srcMatch) return fullTag;
13339
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
13340
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
13341
+ const rawScript = readText(scriptTarget);
13342
+ if (rawScript === null) return fullTag;
13343
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
13344
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
13345
+ const typeAttr = isMod ? ' type="module"' : '';
13346
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
13347
+ });
13348
+
13349
+ return injectPreviewExtras(transformedHtml, importMap);
13350
+ };
13351
+
11277
13352
  const handler = async (request) => {
11278
13353
  let pathname = '/';
11279
- try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
13354
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
11280
13355
  const rel = pathname.replace(/^\/+/, '');
11281
13356
  let target = PosixPath.join(rootDir, rel);
11282
13357
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
@@ -11308,14 +13383,16 @@ if (typeof module !== 'undefined' && module.exports) {
11308
13383
  let body = readText(target);
11309
13384
  if (body === null) body = '';
11310
13385
  if (/\.html?$/i.test(target)) {
11311
- body = injectPreviewExtras(body, importMap);
13386
+ body = buildHtmlPreviewResponse(body, target);
11312
13387
  } else if (isPreviewScriptPath(target)) {
11313
13388
  try {
11314
13389
  const rm = getRuntimeModule();
11315
13390
  if (rm && typeof rm.transpileForBrowser === 'function') {
11316
13391
  body = rm.transpileForBrowser(body, target);
11317
13392
  }
11318
- } catch (_) {}
13393
+ } catch (err) {
13394
+ _shellLogger.warn(`Preview script transpilation failed for ${target}.`, err);
13395
+ }
11319
13396
  }
11320
13397
 
11321
13398
  return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
@@ -11323,7 +13400,7 @@ if (typeof module !== 'undefined' && module.exports) {
11323
13400
 
11324
13401
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
11325
13402
  return portTable.registerServer(port, {
11326
- server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
13403
+ server: { close() { try { portTable.unregisterServer(port); } catch (err) { _shellLogger.debug('Preview server unregister failed.', port, err); } } },
11327
13404
  fetch: handler,
11328
13405
  name: 'code-lab-serve',
11329
13406
  pid,
@@ -11436,7 +13513,9 @@ if (typeof module !== 'undefined' && module.exports) {
11436
13513
  let isDir = false;
11437
13514
  try {
11438
13515
  isDir = ctx.vfs.statSync(resolved).isDirectory();
11439
- } catch (_) {}
13516
+ } catch (err) {
13517
+ _shellLogger.debug('cd statSync failed.', resolved, err);
13518
+ }
11440
13519
 
11441
13520
  if (!isDir) {
11442
13521
  return { code: 1, stdout: '', stderr: `cd: ${target}: Not a directory\n` };
@@ -11536,7 +13615,9 @@ if (typeof module !== 'undefined' && module.exports) {
11536
13615
  isDirectory = st.isDirectory();
11537
13616
  size = st.size;
11538
13617
  mtimeMs = st.mtimeMs || Date.now();
11539
- } catch (_) {}
13618
+ } catch (err) {
13619
+ _shellLogger.debug('ls statSync skipped.', itemPath, err);
13620
+ }
11540
13621
  return { name, isDirectory, size, mtimeMs, absPath: itemPath };
11541
13622
  });
11542
13623
 
@@ -11956,7 +14037,9 @@ if (typeof module !== 'undefined' && module.exports) {
11956
14037
  if (st.isDirectory()) walk(full);
11957
14038
  else targets.push(full);
11958
14039
  }
11959
- } catch (_) {}
14040
+ } catch (err) {
14041
+ _shellLogger.debug('grep directory walk skipped.', dir, err);
14042
+ }
11960
14043
  }
11961
14044
  if (ctx.vfs.existsSync(absRoot)) {
11962
14045
  const st = ctx.vfs.statSync(absRoot);
@@ -12080,7 +14163,9 @@ if (typeof module !== 'undefined' && module.exports) {
12080
14163
  let isDir = false;
12081
14164
  try {
12082
14165
  isDir = ctx.vfs.statSync(full).isDirectory();
12083
- } catch (_) {}
14166
+ } catch (err) {
14167
+ _shellLogger.debug('find statSync skipped.', full, err);
14168
+ }
12084
14169
 
12085
14170
  const relPath = root === '.'
12086
14171
  ? './' + full.replace(absRoot.endsWith('/') ? absRoot : absRoot + '/', '')
@@ -12099,7 +14184,7 @@ if (typeof module !== 'undefined' && module.exports) {
12099
14184
  // Root itself check
12100
14185
  if (ctx.vfs.existsSync(absRoot)) {
12101
14186
  let isDir = false;
12102
- try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (_) {}
14187
+ try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (err) { _shellLogger.debug('find root statSync skipped.', absRoot, err); }
12103
14188
  if (!typeFilter || (typeFilter === 'd' && isDir) || (typeFilter === 'f' && !isDir)) {
12104
14189
  if (!nameRegex || nameRegex.test(PosixPath.basename(root))) {
12105
14190
  results.push(root);
@@ -13011,7 +15096,7 @@ if (typeof module !== 'undefined' && module.exports) {
13011
15096
  const isLast = i === entries.length - 1;
13012
15097
  const full = dirPath === '/' ? '/' + entry : dirPath + '/' + entry;
13013
15098
  let isDir = false;
13014
- try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (_) {}
15099
+ try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (err) { _shellLogger.debug('tree statSync skipped.', full, err); }
13015
15100
 
13016
15101
  stdout += `${prefix}${isLast ? '└── ' : '├── '}${entry}\n`;
13017
15102
 
@@ -13239,10 +15324,10 @@ if (typeof module !== 'undefined' && module.exports) {
13239
15324
  for (const s of ctx.shell.portTable.listServers()) {
13240
15325
  if (s.pid !== undefined && String(s.pid) === String(pid)) {
13241
15326
  if (s.server && typeof s.server.close === 'function') {
13242
- try { s.server.close(); } catch (_) {}
15327
+ try { s.server.close(); } catch (err) { _shellLogger.debug('kill server.close failed.', err); }
13243
15328
  }
13244
15329
  if (typeof s.stop === 'function') {
13245
- try { s.stop(); } catch (_) {}
15330
+ try { s.stop(); } catch (err) { _shellLogger.debug('kill server.stop failed.', err); }
13246
15331
  }
13247
15332
  ctx.shell.portTable.unregisterServer(s.port);
13248
15333
  killedPort = true;
@@ -15575,6 +17660,16 @@ if (typeof module !== 'undefined' && module.exports) {
15575
17660
  })(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this), function () {
15576
17661
  'use strict';
15577
17662
 
17663
+ const _termRoot = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
17664
+ const _terminalLogger = (_termRoot && _termRoot.CodeLabLogger && typeof _termRoot.CodeLabLogger.createLogger === 'function')
17665
+ ? _termRoot.CodeLabLogger.createLogger()
17666
+ : {
17667
+ debug() {},
17668
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
17669
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
17670
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
17671
+ };
17672
+
15578
17673
  const ANSI_CODE_MAP = {
15579
17674
  1: 'cl-ansi-bold',
15580
17675
  2: 'cl-ansi-dim',
@@ -16115,7 +18210,7 @@ if (typeof module !== 'undefined' && module.exports) {
16115
18210
  if (!this.container || typeof this.container.querySelector !== 'function') return;
16116
18211
  const input = this.container.querySelector('#cl-repl-input');
16117
18212
  if (input && typeof input.focus === 'function') {
16118
- try { input.focus(); } catch (_) {}
18213
+ try { input.focus(); } catch (err) { _terminalLogger.debug('Terminal input focus skipped.', err); }
16119
18214
  }
16120
18215
  }
16121
18216
 
@@ -16139,9 +18234,9 @@ if (typeof module !== 'undefined' && module.exports) {
16139
18234
  }
16140
18235
  for (const entry of this._listeners) {
16141
18236
  if (typeof entry === 'function') {
16142
- try { entry(); } catch (_) {}
18237
+ try { entry(); } catch (err) { _terminalLogger.debug('Terminal listener cleanup callback failed.', err); }
16143
18238
  } else if (entry && entry.target && typeof entry.target.removeEventListener === 'function') {
16144
- try { entry.target.removeEventListener(entry.type, entry.handler); } catch (_) {}
18239
+ try { entry.target.removeEventListener(entry.type, entry.handler); } catch (err) { _terminalLogger.debug('Terminal removeEventListener failed.', err); }
16145
18240
  }
16146
18241
  }
16147
18242
  this._listeners = [];
@@ -16210,7 +18305,9 @@ if (typeof module !== 'undefined' && module.exports) {
16210
18305
  try {
16211
18306
  const res = this.onKey(e);
16212
18307
  if (res === false) return;
16213
- } catch (_) {}
18308
+ } catch (err) {
18309
+ _terminalLogger.warn('Terminal onKey callback threw.', err);
18310
+ }
16214
18311
  }
16215
18312
 
16216
18313
  const key = e.key;
@@ -16363,7 +18460,7 @@ if (typeof module !== 'undefined' && module.exports) {
16363
18460
  this.replMode = false;
16364
18461
  }
16365
18462
  if (this.onInterrupt) {
16366
- try { this.onInterrupt(); } catch (_) {}
18463
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
16367
18464
  }
16368
18465
  this.render();
16369
18466
  return;
@@ -16564,7 +18661,9 @@ if (typeof module !== 'undefined' && module.exports) {
16564
18661
  if (typeof nextInput.setSelectionRange === 'function') {
16565
18662
  nextInput.setSelectionRange(this.cursor, this.cursor);
16566
18663
  }
16567
- } catch (_) {}
18664
+ } catch (err) {
18665
+ _terminalLogger.debug('Terminal focus/selection restore skipped.', err);
18666
+ }
16568
18667
  }
16569
18668
  }
16570
18669
  }
@@ -16604,13 +18703,26 @@ if (typeof module !== 'undefined' && module.exports) {
16604
18703
  (function (root) {
16605
18704
  'use strict';
16606
18705
 
16607
- let terminalModule = null;
16608
- let shellModule = null;
16609
- let runtimeModule = null;
18706
+ const _sharedLoggerMod = (typeof CodeLabLogger !== 'undefined' && CodeLabLogger) ||
18707
+ (root && root.CodeLabLogger) ||
18708
+ null;
18709
+ const _bootDebug = (_sharedLoggerMod && _sharedLoggerMod.DEFAULT_LOGGER && typeof _sharedLoggerMod.DEFAULT_LOGGER.debug === 'function')
18710
+ ? (...args) => _sharedLoggerMod.DEFAULT_LOGGER.debug(...args)
18711
+ : () => {};
18712
+
18713
+ let terminalModule = (root && root.CodeLabTerminal) || null;
18714
+ let shellModule = (root && root.CodeLabShell) || null;
18715
+ let runtimeModule = (root && root.CodeLabRuntime) || null;
16610
18716
  if (typeof require === 'function') {
16611
- try { terminalModule = require('./terminal.js'); } catch (_) {}
16612
- try { shellModule = require('./shell.js'); } catch (_) {}
16613
- try { runtimeModule = require('./runtime.js'); } catch (_) {}
18717
+ if (!terminalModule) {
18718
+ try { terminalModule = require('./terminal.js'); } catch (err) { _bootDebug('optional terminal.js require failed', err); }
18719
+ }
18720
+ if (!shellModule) {
18721
+ try { shellModule = require('./shell.js'); } catch (err) { _bootDebug('optional shell.js require failed', err); }
18722
+ }
18723
+ if (!runtimeModule) {
18724
+ try { runtimeModule = require('./runtime.js'); } catch (err) { _bootDebug('optional runtime.js require failed', err); }
18725
+ }
16614
18726
  }
16615
18727
  const CodeLabTerminal = (root && root.CodeLabTerminal) || terminalModule || {};
16616
18728
  const CodeLabShell = (root && root.CodeLabShell) || shellModule || {};
@@ -16641,7 +18753,7 @@ if (typeof module !== 'undefined' && module.exports) {
16641
18753
 
16642
18754
  // The bundler rewrites this literal from package.json at build time. Keeping
16643
18755
  // the fallback in sync lets tests require src/workbench.js directly.
16644
- const CODELAB_VERSION = '0.1.7';
18756
+ const CODELAB_VERSION = '0.1.9';
16645
18757
 
16646
18758
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
16647
18759
  const NODE_AMBIENT_DTS = `
@@ -16969,7 +19081,14 @@ declare module 'bun:sqlite' {
16969
19081
  }
16970
19082
  `;
16971
19083
 
19084
+ const _sharedHtmlMod = (typeof CodeLabHtml !== 'undefined' && CodeLabHtml) ||
19085
+ (root && root.CodeLabHtml) ||
19086
+ null;
19087
+
16972
19088
  function escapeHtml(str) {
19089
+ if (_sharedHtmlMod && typeof _sharedHtmlMod.escapeHtml === 'function') {
19090
+ return _sharedHtmlMod.escapeHtml(str);
19091
+ }
16973
19092
  if (str == null) return '';
16974
19093
  return String(str)
16975
19094
  .replace(/&/g, '&amp;')
@@ -16979,6 +19098,18 @@ declare module 'bun:sqlite' {
16979
19098
  .replace(/'/g, '&#39;');
16980
19099
  }
16981
19100
 
19101
+ const isSafeHtml = (_sharedHtmlMod && _sharedHtmlMod.isSafeHtml) || ((v) => Boolean(v && typeof v === 'object' && typeof v.__html === 'string'));
19102
+ const raw = (_sharedHtmlMod && _sharedHtmlMod.raw) || ((trusted) => ({ __html: String(trusted), toString() { return this.__html; } }));
19103
+ const html = (_sharedHtmlMod && _sharedHtmlMod.html) || ((strings, ...values) => {
19104
+ let out = strings[0] || '';
19105
+ for (let i = 0; i < values.length; i++) {
19106
+ const val = values[i];
19107
+ out += (val == null || val === false) ? '' : (isSafeHtml(val) ? val.__html : escapeHtml(val));
19108
+ out += strings[i + 1] || '';
19109
+ }
19110
+ return raw(out);
19111
+ });
19112
+
16982
19113
  // Schemes that may appear in a rendered href. Everything else
16983
19114
  // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
16984
19115
  const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
@@ -17197,11 +19328,11 @@ declare module 'bun:sqlite' {
17197
19328
  if (!str) return '';
17198
19329
  let text = String(str);
17199
19330
 
17200
- // Markdown Links: [label](url "title") or [label](url)
17201
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
19331
+ // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
19332
+ text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
17202
19333
  const cleanUrl = sanitizeUrl(url);
17203
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
17204
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
19334
+ const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
19335
+ return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
17205
19336
  });
17206
19337
 
17207
19338
  // Strikethrough: ~~del~~
@@ -17728,23 +19859,24 @@ declare module 'bun:sqlite' {
17728
19859
  let _workbenchInstanceCounter = 0;
17729
19860
  const _fallbackStorage = new Map();
17730
19861
 
17731
- // CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
17732
- // in src/preview-sw.js — keep both copies in sync.
17733
- const PREVIEW_CSP = [
17734
- "default-src 'self' data: blob:",
17735
- "base-uri 'self'",
17736
- "object-src 'none'",
17737
- "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
17738
- "style-src 'self' 'unsafe-inline'",
17739
- "img-src 'self' data: blob:",
17740
- "font-src 'self' data:",
17741
- "connect-src 'self' data: blob:",
17742
- "media-src 'self' data: blob:",
17743
- "worker-src 'self' blob:",
17744
- "frame-src 'self' data: blob:",
17745
- "form-action 'self'",
17746
- "frame-ancestors 'self'"
17747
- ].join('; ');
19862
+ // Preview CSP, storage shims and violation reporting live in src/csp.ts.
19863
+ // The build embeds that module in this bundle (and in dist/preview-sw.js), so
19864
+ // there is exactly one policy implementation shared by both sides.
19865
+ const PreviewCsp = (typeof CodeLabCsp !== 'undefined' && CodeLabCsp) ||
19866
+ (root && root.CodeLabCsp) ||
19867
+ null;
19868
+
19869
+ function normalizePreviewCspOption(raw) {
19870
+ if (PreviewCsp && typeof PreviewCsp.normalizePreviewCspConfig === 'function') {
19871
+ return PreviewCsp.normalizePreviewCspConfig(raw);
19872
+ }
19873
+ return { mode: 'balanced', allow: {} };
19874
+ }
19875
+
19876
+ // `previewOrigin` needs a relay page + service worker on that origin. Until
19877
+ // that ships, using it would silently *pretend* to isolate previews while the
19878
+ // iframe gets a 503 from a worker that has no clients on the preview origin.
19879
+ const PREVIEW_RELAY_AVAILABLE = false;
17748
19880
 
17749
19881
  function normalizePreviewOrigin(raw) {
17750
19882
  if (raw === null || raw === undefined || raw === '') return null;
@@ -17757,12 +19889,26 @@ declare module 'bun:sqlite' {
17757
19889
  }
17758
19890
  }
17759
19891
 
17760
- const LOG_PREFIX = '[code-lab]';
19892
+ const LOG_PREFIX = (_sharedLoggerMod && _sharedLoggerMod.LOG_PREFIX) || '[code-lab]';
19893
+ const CodeLabError = (_sharedLoggerMod && _sharedLoggerMod.CodeLabError) || class CodeLabError extends Error {
19894
+ constructor(code, message, options = {}) {
19895
+ super(message);
19896
+ this.name = 'CodeLabError';
19897
+ this.code = code || 'E_CODELAB';
19898
+ this.module = options.module || 'workbench';
19899
+ this.context = options.context || {};
19900
+ if (options.cause !== undefined) this.cause = options.cause;
19901
+ }
19902
+ };
19903
+ const isCodeLabError = (_sharedLoggerMod && _sharedLoggerMod.isCodeLabError) || ((value) => Boolean(value && typeof value === 'object' && value.name === 'CodeLabError' && typeof value.code === 'string'));
17761
19904
 
17762
19905
  // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
17763
19906
  // into their own telemetry; `options.debug` enables verbose output. Errors
17764
19907
  // are never silently discarded.
17765
19908
  function createLogger(options = {}) {
19909
+ if (_sharedLoggerMod && typeof _sharedLoggerMod.createLogger === 'function') {
19910
+ return _sharedLoggerMod.createLogger({ module: 'workbench', ...options });
19911
+ }
17766
19912
  const sink = options.logger;
17767
19913
  const debugEnabled = options.debug === true;
17768
19914
 
@@ -17772,8 +19918,9 @@ declare module 'bun:sqlite' {
17772
19918
  try {
17773
19919
  sink[level](...args);
17774
19920
  return;
17775
- } catch (_) {
17776
- // A broken host logger must not break the IDE; fall through.
19921
+ } catch (sinkErr) {
19922
+ const fallbackWarn = typeof console !== 'undefined' && typeof console.warn === 'function' ? console.warn : null;
19923
+ if (fallbackWarn) fallbackWarn(LOG_PREFIX, 'Host logger sink threw; falling back to console.', sinkErr);
17777
19924
  }
17778
19925
  }
17779
19926
  const fn = typeof console !== 'undefined' ? console[level] : null;
@@ -17805,7 +19952,7 @@ declare module 'bun:sqlite' {
17805
19952
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
17806
19953
  }
17807
19954
 
17808
- function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
19955
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER, onError = null) {
17809
19956
  const str = String(value);
17810
19957
  try {
17811
19958
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
@@ -17813,6 +19960,9 @@ declare module 'bun:sqlite' {
17813
19960
  return true;
17814
19961
  }
17815
19962
  } catch (err) {
19963
+ if (typeof onError === 'function') {
19964
+ onError(err);
19965
+ }
17816
19966
  if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
17817
19967
  if (!safeStorageSet._warnedKeys.has(key)) {
17818
19968
  safeStorageSet._warnedKeys.add(key);
@@ -17836,6 +19986,8 @@ declare module 'bun:sqlite' {
17836
19986
  this.options = options || {};
17837
19987
  this.logger = createLogger({ logger: options.logger, debug: options.debug });
17838
19988
  this._persistenceFailureReported = false;
19989
+ this.saveStatusState = 'saved';
19990
+ this.saveStatusError = null;
17839
19991
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
17840
19992
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
17841
19993
  this.title = options.title || this.labId;
@@ -17843,6 +19995,7 @@ declare module 'bun:sqlite' {
17843
19995
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
17844
19996
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
17845
19997
  this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
19998
+ this.previewCsp = normalizePreviewCspOption(options.previewCsp);
17846
19999
  this._previewIsolationWarned = false;
17847
20000
  if (options.previewOrigin && !this.previewOrigin) {
17848
20001
  this.logger.warn(
@@ -17919,14 +20072,22 @@ declare module 'bun:sqlite' {
17919
20072
  path: '/',
17920
20073
  url: '',
17921
20074
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
20075
+ dockMode: (options && options.previewDock === 'split') ? 'split' : 'bottom', // 'bottom' | 'split'
20076
+ maximized: false,
20077
+ consoleOpen: false,
20078
+ consoleLogs: [],
17922
20079
  loading: false,
17923
20080
  error: null,
17924
- srcdoc: ''
20081
+ srcdoc: '',
20082
+ violations: []
17925
20083
  };
17926
20084
  this.previewHistory = [];
17927
20085
  this.previewHistoryIdx = -1;
17928
20086
  this._previewSwReady = false;
17929
20087
  this._previewSwRegistration = null;
20088
+ this._previewViolationHandler = null;
20089
+ this._swMessageHandler = null;
20090
+ this._beforeUnloadHandler = null;
17930
20091
  this._portToasts = new Map();
17931
20092
  this.isFullscreen = false;
17932
20093
  this.isRunning = false;
@@ -18026,7 +20187,9 @@ declare module 'bun:sqlite' {
18026
20187
  onCommand: (cmd) => this._handleReplCommand(cmd),
18027
20188
  onInterrupt: () => this._handleInterrupt()
18028
20189
  });
18029
- } catch (_) {}
20190
+ } catch (err) {
20191
+ this.logger.debug('PTY engine initialization skipped.', err);
20192
+ }
18030
20193
  }
18031
20194
 
18032
20195
  this.shell = null;
@@ -18052,7 +20215,7 @@ declare module 'bun:sqlite' {
18052
20215
  intoRoot: options.cloneIntoRoot !== false,
18053
20216
  branch: options.branch || undefined,
18054
20217
  fetchImpl: options.fetchImpl || undefined
18055
- }).catch(() => {});
20218
+ }).catch((err) => this.logger.warn('Initial cloneRepo failed.', err));
18056
20219
  }
18057
20220
  }
18058
20221
 
@@ -18077,7 +20240,9 @@ declare module 'bun:sqlite' {
18077
20240
  }
18078
20241
  });
18079
20242
  this._syncFilesToShellVfs();
18080
- } catch (_) {}
20243
+ } catch (err) {
20244
+ this.logger.debug('POSIX shell initialization skipped.', err);
20245
+ }
18081
20246
  }
18082
20247
  }
18083
20248
 
@@ -18103,7 +20268,9 @@ declare module 'bun:sqlite' {
18103
20268
  const u = new URL(fullUrl);
18104
20269
  parsedPort = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
18105
20270
  reqPath = u.pathname + (u.search || '');
18106
- } catch (_) {}
20271
+ } catch (err) {
20272
+ this.logger.debug('Could not parse portTable dispatch URL.', err);
20273
+ }
18107
20274
  const method = String((init && init.method) || 'GET').toUpperCase();
18108
20275
  try {
18109
20276
  const res = await origDispatch(url, init);
@@ -18115,7 +20282,9 @@ declare module 'bun:sqlite' {
18115
20282
  } else if (res && res.body !== undefined) {
18116
20283
  bodyText = String(res.body);
18117
20284
  }
18118
- } catch (_) {}
20285
+ } catch (err) {
20286
+ this.logger.debug('Could not read response body for HTTP trace.', err);
20287
+ }
18119
20288
  const responseHeaders = {};
18120
20289
  if (res && res.headers) {
18121
20290
  if (typeof res.headers.forEach === 'function') {
@@ -18127,7 +20296,9 @@ declare module 'bun:sqlite' {
18127
20296
  let formattedBody = bodyText;
18128
20297
  try {
18129
20298
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
18130
- } catch (_) {}
20299
+ } catch (err) {
20300
+ void err;
20301
+ }
18131
20302
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
18132
20303
  this.lastHttpTrace.push({
18133
20304
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -18176,7 +20347,9 @@ declare module 'bun:sqlite' {
18176
20347
  vfs.writeFileSync(absPath, String(content ?? ''));
18177
20348
  }
18178
20349
  }
18179
- } catch (_) {}
20350
+ } catch (err) {
20351
+ this.logger.debug('Could not sync files to shell VFS.', err);
20352
+ }
18180
20353
  }
18181
20354
 
18182
20355
  _emitEvent(name, detail) {
@@ -18198,7 +20371,9 @@ declare module 'bun:sqlite' {
18198
20371
  if (shortName !== fullName) {
18199
20372
  this.container.dispatchEvent(new CustomEvent(shortName, { detail, bubbles: true, composed: true }));
18200
20373
  }
18201
- } catch (_) {}
20374
+ } catch (err) {
20375
+ this.logger.debug(`CustomEvent dispatch for "${name}" failed.`, err);
20376
+ }
18202
20377
  }
18203
20378
 
18204
20379
  _resolvedTheme() {
@@ -18232,13 +20407,26 @@ declare module 'bun:sqlite' {
18232
20407
  }
18233
20408
  }
18234
20409
 
18235
- _reportPersistenceFailure() {
18236
- if (this._persistenceFailureReported) return;
20410
+ _reportPersistenceFailure(cause) {
20411
+ const error = isCodeLabError(cause)
20412
+ ? cause
20413
+ : new CodeLabError(
20414
+ 'E_SAVE',
20415
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.',
20416
+ { cause, recoverable: true, details: { labId: this.labId } }
20417
+ );
20418
+ this.saveStatusState = 'failed';
20419
+ this.saveStatusError = error;
20420
+ this._updateStatusBar();
20421
+ this._emitEvent('save-state', { status: 'failed', state: 'failed', labId: this.labId, error });
20422
+ if (this._persistenceFailureReported) return error;
18237
20423
  this._persistenceFailureReported = true;
18238
20424
  this.logger.warn(
18239
20425
  'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
18240
20426
  );
18241
- this._emitEvent('persistence-error', { labId: this.labId });
20427
+ this._emitEvent('persistence-error', { labId: this.labId, error });
20428
+ this._emitEvent('error', error);
20429
+ return error;
18242
20430
  }
18243
20431
 
18244
20432
  _saveState() {
@@ -18246,6 +20434,11 @@ declare module 'bun:sqlite' {
18246
20434
  const key = `${this.mode}:${this.lang}`;
18247
20435
  const customFiles = (this.savedState && this.savedState.customFiles) || {};
18248
20436
  customFiles[key] = { ...this.files };
20437
+ const hasSnapshot = Object.assign(
20438
+ {},
20439
+ (this.savedState && this.savedState.hasSnapshot) || {},
20440
+ { [key]: true }
20441
+ );
18249
20442
  const completedArr = Array.from(this.completedSteps);
18250
20443
  const state = {
18251
20444
  mode: this.mode,
@@ -18253,6 +20446,7 @@ declare module 'bun:sqlite' {
18253
20446
  activeStepIndex: this.activeStepIndex,
18254
20447
  completedSteps: completedArr,
18255
20448
  customFiles,
20449
+ hasSnapshot,
18256
20450
  openTabs: Array.isArray(this.openTabs) ? [...this.openTabs] : undefined,
18257
20451
  activeFile: this.activeFile,
18258
20452
  folders: Array.from(this.folders || []),
@@ -18262,22 +20456,49 @@ declare module 'bun:sqlite' {
18262
20456
  };
18263
20457
  this.savedState = state;
18264
20458
  if (this.options && this.options.persistState === false) {
20459
+ this.saveStatusState = 'saved';
20460
+ this.saveStatusError = null;
20461
+ this._updateStatusBar();
18265
20462
  return;
18266
20463
  }
20464
+ this._emitEvent('save-state', { status: 'saving', state: 'saving', labId: this.labId });
18267
20465
  const serialized = JSON.stringify(state);
20466
+ safeStorageSet._lastError = null;
20467
+ const recordErr = (err) => { safeStorageSet._lastError = err; };
18268
20468
  const persisted = [
18269
- safeStorageSet(this._storageKey(), serialized, this.logger),
20469
+ safeStorageSet(this._storageKey(), serialized, this.logger, recordErr),
18270
20470
  // Sync with host app sidebar & build overview progress trackers
18271
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
18272
- safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
20471
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
20472
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
18273
20473
  ];
18274
- if (persisted.includes(false)) this._reportPersistenceFailure();
20474
+ if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
20475
+ try {
20476
+ if (!this._idbStorage) {
20477
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
20478
+ }
20479
+ if (this._idbStorage && typeof this._idbStorage.save === 'function') {
20480
+ Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
20481
+ this.logger.debug('Async WorkspaceStorage save skipped.', err);
20482
+ });
20483
+ }
20484
+ } catch (err) {
20485
+ this.logger.debug('WorkspaceStorage initialization skipped.', err);
20486
+ }
20487
+ }
20488
+ if (persisted.includes(false)) {
20489
+ this._reportPersistenceFailure(safeStorageSet._lastError);
20490
+ } else {
20491
+ this.saveStatusState = 'saved';
20492
+ this.saveStatusError = null;
20493
+ this._updateStatusBar();
20494
+ this._emitEvent('save-state', { status: 'saved', state: 'saved', labId: this.labId });
20495
+ }
18275
20496
  } catch (err) {
18276
20497
  this.logger.error(
18277
20498
  'Failed to save workbench state.',
18278
20499
  err && err.message ? err.message : err
18279
20500
  );
18280
- this._reportPersistenceFailure();
20501
+ this._reportPersistenceFailure(err);
18281
20502
  }
18282
20503
  }
18283
20504
 
@@ -18300,7 +20521,9 @@ declare module 'bun:sqlite' {
18300
20521
  for (const [dep, ver] of Object.entries(pkgJsonDeps)) {
18301
20522
  npmSet.add(ver && ver !== '*' && ver !== 'latest' ? `${dep}@${String(ver).replace(/^[\^~]/, '')}` : dep);
18302
20523
  }
18303
- } catch (_) {}
20524
+ } catch (err) {
20525
+ this.logger.debug('Malformed package.json while detecting dependencies.', err);
20526
+ }
18304
20527
  }
18305
20528
 
18306
20529
  const reqRe = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -18347,6 +20570,7 @@ declare module 'bun:sqlite' {
18347
20570
  const dotEl = this.container.querySelector('#cl-status-dot');
18348
20571
  const textEl = this.container.querySelector('#cl-status-text');
18349
20572
  const fileEl = this.container.querySelector('#cl-status-file');
20573
+ const saveEl = this.container.querySelector('#cl-status-save');
18350
20574
  const durEl = this.container.querySelector('#cl-status-duration');
18351
20575
  const curEl = this.container.querySelector('#cl-status-cursor');
18352
20576
  const langEl = this.container.querySelector('#cl-status-lang');
@@ -18358,6 +20582,24 @@ declare module 'bun:sqlite' {
18358
20582
  }
18359
20583
  if (textEl) textEl.textContent = this.runtimeStatusText;
18360
20584
  if (fileEl) fileEl.textContent = this.activeFile || 'workspace';
20585
+ if (saveEl) {
20586
+ if (this.saveStatusState === 'failed') {
20587
+ saveEl.style.display = 'inline-flex';
20588
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save is-failed';
20589
+ saveEl.textContent = '⚠ Save failed (session-only)';
20590
+ const reason = this.saveStatusError && this.saveStatusError.message
20591
+ ? this.saveStatusError.message
20592
+ : 'localStorage is unavailable or quota exceeded';
20593
+ saveEl.setAttribute('title', `State is stored in memory only: ${reason}`);
20594
+ saveEl.setAttribute('data-save-state', 'failed');
20595
+ } else {
20596
+ saveEl.style.display = 'none';
20597
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save';
20598
+ saveEl.textContent = '';
20599
+ saveEl.removeAttribute('title');
20600
+ saveEl.setAttribute('data-save-state', 'saved');
20601
+ }
20602
+ }
18361
20603
  if (durEl) {
18362
20604
  if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
18363
20605
  durEl.style.display = 'inline-flex';
@@ -18395,6 +20637,9 @@ declare module 'bun:sqlite' {
18395
20637
  const key = `${this.mode}:${this.lang}`;
18396
20638
  const saved = this.savedState.customFiles?.[key];
18397
20639
  const base = this._getBaseFilesForModeAndLang(this.mode, this.lang);
20640
+ if (this.savedState && this.savedState.hasSnapshot && this.savedState.hasSnapshot[key] && saved && typeof saved === 'object') {
20641
+ return { ...saved };
20642
+ }
18398
20643
  if (saved && Object.keys(saved).length > 0) {
18399
20644
  return { ...base, ...saved };
18400
20645
  }
@@ -18607,6 +20852,10 @@ declare module 'bun:sqlite' {
18607
20852
  <div class="codelab-empty-editor" id="cl-empty-editor" style="display:none"></div>
18608
20853
  </div>
18609
20854
  </div>
20855
+
20856
+ <!-- Right-Hand Split Web Preview Pane -->
20857
+ <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>
20858
+ <div class="codelab-preview-split" id="cl-preview-split" aria-label="In-Browser Web Preview" style="display:none"></div>
18610
20859
  </div>
18611
20860
 
18612
20861
  <!-- Interactive Horizontal Splitter -->
@@ -18665,6 +20914,7 @@ declare module 'bun:sqlite' {
18665
20914
  </span>
18666
20915
  <span class="codelab-statusbar__sep">·</span>
18667
20916
  <span class="codelab-statusbar__item" id="cl-status-file">${escapeHtml(this.activeFile || 'workspace')}</span>
20917
+ <span class="codelab-statusbar__item codelab-statusbar__save" id="cl-status-save" data-save-state="saved" style="display:none"></span>
18668
20918
  </div>
18669
20919
  <div class="codelab-statusbar__right">
18670
20920
  <span class="codelab-statusbar__item" id="cl-status-duration" style="display:none"></span>
@@ -19919,7 +22169,9 @@ declare module 'bun:sqlite' {
19919
22169
  if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
19920
22170
  try {
19921
22171
  this.ptyEngine.writeStreamChunk(rawText, type);
19922
- } catch (_) {}
22172
+ } catch (err) {
22173
+ this.logger.debug('ptyEngine.writeStreamChunk failed.', err);
22174
+ }
19923
22175
  }
19924
22176
 
19925
22177
  this._activeStreamType = type;
@@ -20051,14 +22303,18 @@ declare module 'bun:sqlite' {
20051
22303
  if (this._activeCommandAbortController) {
20052
22304
  try {
20053
22305
  this._activeCommandAbortController.abort('SIGINT');
20054
- } catch (_) {}
22306
+ } catch (err) {
22307
+ this.logger.debug('AbortController.abort failed.', err);
22308
+ }
20055
22309
  this._activeCommandAbortController = null;
20056
22310
  }
20057
22311
 
20058
22312
  if (typeof root.CodeLabRuntime?.cancelWorkerExecution === 'function') {
20059
22313
  try {
20060
22314
  root.CodeLabRuntime.cancelWorkerExecution('SIGINT: Interrupted by user (Ctrl+C)', this.instanceId);
20061
- } catch (_) {}
22315
+ } catch (err) {
22316
+ this.logger.debug('cancelWorkerExecution failed.', err);
22317
+ }
20062
22318
  }
20063
22319
 
20064
22320
  this.isRunning = false;
@@ -20627,7 +22883,9 @@ declare module 'bun:sqlite' {
20627
22883
  try {
20628
22884
  const parsed = JSON.parse(responseBody);
20629
22885
  formattedBody = JSON.stringify(parsed, null, 2);
20630
- } catch (_) {}
22886
+ } catch (_) {
22887
+ formattedBody = responseBody;
22888
+ }
20631
22889
 
20632
22890
  const traceId = 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
20633
22891
  const traceItem = {
@@ -20700,7 +22958,9 @@ declare module 'bun:sqlite' {
20700
22958
  if (this.drawerTab === 'ports') this._renderDrawerBody();
20701
22959
  this._dismissPortToast(port);
20702
22960
  }));
20703
- } catch (_) {}
22961
+ } catch (err) {
22962
+ this.logger.warn('Failed to attach portTable event listeners.', err);
22963
+ }
20704
22964
  }
20705
22965
 
20706
22966
  _updatePortsPill() {
@@ -20774,16 +23034,55 @@ declare module 'bun:sqlite' {
20774
23034
  const url = (this.options && this.options.previewSwUrl) || 'preview-sw.js';
20775
23035
  try {
20776
23036
  const onMessage = (event) => this._handleServiceWorkerMessage(event);
23037
+ this._swMessageHandler = onMessage;
20777
23038
  if (typeof navigator.serviceWorker.addEventListener === 'function') {
20778
23039
  navigator.serviceWorker.addEventListener('message', onMessage);
20779
23040
  } else {
20780
23041
  navigator.serviceWorker.onmessage = onMessage;
20781
23042
  }
20782
23043
  navigator.serviceWorker.register(url, { scope: (this.options && this.options.previewSwScope) || './' })
20783
- .then((reg) => { this._previewSwRegistration = reg; this._previewSwReady = true; })
20784
- .catch(() => { this._previewSwReady = false; });
20785
- } catch (_) {
23044
+ .then((reg) => {
23045
+ this._previewSwRegistration = reg;
23046
+ this._previewSwReady = true;
23047
+ this._pushPreviewCsp(reg);
23048
+ })
23049
+ .catch((err) => {
23050
+ this._previewSwReady = false;
23051
+ this.logger.warn('Preview service worker registration failed; using the srcdoc fallback.', err);
23052
+ });
23053
+ } catch (err) {
20786
23054
  this._previewSwReady = false;
23055
+ this.logger.warn('Preview service worker is unavailable in this context.', err);
23056
+ }
23057
+ }
23058
+
23059
+ /**
23060
+ * The service worker cannot read workbench options, so the resolved policy
23061
+ * is pushed to it. Without this, `previewCsp: 'strict'` would only change
23062
+ * the srcdoc fallback and silently not the served previews.
23063
+ */
23064
+ _pushPreviewCsp(registration) {
23065
+ const policy = this._previewPolicy();
23066
+ const send = (worker) => {
23067
+ if (!worker || typeof worker.postMessage !== 'function') return;
23068
+ try {
23069
+ worker.postMessage({ type: 'codelab:config', csp: policy });
23070
+ } catch (err) {
23071
+ this.logger.warn('Could not deliver the preview CSP to the service worker.', err);
23072
+ }
23073
+ };
23074
+
23075
+ if (registration) {
23076
+ send(registration.active);
23077
+ send(registration.installing);
23078
+ send(registration.waiting);
23079
+ }
23080
+
23081
+ const sw = (typeof navigator !== 'undefined' && navigator.serviceWorker) ? navigator.serviceWorker : null;
23082
+ if (sw && sw.ready && typeof sw.ready.then === 'function') {
23083
+ sw.ready
23084
+ .then((readyReg) => { if (readyReg) send(readyReg.active); })
23085
+ .catch((err) => this.logger.warn('Preview service worker never became ready.', err));
20787
23086
  }
20788
23087
  }
20789
23088
 
@@ -20816,11 +23115,15 @@ declare module 'bun:sqlite' {
20816
23115
  } else if (res && res.headers) {
20817
23116
  Object.assign(outHeaders, res.headers);
20818
23117
  }
20819
- } catch (_) {}
23118
+ } catch (err) {
23119
+ this.logger.debug('Could not copy response headers in _dispatchPreviewRequest.', err);
23120
+ }
20820
23121
  let bodyText = '';
20821
23122
  try {
20822
23123
  bodyText = res && typeof res.text === 'function' ? await res.text() : String((res && res.body) || '');
20823
- } catch (_) {}
23124
+ } catch (err) {
23125
+ this.logger.debug('Could not read response body in _dispatchPreviewRequest.', err);
23126
+ }
20824
23127
  return {
20825
23128
  status: (res && res.status) || 200,
20826
23129
  statusText: (res && res.statusText) || 'OK',
@@ -20847,48 +23150,240 @@ declare module 'bun:sqlite' {
20847
23150
  const p = Number(port) || 3000;
20848
23151
  const rawPath = pathAndQuery || '/';
20849
23152
  const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
20850
- const base = this.previewOrigin || '';
23153
+ // Same-origin loopback by default. `previewOrigin` is only honoured once a
23154
+ // relay exists on that origin; pretending otherwise yields a 503.
23155
+ const base = (PREVIEW_RELAY_AVAILABLE && this.previewOrigin) ? this.previewOrigin : '';
20851
23156
  return `${base}/__preview/${p}${path}`;
20852
23157
  }
20853
23158
 
23159
+ /** Resolved CSP for preview documents served by this workbench. */
23160
+ _previewPolicy() {
23161
+ const origin = (typeof location !== 'undefined' && location && location.origin) ? location.origin : '';
23162
+ if (!PreviewCsp || typeof PreviewCsp.buildPreviewPolicy !== 'function') {
23163
+ return "default-src 'self'; object-src 'none'";
23164
+ }
23165
+ return PreviewCsp.buildPreviewPolicy(
23166
+ Object.assign({ hostOrigin: origin }, this.previewCsp.allow, { mode: this.previewCsp.mode })
23167
+ );
23168
+ }
23169
+
23170
+ /** Remote origins the current policy allows, for the preview toolbar. */
23171
+ _previewNetworkHosts() {
23172
+ if (!PreviewCsp || typeof PreviewCsp.describePreviewNetwork !== 'function') return [];
23173
+ return PreviewCsp.describePreviewNetwork(this.previewCsp);
23174
+ }
23175
+
20854
23176
  _warnPreviewIsolation() {
20855
- if (this.previewOrigin || this._previewIsolationWarned) return;
23177
+ if (!this.previewOrigin || this._previewIsolationWarned) return;
20856
23178
  this._previewIsolationWarned = true;
20857
- if (typeof console !== 'undefined' && typeof console.warn === 'function') {
20858
- console.warn(
20859
- '[code-lab] Web Preview runs on the host origin and can read host storage. ' +
20860
- 'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
20861
- );
20862
- }
23179
+ if (PREVIEW_RELAY_AVAILABLE) return;
23180
+ this.logger.warn(
23181
+ '`previewOrigin` was ignored: cross-origin previews need the preview relay ' +
23182
+ '(apps/preview-origin), which has not shipped yet. Previews run sandboxed on ' +
23183
+ 'the host origin: no host DOM, no host storage.'
23184
+ );
20863
23185
  }
20864
23186
 
20865
23187
  _injectPreviewCsp(html, port) {
20866
23188
  if (typeof html !== 'string' || !html) return html;
20867
- if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
20868
23189
 
20869
- const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
20870
- (/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
23190
+ const tags = [];
23191
+ if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
23192
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
23193
+ }
23194
+ if (!/<base\b/i.test(html)) {
23195
+ tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
23196
+ }
23197
+ if (html.indexOf('data-codelab-preview-shims') === -1 &&
23198
+ PreviewCsp && typeof PreviewCsp.buildPreviewShims === 'function') {
23199
+ tags.push(PreviewCsp.buildPreviewShims());
23200
+ }
23201
+ if (tags.length === 0) return html;
20871
23202
 
23203
+ const injection = tags.join('');
20872
23204
  if (/<head\b[^>]*>/i.test(html)) {
20873
- return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
23205
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
20874
23206
  }
20875
23207
  if (/<html\b[^>]*>/i.test(html)) {
20876
- return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
23208
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
23209
+ }
23210
+ return `<head>${injection}</head>${html}`;
23211
+ }
23212
+
23213
+ /**
23214
+ * Preview documents are sandboxed (opaque origin), so `event.origin` is the
23215
+ * string `"null"` and cannot be used to authenticate the sender. Match the
23216
+ * message source against the preview frame instead.
23217
+ */
23218
+ _installPreviewViolationListener() {
23219
+ if (this._previewViolationHandler) return;
23220
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
23221
+
23222
+ this._previewViolationHandler = (event) => {
23223
+ const data = event && event.data;
23224
+ if (!data || typeof data.type !== 'string') return;
23225
+ const iframe = this.container ? this.container.querySelector('#cl-preview-iframe') : null;
23226
+ if (!iframe) return;
23227
+ // `contentWindow` is unavailable on the mock DOM used by unit tests.
23228
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
23229
+
23230
+ if (data.type === 'codelab:preview-violation') {
23231
+ this._reportPreviewViolation(data);
23232
+ } else if (data.type === 'codelab:preview-console') {
23233
+ const level = ['log', 'warn', 'error', 'info'].includes(data.level) ? data.level : 'log';
23234
+ const args = Array.isArray(data.args) ? data.args : [data.args];
23235
+ const text = args.map((a) => String(a ?? '')).join(' ');
23236
+ this.terminalLogs.push({
23237
+ type: level === 'error' ? 'stderr' : 'stdout',
23238
+ text: `[Preview ${level.toUpperCase()}] ${text}`
23239
+ });
23240
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23241
+ this.previewState.consoleLogs.push({ level, text, timestamp: new Date().toLocaleTimeString() });
23242
+ if (this.previewState.consoleLogs.length > 200) this.previewState.consoleLogs.shift();
23243
+ this._updatePreviewConsoleUI();
23244
+ this._emitEvent('preview-console', { level, text, args });
23245
+ } else if (data.type === 'codelab:preview-error') {
23246
+ const msg = String(data.message || 'Uncaught runtime error');
23247
+ this.previewState.runtimeError = {
23248
+ message: msg,
23249
+ file: data.file ? String(data.file) : null,
23250
+ line: typeof data.line === 'number' ? data.line : null,
23251
+ col: typeof data.col === 'number' ? data.col : null,
23252
+ stack: data.stack ? String(data.stack) : null
23253
+ };
23254
+ this.terminalLogs.push({
23255
+ type: 'stderr',
23256
+ text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
23257
+ });
23258
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23259
+ this.previewState.consoleLogs.push({
23260
+ level: 'error',
23261
+ text: `${msg}${data.stack ? '\n' + String(data.stack) : ''}`,
23262
+ timestamp: new Date().toLocaleTimeString()
23263
+ });
23264
+ this._updatePreviewConsoleUI();
23265
+ this._emitEvent('preview-error', this.previewState.runtimeError);
23266
+ } else if (data.type === 'codelab:preview-error-clear') {
23267
+ this.previewState.runtimeError = null;
23268
+ } else if (data.type === 'codelab:preview-fetch') {
23269
+ const reqId = data.reqId || data.id;
23270
+ const targetPort = Number(data.port) || this.previewState.port || this._firstListeningPort() || 3000;
23271
+ const reqPath = data.path ? (String(data.path).startsWith('/') ? String(data.path) : '/' + String(data.path)) : '/';
23272
+ const targetUrl = String(data.url || `http://127.0.0.1:${targetPort}${reqPath}`);
23273
+ this._dispatchPreviewRequest({
23274
+ port: targetPort,
23275
+ url: targetUrl,
23276
+ method: data.method || 'GET',
23277
+ headers: data.headers || {},
23278
+ body: data.body !== undefined ? data.body : null
23279
+ })
23280
+ .then((res) => {
23281
+ const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
23282
+ if (netPill) netPill.textContent = `${(this.lastHttpTrace || []).length} reqs`;
23283
+ if (this.drawerTab === 'network') this._renderDrawerBody();
23284
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23285
+ iframe.contentWindow.postMessage({
23286
+ type: 'codelab:preview-fetch-res',
23287
+ reqId,
23288
+ id: reqId,
23289
+ status: res.status || 200,
23290
+ statusText: res.statusText || 'OK',
23291
+ headers: res.headers || {},
23292
+ body: res.body || ''
23293
+ }, '*');
23294
+ }
23295
+ })
23296
+ .catch((err) => {
23297
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23298
+ iframe.contentWindow.postMessage({
23299
+ type: 'codelab:preview-fetch-res',
23300
+ reqId,
23301
+ id: reqId,
23302
+ error: String((err && err.message) || err)
23303
+ }, '*');
23304
+ }
23305
+ });
23306
+ } else if (data.type === 'codelab:preview-navigate') {
23307
+ const navHref = data.href || (data.path ? (data.port ? `http://127.0.0.1:${data.port}${data.path}` : String(data.path)) : '');
23308
+ if (navHref) {
23309
+ this._previewGo(String(navHref));
23310
+ }
23311
+ } else if (data.type === 'codelab:preview-url-change') {
23312
+ if (data.path && typeof data.path === 'string') {
23313
+ this.previewState.path = data.path.startsWith('/') ? data.path : '/' + data.path;
23314
+ this.previewState.url = this._previewUrl();
23315
+ const input = this.container ? this.container.querySelector('#cl-preview-url-input') : null;
23316
+ if (input) input.value = this.previewState.url;
23317
+ }
23318
+ }
23319
+ };
23320
+ window.addEventListener('message', this._previewViolationHandler);
23321
+ }
23322
+
23323
+ _reportPreviewViolation(violation) {
23324
+ const blockedURI = String((violation && violation.blockedURI) || 'unknown');
23325
+ const directive = String((violation && violation.directive) || '');
23326
+ const key = `${directive}|${blockedURI}`;
23327
+ const state = this.previewState;
23328
+ state.violations = state.violations || [];
23329
+ if (state.violations.length < 20 && !state.violations.some((v) => v.key === key)) {
23330
+ state.violations.push({ key, directive, blockedURI });
23331
+ this._showToast(`Blocked by Content-Security-Policy: ${this._shortPreviewUrl(blockedURI)}`, 'error');
23332
+ this._emitEvent('preview-violation', { directive, blockedURI, violations: state.violations.slice() });
23333
+ }
23334
+ this._updatePreviewCspStatus();
23335
+ }
23336
+
23337
+ _shortPreviewUrl(raw) {
23338
+ const value = String(raw || '');
23339
+ try {
23340
+ const parsed = new URL(value);
23341
+ const path = parsed.pathname.length > 32 ? `${parsed.pathname.slice(0, 32)}…` : parsed.pathname;
23342
+ return `${parsed.host}${path === '/' ? '' : path}`;
23343
+ } catch (_) {
23344
+ // Not a URL (e.g. "inline" or "eval"); show it verbatim, truncated.
23345
+ return value.length > 48 ? `${value.slice(0, 48)}…` : value;
23346
+ }
23347
+ }
23348
+
23349
+ /** Update (or create) the CSP status chip in the preview toolbar. */
23350
+ _updatePreviewCspStatus() {
23351
+ if (!this.container) return;
23352
+ const chip = this.container.querySelector('#cl-preview-csp-status');
23353
+ if (!chip) return;
23354
+ const violations = (this.previewState && this.previewState.violations) || [];
23355
+ if (!violations.length) {
23356
+ chip.hidden = true;
23357
+ chip.textContent = '';
23358
+ chip.removeAttribute('title');
23359
+ return;
20877
23360
  }
20878
- return `<head>${tags}</head>${html}`;
23361
+ const last = violations[violations.length - 1];
23362
+ chip.hidden = false;
23363
+ chip.textContent = `Blocked: ${this._shortPreviewUrl(last.blockedURI)}`;
23364
+ chip.title = violations
23365
+ .map((v) => `${v.directive} → ${v.blockedURI}`)
23366
+ .join('\n');
20879
23367
  }
20880
23368
 
20881
23369
  _openWebPreview(port, path = '/') {
20882
23370
  const p = Number(port) || this._firstListeningPort() || 3000;
20883
23371
  this._warnPreviewIsolation();
23372
+ this._installPreviewViolationListener();
20884
23373
  this.previewState.port = p;
20885
23374
  this.previewState.path = path || '/';
20886
23375
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
20887
23376
  this.previewState.error = null;
23377
+ this.previewState.violations = [];
20888
23378
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
20889
23379
  this.previewHistory.push(this.previewState.url);
20890
23380
  this.previewHistoryIdx = this.previewHistory.length - 1;
20891
- this.switchDrawerTab('preview');
23381
+ if (this.previewState.dockMode === 'split') {
23382
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23383
+ if (splitHost) this._renderWebPreview(splitHost);
23384
+ } else {
23385
+ this.switchDrawerTab('preview');
23386
+ }
20892
23387
  return this._previewLoadPromise || Promise.resolve();
20893
23388
  }
20894
23389
 
@@ -20975,7 +23470,7 @@ declare module 'bun:sqlite' {
20975
23470
  try {
20976
23471
  const win = window.open(url, '_blank');
20977
23472
  if (win) {
20978
- try { win.opener = null; } catch (_) {}
23473
+ try { win.opener = null; } catch (err) { this.logger.debug('Could not clear win.opener.', err); }
20979
23474
  opened = true;
20980
23475
  }
20981
23476
  } catch (_) { opened = false; }
@@ -20997,7 +23492,9 @@ declare module 'bun:sqlite' {
20997
23492
  const u = new URL(url);
20998
23493
  port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
20999
23494
  path = u.pathname + (u.search || '') + (u.hash || '');
21000
- } catch (_) {}
23495
+ } catch (err) {
23496
+ this.logger.debug('Failed to parse preview URL; using fallback port/path.', err);
23497
+ }
21001
23498
  this.previewState.port = port;
21002
23499
  this.previewState.path = path;
21003
23500
  this.previewState.url = url;
@@ -21005,7 +23502,12 @@ declare module 'bun:sqlite' {
21005
23502
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
21006
23503
  this.previewHistory.push(url);
21007
23504
  this.previewHistoryIdx = this.previewHistory.length - 1;
21008
- this.switchDrawerTab('preview');
23505
+ if (this.previewState.dockMode === 'split') {
23506
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23507
+ if (splitHost) this._renderWebPreview(splitHost);
23508
+ } else {
23509
+ this.switchDrawerTab('preview');
23510
+ }
21009
23511
  return this._previewLoadPromise || Promise.resolve();
21010
23512
  }
21011
23513
 
@@ -21029,7 +23531,9 @@ declare module 'bun:sqlite' {
21029
23531
  const u = new URL(url);
21030
23532
  this.previewState.port = Number(u.port || 80);
21031
23533
  this.previewState.path = u.pathname + (u.search || '');
21032
- } catch (_) {}
23534
+ } catch (err) {
23535
+ this.logger.debug('Failed to parse preview history URL.', err);
23536
+ }
21033
23537
  const input = this.container.querySelector('#cl-preview-url-input');
21034
23538
  if (input) input.value = url;
21035
23539
  this._renderWebPreviewControls();
@@ -21044,6 +23548,94 @@ declare module 'bun:sqlite' {
21044
23548
  if (!['desktop', 'tablet', 'mobile'].includes(mode)) return;
21045
23549
  this.previewState.frameMode = mode;
21046
23550
  this._renderDrawerBody();
23551
+ if (this.previewState.dockMode === 'split') {
23552
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23553
+ if (splitHost) this._renderWebPreview(splitHost);
23554
+ }
23555
+ }
23556
+
23557
+ _togglePreviewDock() {
23558
+ this.previewState.dockMode = this.previewState.dockMode === 'split' ? 'bottom' : 'split';
23559
+ this._previewRenderKey = null;
23560
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23561
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23562
+ if (this.previewState.dockMode === 'split') {
23563
+ if (splitBar) splitBar.style.display = 'block';
23564
+ if (splitHost) {
23565
+ splitHost.style.display = 'flex';
23566
+ this._renderWebPreview(splitHost);
23567
+ }
23568
+ if (this.drawerTab === 'preview') {
23569
+ this.switchDrawerTab('terminal');
23570
+ } else {
23571
+ this._renderDrawerBody();
23572
+ }
23573
+ } else {
23574
+ if (splitBar) splitBar.style.display = 'none';
23575
+ if (splitHost) {
23576
+ splitHost.style.display = 'none';
23577
+ splitHost.innerHTML = '';
23578
+ }
23579
+ this.switchDrawerTab('preview');
23580
+ }
23581
+ if (this.editor && typeof this.editor.layout === 'function') {
23582
+ setTimeout(() => {
23583
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
23584
+ }, 30);
23585
+ }
23586
+ }
23587
+
23588
+ _togglePreviewMaximize() {
23589
+ this.previewState.maximized = !this.previewState.maximized;
23590
+ const previewEl = this.container ? this.container.querySelector('.codelab-preview') : null;
23591
+ if (previewEl) {
23592
+ previewEl.classList.toggle('is-maximized', Boolean(this.previewState.maximized));
23593
+ }
23594
+ const maxBtn = this.container ? this.container.querySelector('[data-cl-action="preview-maximize"]') : null;
23595
+ if (maxBtn) {
23596
+ maxBtn.classList.toggle('active', Boolean(this.previewState.maximized));
23597
+ }
23598
+ }
23599
+
23600
+ _togglePreviewConsole() {
23601
+ this.previewState.consoleOpen = !this.previewState.consoleOpen;
23602
+ this._updatePreviewConsoleUI();
23603
+ }
23604
+
23605
+ _clearPreviewConsole() {
23606
+ this.previewState.consoleLogs = [];
23607
+ this._updatePreviewConsoleUI();
23608
+ }
23609
+
23610
+ _updatePreviewConsoleUI() {
23611
+ if (!this.container) return;
23612
+ const consoleDrawer = this.container.querySelector('#cl-preview-console');
23613
+ const consoleBody = this.container.querySelector('#cl-preview-console-body');
23614
+ const consolePill = this.container.querySelector('#cl-preview-console-pill');
23615
+ const consoleBtn = this.container.querySelector('[data-cl-action="preview-console-toggle"]');
23616
+ const logs = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs : [];
23617
+ if (consolePill) {
23618
+ consolePill.textContent = String(logs.length);
23619
+ }
23620
+ if (consoleBtn) {
23621
+ consoleBtn.classList.toggle('active', Boolean(this.previewState.consoleOpen));
23622
+ }
23623
+ if (consoleDrawer) {
23624
+ consoleDrawer.style.display = this.previewState.consoleOpen ? 'flex' : 'none';
23625
+ }
23626
+ if (consoleBody) {
23627
+ if (logs.length === 0) {
23628
+ consoleBody.innerHTML = `<div class="codelab-preview-console__empty">No console output from preview frame yet.</div>`;
23629
+ } else {
23630
+ consoleBody.innerHTML = logs.map((entry) => `
23631
+ <div class="codelab-preview-console__row codelab-preview-console__row--${escapeHtml(entry.level || 'log')}">
23632
+ <span class="codelab-preview-console__time">${escapeHtml(entry.timestamp || '')}</span>
23633
+ <span class="codelab-preview-console__text">${escapeHtml(entry.text || '')}</span>
23634
+ </div>
23635
+ `).join('');
23636
+ consoleBody.scrollTop = consoleBody.scrollHeight;
23637
+ }
23638
+ }
21047
23639
  }
21048
23640
 
21049
23641
  _renderWebPreviewControls() {
@@ -21055,6 +23647,7 @@ declare module 'bun:sqlite' {
21055
23647
  if (backBtn) backBtn.disabled = this.previewHistoryIdx <= 0;
21056
23648
  const fwdBtn = this.container.querySelector('[data-cl-action="preview-forward"]');
21057
23649
  if (fwdBtn) fwdBtn.disabled = this.previewHistoryIdx >= this.previewHistory.length - 1;
23650
+ this._updatePreviewConsoleUI();
21058
23651
  }
21059
23652
 
21060
23653
  _popoutPreview() {
@@ -21063,9 +23656,11 @@ declare module 'bun:sqlite' {
21063
23656
  try {
21064
23657
  const u = new URL(url);
21065
23658
  popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
21066
- } catch (_) {}
23659
+ } catch (err) {
23660
+ this.logger.debug('Failed to parse popout preview URL.', err);
23661
+ }
21067
23662
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
21068
- try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
23663
+ try { window.open(popout, '_blank', 'noopener'); } catch (err) { this.logger.warn('window.open failed for preview popout.', err); }
21069
23664
  }
21070
23665
  return popout;
21071
23666
  }
@@ -21073,8 +23668,32 @@ declare module 'bun:sqlite' {
21073
23668
  _renderWebPreview(bodyEl) {
21074
23669
  if (!bodyEl) return;
21075
23670
  this._warnPreviewIsolation();
21076
- const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
21077
- if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
23671
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23672
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23673
+
23674
+ let targetHost = bodyEl;
23675
+ if (this.previewState.dockMode === 'split' && splitHost) {
23676
+ if (splitBar) splitBar.style.display = 'block';
23677
+ splitHost.style.display = 'flex';
23678
+ if (bodyEl !== splitHost) {
23679
+ bodyEl.innerHTML = `
23680
+ <div class="codelab-preview-split-notice">
23681
+ <span>Web Preview is docked to the right split pane.</span>
23682
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-dock-toggle">Dock to Bottom Drawer</button>
23683
+ </div>
23684
+ `;
23685
+ }
23686
+ targetHost = splitHost;
23687
+ } else {
23688
+ if (splitBar) splitBar.style.display = 'none';
23689
+ if (splitHost && bodyEl !== splitHost) {
23690
+ splitHost.style.display = 'none';
23691
+ splitHost.innerHTML = '';
23692
+ }
23693
+ }
23694
+
23695
+ const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this.previewState.dockMode}|${this._previewSwReady}`;
23696
+ if (targetHost.querySelector && targetHost.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
21078
23697
  this._renderWebPreviewControls();
21079
23698
  return;
21080
23699
  }
@@ -21092,8 +23711,24 @@ declare module 'bun:sqlite' {
21092
23711
  ? servers.map(s => `<option value="${s.port}" ${Number(s.port) === Number(this.previewState.port) ? 'selected' : ''}>Port ${s.port} · ${escapeHtml(s.name || 'server')}</option>`).join('')
21093
23712
  : `<option value="${this.previewState.port || 3000}">Port ${this.previewState.port || 3000}</option>`;
21094
23713
 
21095
- bodyEl.innerHTML = `
21096
- <div class="codelab-preview">
23714
+ const cspMode = (this.previewCsp && this.previewCsp.mode) || 'balanced';
23715
+ const cspHosts = this._previewNetworkHosts();
23716
+ const cspBadge = cspMode === 'strict'
23717
+ ? 'CSP: strict'
23718
+ : !cspHosts.length
23719
+ ? 'CSP: custom'
23720
+ : cspHosts.length === 1
23721
+ ? `CSP: ${cspHosts[0]}`
23722
+ : `CSP: ${cspHosts[0]} +${cspHosts.length - 1}`;
23723
+ const cspBadgeTitle = cspMode === 'strict'
23724
+ ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
23725
+ : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
23726
+
23727
+ const logsCount = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs.length : 0;
23728
+ const isSplit = this.previewState.dockMode === 'split';
23729
+
23730
+ targetHost.innerHTML = `
23731
+ <div class="codelab-preview ${this.previewState.maximized ? 'is-maximized' : ''}">
21097
23732
  <div class="codelab-preview-chrome">
21098
23733
  <div class="codelab-preview-nav">
21099
23734
  <button type="button" class="codelab-preview-btn" data-cl-action="preview-back" title="Back" ${this.previewHistoryIdx <= 0 ? 'disabled' : ''}>${CL_ICONS.arrowLeft || '←'}</button>
@@ -21107,10 +23742,31 @@ declare module 'bun:sqlite' {
21107
23742
  <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>
21108
23743
  <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>
21109
23744
  </div>
23745
+ <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
23746
+ <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
23747
+ <button type="button" class="codelab-preview-btn ${this.previewState.consoleOpen ? 'active' : ''}" data-cl-action="preview-console-toggle" title="Toggle Preview Console">
23748
+ ${CL_ICONS.terminal || '>_'} <span class="codelab-preview-console-pill" id="cl-preview-console-pill">${logsCount}</span>
23749
+ </button>
23750
+ <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'}">
23751
+ ${CL_ICONS.layout || '◫'}
23752
+ </button>
23753
+ <button type="button" class="codelab-preview-btn ${this.previewState.maximized ? 'active' : ''}" data-cl-action="preview-maximize" title="Maximize / Restore Preview">
23754
+ ${CL_ICONS.maximize || '⛶'}
23755
+ </button>
21110
23756
  <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>
21111
23757
  </div>
21112
23758
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
21113
- <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>
23759
+ <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>
23760
+ </div>
23761
+ <div class="codelab-preview-console" id="cl-preview-console" style="display:${this.previewState.consoleOpen ? 'flex' : 'none'}">
23762
+ <div class="codelab-preview-console__bar">
23763
+ <span>Preview Console</span>
23764
+ <div style="display:flex;align-items:center;gap:6px;">
23765
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-clear">Clear</button>
23766
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-toggle">Close</button>
23767
+ </div>
23768
+ </div>
23769
+ <div class="codelab-preview-console__body" id="cl-preview-console-body"></div>
21114
23770
  </div>
21115
23771
  ${servers.length
21116
23772
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -21123,6 +23779,8 @@ declare module 'bun:sqlite' {
21123
23779
  </div>`}
21124
23780
  </div>
21125
23781
  `;
23782
+ this._updatePreviewCspStatus();
23783
+ this._updatePreviewConsoleUI();
21126
23784
  this._loadPreviewFrame();
21127
23785
  }
21128
23786
 
@@ -21139,22 +23797,25 @@ declare module 'bun:sqlite' {
21139
23797
  this.previewState.error = 'No port selected';
21140
23798
  return Promise.resolve();
21141
23799
  }
23800
+ this._syncFilesToShellVfs();
21142
23801
  const fullUrl = this._previewUrl();
21143
23802
  this.previewState.loading = true;
21144
23803
  this.previewState.error = null;
21145
23804
 
21146
- if (this._previewSwReady) {
23805
+ if (this.options && this.options.useServiceWorkerForIframe === true && this._previewSwReady) {
21147
23806
  try {
21148
23807
  const u = new URL(fullUrl);
21149
23808
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
21150
23809
  iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
21151
23810
  this.previewState.loading = false;
21152
23811
  return Promise.resolve();
21153
- } catch (_) {}
23812
+ } catch (err) {
23813
+ this.logger.warn('Failed to set Service Worker preview URL; falling back to srcdoc.', err);
23814
+ }
21154
23815
  }
21155
23816
 
21156
- // Fallback (no Service Worker): dispatch via the virtual port table and
21157
- // inline the response with an injected <base> for relative asset URLs.
23817
+ // Direct virtual dispatch + srcdoc injection guarantees zero Service Worker
23818
+ // race conditions and 100% deterministic loading inside sandboxed iframes.
21158
23819
  return this._dispatchPreviewRequest({ port, url: fullUrl, method: 'GET' })
21159
23820
  .then((res) => {
21160
23821
  let body = res.body || '';
@@ -21216,7 +23877,7 @@ declare module 'bun:sqlite' {
21216
23877
  const full = dir === '/' ? '/' + entry : dir + '/' + entry;
21217
23878
  const rel = relPrefix ? relPrefix + '/' + entry : entry;
21218
23879
  let isDir = false;
21219
- try { isDir = vfs.statSync(full).isDirectory(); } catch (_) {}
23880
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
21220
23881
  if (isDir) {
21221
23882
  shellWorkspaceFolders.add(rel);
21222
23883
  walk(full, rel);
@@ -21224,7 +23885,9 @@ declare module 'bun:sqlite' {
21224
23885
  try {
21225
23886
  const content = String(vfs.readFileSync(full, 'utf8') ?? '');
21226
23887
  shellWorkspaceFiles.set(rel, content);
21227
- } catch (_) {}
23888
+ } catch (err) {
23889
+ this.logger.debug(`Could not read VFS file "${full}" during snapshot sync.`, err);
23890
+ }
21228
23891
  }
21229
23892
  }
21230
23893
  };
@@ -21526,6 +24189,27 @@ declare module 'bun:sqlite' {
21526
24189
  }
21527
24190
 
21528
24191
  _notifyCodeChange(filename, code) {
24192
+ if (this.shell && this.shell.vfs && filename && typeof this.shell.vfs.writeFileSync === 'function') {
24193
+ try {
24194
+ const clean = String(filename).replace(/^\/+/, '');
24195
+ const parts = clean.split('/');
24196
+ if (parts.length > 1 && typeof this.shell.vfs.mkdirSync === 'function') {
24197
+ this.shell.vfs.mkdirSync('/workspace/' + parts.slice(0, -1).join('/'), { recursive: true });
24198
+ }
24199
+ this.shell.vfs.writeFileSync('/workspace/' + clean, String(code ?? ''));
24200
+ } catch (err) {
24201
+ this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
24202
+ }
24203
+ }
24204
+ if ((this.drawerTab === 'preview' || (this.previewState && this.previewState.dockMode === 'split')) && this.previewState && this.previewState.port) {
24205
+ if (this._previewReloadTimer) {
24206
+ clearTimeout(this._previewReloadTimer);
24207
+ }
24208
+ this._previewReloadTimer = setTimeout(() => {
24209
+ this._previewReloadTimer = null;
24210
+ this._previewReload();
24211
+ }, 300);
24212
+ }
21529
24213
  if (this.onCodeChange) {
21530
24214
  try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
21531
24215
  }
@@ -21583,7 +24267,7 @@ declare module 'bun:sqlite' {
21583
24267
  if (fallbackWrap) fallbackWrap.style.display = 'none';
21584
24268
  if (mdPreview) mdPreview.style.display = 'none';
21585
24269
  if (this.editor) {
21586
- try { this.editor.setModel(null); } catch (_) {}
24270
+ try { this.editor.setModel(null); } catch (err) { this.logger.debug('editor.setModel(null) failed.', err); }
21587
24271
  }
21588
24272
  if (emptyEl) {
21589
24273
  emptyEl.style.display = 'flex';
@@ -21693,6 +24377,16 @@ declare module 'bun:sqlite' {
21693
24377
  };
21694
24378
  if (typeof document !== 'undefined') {
21695
24379
  document.addEventListener('keydown', this._escHandler);
24380
+ this._beforeUnloadHandler = () => {
24381
+ if (document.visibilityState === 'hidden') {
24382
+ try {
24383
+ this._saveState();
24384
+ } catch (err) {
24385
+ void err;
24386
+ }
24387
+ }
24388
+ };
24389
+ document.addEventListener('visibilitychange', this._beforeUnloadHandler);
21696
24390
  }
21697
24391
 
21698
24392
  this.container.addEventListener('keydown', e => {
@@ -21895,7 +24589,9 @@ declare module 'bun:sqlite' {
21895
24589
  textarea.select();
21896
24590
  document.execCommand('copy');
21897
24591
  document.body.removeChild(textarea);
21898
- } catch (_) {}
24592
+ } catch (err) {
24593
+ this.logger.warn('Clipboard fallback (execCommand) failed.', err);
24594
+ }
21899
24595
  };
21900
24596
 
21901
24597
  if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
@@ -22137,15 +24833,29 @@ declare module 'bun:sqlite' {
22137
24833
  this._previewSetFrameMode(actionBtn.dataset.mode);
22138
24834
  } else if (action === 'preview-popout') {
22139
24835
  this._popoutPreview();
24836
+ } else if (action === 'preview-dock-toggle') {
24837
+ this._togglePreviewDock();
24838
+ } else if (action === 'preview-maximize') {
24839
+ this._togglePreviewMaximize();
24840
+ } else if (action === 'preview-console-toggle') {
24841
+ this._togglePreviewConsole();
24842
+ } else if (action === 'preview-console-clear') {
24843
+ this._clearPreviewConsole();
22140
24844
  } else if (action === 'open-port-client') {
22141
- const port = actionBtn.dataset.port;
24845
+ const port = actionBtn.dataset.port || actionBtn.dataset.clPort;
22142
24846
  if (port) {
22143
24847
  this.httpClientUrl = `http://localhost:${port}/`;
24848
+ if (this.httpClientState) {
24849
+ this.httpClientState.url = `http://localhost:${port}/`;
24850
+ }
22144
24851
  this._renderDrawerBody();
22145
24852
  }
22146
24853
  } else if (action === 'stop-port') {
22147
- const port = Number(actionBtn.dataset.port);
24854
+ const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
22148
24855
  if (port) {
24856
+ if (this.portTable && typeof this.portTable.closeServer === 'function') {
24857
+ this.portTable.closeServer(port);
24858
+ }
22149
24859
  if (this.shell && this.shell.portTable && typeof this.shell.portTable.unregister === 'function') {
22150
24860
  this.shell.portTable.unregister(port);
22151
24861
  }
@@ -22155,18 +24865,32 @@ declare module 'bun:sqlite' {
22155
24865
  } else if (action === 'http-send') {
22156
24866
  this._sendHttpClientRequest();
22157
24867
  } else if (action === 'http-tab') {
22158
- this.httpActiveTab = actionBtn.dataset.httpTab || 'headers';
24868
+ const nextTab = actionBtn.dataset.tab || actionBtn.dataset.clHttpTab || actionBtn.dataset.httpTab || 'preview';
24869
+ this.httpActiveTab = nextTab;
24870
+ if (this.httpClientState) {
24871
+ this.httpClientState.activeResponseTab = nextTab;
24872
+ }
22159
24873
  this._renderDrawerBody();
22160
24874
  } else if (action === 'clear-net-traces') {
22161
24875
  this.lastHttpTrace = [];
22162
24876
  this.selectedNetTraceIdx = null;
24877
+ if (this.networkFilter) {
24878
+ this.networkFilter.selectedTraceId = null;
24879
+ }
22163
24880
  this._renderDrawerBody();
22164
24881
  } else if (action === 'select-net-trace') {
24882
+ const traceId = actionBtn.dataset.traceId || actionBtn.dataset.clTraceId || null;
22165
24883
  const idx = Number(actionBtn.dataset.traceIdx);
22166
24884
  this.selectedNetTraceIdx = Number.isNaN(idx) ? null : idx;
24885
+ if (this.networkFilter) {
24886
+ this.networkFilter.selectedTraceId = traceId;
24887
+ }
22167
24888
  this._renderDrawerBody();
22168
24889
  } else if (action === 'close-net-detail') {
22169
24890
  this.selectedNetTraceIdx = null;
24891
+ if (this.networkFilter) {
24892
+ this.networkFilter.selectedTraceId = null;
24893
+ }
22170
24894
  this._renderDrawerBody();
22171
24895
  }
22172
24896
  return;
@@ -22253,6 +24977,7 @@ declare module 'bun:sqlite' {
22253
24977
  { id: 'rename-active', label: 'File: Rename Active File...', shortcut: 'F2', action: () => { if (this.activeFile) this.startInlineRename('file', this.activeFile); } },
22254
24978
  { id: 'delete-active', label: 'File: Delete Active File', action: () => { if (this.activeFile) this.deleteFile(this.activeFile); } },
22255
24979
  { id: 'export-workspace', label: 'Workspace: Export Workspace as JSON', action: () => this.exportWorkspace({ download: true }) },
24980
+ { id: 'export-workspace-zip', label: 'Workspace: Export Project as ZIP Archive', action: () => this.exportProjectZip({ download: true }) },
22256
24981
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
22257
24982
  { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
22258
24983
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
@@ -22263,6 +24988,9 @@ declare module 'bun:sqlite' {
22263
24988
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
22264
24989
  } },
22265
24990
  { id: 'toggle-fullscreen', label: 'View: Toggle Fullscreen Workbench', action: () => this.toggleFullscreen() },
24991
+ { id: 'search-workspace', label: 'Search: Find & Replace Across Files...', shortcut: '⇧⌘F', action: () => this.showSearchModal() },
24992
+ { id: 'open-scm', label: 'Git: Source Control (Status, Stage & Commit)...', action: () => this.showScmModal() },
24993
+ { id: 'open-problems', label: 'View: Show Problems & Diagnostics...', action: () => this.showProblemsModal() },
22266
24994
  { id: 'open-packages', label: 'Packages: Manage NPM Dependencies & Runtime', action: () => this.showPackagesModal() },
22267
24995
  { id: 'git-clone', label: 'Git: Clone Public GitHub Repository...', action: () => this.showCloneRepoModal() }
22268
24996
  ];
@@ -22295,7 +25023,9 @@ declare module 'bun:sqlite' {
22295
25023
  input.focus();
22296
25024
  try {
22297
25025
  input.setSelectionRange(initialVal.length, initialVal.length);
22298
- } catch (_) {}
25026
+ } catch (err) {
25027
+ this.logger.debug('input.setSelectionRange failed in command palette.', err);
25028
+ }
22299
25029
 
22300
25030
  input.addEventListener('input', () => {
22301
25031
  this.paletteSelectedIndex = 0;
@@ -22568,7 +25298,7 @@ declare module 'bun:sqlite' {
22568
25298
  const onUp = ev => {
22569
25299
  vSplitter.classList.remove('is-dragging');
22570
25300
  shell.classList.remove('is-resizing');
22571
- try { vSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
25301
+ try { vSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22572
25302
  vSplitter.removeEventListener('pointermove', onMove);
22573
25303
  vSplitter.removeEventListener('pointerup', onUp);
22574
25304
  };
@@ -22609,7 +25339,7 @@ declare module 'bun:sqlite' {
22609
25339
  const onUp = ev => {
22610
25340
  hSplitter.classList.remove('is-dragging');
22611
25341
  shell.classList.remove('is-resizing-row');
22612
- try { hSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
25342
+ try { hSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22613
25343
  hSplitter.removeEventListener('pointermove', onMove);
22614
25344
  hSplitter.removeEventListener('pointerup', onUp);
22615
25345
  };
@@ -22636,7 +25366,7 @@ declare module 'bun:sqlite' {
22636
25366
  e.preventDefault();
22637
25367
  fSplitter.classList.add('is-dragging');
22638
25368
  shell.classList.add('is-resizing');
22639
- try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
25369
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
22640
25370
 
22641
25371
  const onMove = ev => {
22642
25372
  const ws = this.container.querySelector('.codelab-workspace');
@@ -22650,7 +25380,7 @@ declare module 'bun:sqlite' {
22650
25380
  const onUp = ev => {
22651
25381
  fSplitter.classList.remove('is-dragging');
22652
25382
  shell.classList.remove('is-resizing');
22653
- try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
25383
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
22654
25384
  fSplitter.removeEventListener('pointermove', onMove);
22655
25385
  fSplitter.removeEventListener('pointerup', onUp);
22656
25386
  this._saveState();
@@ -22660,6 +25390,42 @@ declare module 'bun:sqlite' {
22660
25390
  fSplitter.addEventListener('pointerup', onUp);
22661
25391
  });
22662
25392
  }
25393
+
25394
+ const pSplitter = this.container.querySelector('#cl-splitter-preview');
25395
+ if (pSplitter) {
25396
+ pSplitter.addEventListener('dblclick', () => {
25397
+ shell.style.setProperty('--cl-preview-split-width', '44%');
25398
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25399
+ });
25400
+
25401
+ pSplitter.addEventListener('pointerdown', e => {
25402
+ e.preventDefault();
25403
+ pSplitter.classList.add('is-dragging');
25404
+ shell.classList.add('is-resizing');
25405
+ try { pSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
25406
+
25407
+ const onMove = ev => {
25408
+ const ws = this.container.querySelector('.codelab-workspace');
25409
+ const rect = (ws || shell).getBoundingClientRect();
25410
+ const minW = 240;
25411
+ const maxW = Math.max(minW, Math.floor(rect.width * 0.65));
25412
+ const nextW = Math.min(maxW, Math.max(minW, Math.round(rect.right - ev.clientX)));
25413
+ shell.style.setProperty('--cl-preview-split-width', `${nextW}px`);
25414
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25415
+ };
25416
+
25417
+ const onUp = ev => {
25418
+ pSplitter.classList.remove('is-dragging');
25419
+ shell.classList.remove('is-resizing');
25420
+ try { pSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
25421
+ pSplitter.removeEventListener('pointermove', onMove);
25422
+ pSplitter.removeEventListener('pointerup', onUp);
25423
+ };
25424
+
25425
+ pSplitter.addEventListener('pointermove', onMove);
25426
+ pSplitter.addEventListener('pointerup', onUp);
25427
+ });
25428
+ }
22663
25429
  }
22664
25430
 
22665
25431
  selectStep(idx, shouldJump = true) {
@@ -22888,6 +25654,9 @@ declare module 'bun:sqlite' {
22888
25654
  if (this.savedState.customFiles) {
22889
25655
  delete this.savedState.customFiles[key];
22890
25656
  }
25657
+ if (this.savedState.hasSnapshot) {
25658
+ delete this.savedState.hasSnapshot[key];
25659
+ }
22891
25660
  this._saveState();
22892
25661
  this._syncAllModels();
22893
25662
  this._syncActiveFileToView();
@@ -22993,7 +25762,9 @@ declare module 'bun:sqlite' {
22993
25762
  if (this.files['package.json']) {
22994
25763
  try {
22995
25764
  pkgJson = JSON.parse(this.files['package.json']);
22996
- } catch (_) {}
25765
+ } catch (err) {
25766
+ this.logger.warn('Malformed package.json when adding dependency; reinitializing.', err);
25767
+ }
22997
25768
  }
22998
25769
  if (!pkgJson.dependencies || typeof pkgJson.dependencies !== 'object') {
22999
25770
  pkgJson.dependencies = {};
@@ -23654,6 +26425,219 @@ declare module 'bun:sqlite' {
23654
26425
  return true;
23655
26426
  }
23656
26427
 
26428
+ exportProjectZip(options = {}) {
26429
+ const zipMod = root.CodeLabZip;
26430
+ if (!zipMod || typeof zipMod.createZip !== 'function') {
26431
+ throw new Error('CodeLabZip engine is not loaded');
26432
+ }
26433
+ const bytes = zipMod.createZip(this.files || {});
26434
+ if (options && options.download) {
26435
+ try {
26436
+ if (typeof Blob !== 'undefined' && typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function' && typeof document !== 'undefined') {
26437
+ const blob = new Blob([bytes], { type: 'application/zip' });
26438
+ const url = URL.createObjectURL(blob);
26439
+ const a = document.createElement('a');
26440
+ a.href = url;
26441
+ a.download = `${this.labId || 'workspace'}.zip`;
26442
+ a.click();
26443
+ setTimeout(() => URL.revokeObjectURL(url), 500);
26444
+ }
26445
+ } catch (err) {
26446
+ this.logger.error('Failed to download project ZIP export.', err);
26447
+ }
26448
+ }
26449
+ return bytes;
26450
+ }
26451
+
26452
+ importProjectZip(zipBytes) {
26453
+ const zipMod = root.CodeLabZip;
26454
+ if (!zipMod || typeof zipMod.extractZip !== 'function') {
26455
+ throw new Error('CodeLabZip engine is not loaded');
26456
+ }
26457
+ const extracted = zipMod.extractZip(zipBytes);
26458
+ if (!extracted || typeof extracted !== 'object') return false;
26459
+ this.setFiles(extracted);
26460
+ this._syncFilesToShellVfs();
26461
+ return true;
26462
+ }
26463
+
26464
+ searchWorkspace(options) {
26465
+ const searchMod = root.CodeLabSearch;
26466
+ if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
26467
+ throw new Error('CodeLabSearch engine is not loaded');
26468
+ }
26469
+ return searchMod.searchInFiles(this.files || {}, options);
26470
+ }
26471
+
26472
+ replaceInWorkspace(options) {
26473
+ const searchMod = root.CodeLabSearch;
26474
+ if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
26475
+ throw new Error('CodeLabSearch engine is not loaded');
26476
+ }
26477
+ const res = searchMod.replaceInFiles(this.files || {}, options);
26478
+ if (res && res.files && res.filesModified > 0) {
26479
+ this.setFiles(res.files);
26480
+ this._syncFilesToShellVfs();
26481
+ }
26482
+ return res;
26483
+ }
26484
+
26485
+ getGitStatus() {
26486
+ const scmMod = root.CodeLabScm;
26487
+ if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
26488
+ return [];
26489
+ }
26490
+ const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
26491
+ return scmMod.computeGitStatus(gs, this.files || {});
26492
+ }
26493
+
26494
+ getDiagnostics() {
26495
+ const diagMod = root.CodeLabDiagnostics;
26496
+ if (!this._diagnosticsStore && diagMod && typeof diagMod.createDiagnosticsStore === 'function') {
26497
+ this._diagnosticsStore = diagMod.createDiagnosticsStore();
26498
+ }
26499
+ if (this._diagnosticsStore && typeof this._diagnosticsStore.getAll === 'function') {
26500
+ return this._diagnosticsStore.getAll();
26501
+ }
26502
+ return [];
26503
+ }
26504
+
26505
+ showSearchModal(initialQuery = '') {
26506
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
26507
+ if (!slot) return;
26508
+ const q = String(initialQuery || '');
26509
+ const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
26510
+ const rowsHtml = (results.matches || []).map((m) => `
26511
+ <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;">
26512
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
26513
+ </div>
26514
+ `).join('');
26515
+ slot.innerHTML = `
26516
+ <div class="codelab-modal-backdrop">
26517
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
26518
+ <div class="codelab-modal__header">
26519
+ <span>Search &amp; Replace Across Workspace</span>
26520
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
26521
+ </div>
26522
+ <div class="codelab-modal__body">
26523
+ <div style="display:flex;gap:8px;margin-bottom:8px;">
26524
+ <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
26525
+ <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
26526
+ </div>
26527
+ <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>
26528
+ </div>
26529
+ </div>
26530
+ </div>
26531
+ `;
26532
+ }
26533
+
26534
+ showScmModal() {
26535
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
26536
+ if (!slot) return;
26537
+ const statusList = this.getGitStatus();
26538
+ const rowsHtml = statusList.map((entry) => `
26539
+ <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;">
26540
+ <span>${escapeHtml(entry.path)}</span>
26541
+ <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
26542
+ </div>
26543
+ `).join('');
26544
+ slot.innerHTML = `
26545
+ <div class="codelab-modal-backdrop">
26546
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
26547
+ <div class="codelab-modal__header">
26548
+ <span>Source Control (Git Status)</span>
26549
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
26550
+ </div>
26551
+ <div class="codelab-modal__body">
26552
+ <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
26553
+ </div>
26554
+ </div>
26555
+ </div>
26556
+ `;
26557
+ }
26558
+
26559
+ showProblemsModal() {
26560
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
26561
+ if (!slot) return;
26562
+ const items = this.getDiagnostics();
26563
+ const rowsHtml = items.map((d) => `
26564
+ <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;">
26565
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
26566
+ </div>
26567
+ `).join('');
26568
+ slot.innerHTML = `
26569
+ <div class="codelab-modal-backdrop">
26570
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
26571
+ <div class="codelab-modal__header">
26572
+ <span>Problems (${items.length})</span>
26573
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
26574
+ </div>
26575
+ <div class="codelab-modal__body">
26576
+ <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>
26577
+ </div>
26578
+ </div>
26579
+ </div>
26580
+ `;
26581
+ }
26582
+
26583
+ _ensureTerminalSessions() {
26584
+ if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
26585
+ this._terminalSessions = [
26586
+ { id: 'session-1', name: 'bash-1', logs: this.terminalLogs || [] }
26587
+ ];
26588
+ this._activeTerminalSessionId = 'session-1';
26589
+ }
26590
+ return this._terminalSessions;
26591
+ }
26592
+
26593
+ listTerminalSessions() {
26594
+ const sessions = this._ensureTerminalSessions();
26595
+ return sessions.map((s) => ({
26596
+ id: s.id,
26597
+ name: s.name,
26598
+ active: s.id === this._activeTerminalSessionId,
26599
+ logCount: Array.isArray(s.logs) ? s.logs.length : 0
26600
+ }));
26601
+ }
26602
+
26603
+ createTerminalSession(name) {
26604
+ const sessions = this._ensureTerminalSessions();
26605
+ const nextNum = sessions.length + 1;
26606
+ const id = `session-${Date.now()}-${nextNum}`;
26607
+ const label = name ? String(name).trim() : `bash-${nextNum}`;
26608
+ const newLogs = [];
26609
+ sessions.push({ id, name: label, logs: newLogs });
26610
+ this._activeTerminalSessionId = id;
26611
+ this.terminalLogs = newLogs;
26612
+ this._renderDrawerBody();
26613
+ return id;
26614
+ }
26615
+
26616
+ switchTerminalSession(id) {
26617
+ const sessions = this._ensureTerminalSessions();
26618
+ const target = sessions.find((s) => s.id === id || s.name === id);
26619
+ if (!target) return false;
26620
+ this._activeTerminalSessionId = target.id;
26621
+ this.terminalLogs = target.logs;
26622
+ this._renderDrawerBody();
26623
+ return true;
26624
+ }
26625
+
26626
+ closeTerminalSession(id) {
26627
+ const sessions = this._ensureTerminalSessions();
26628
+ if (sessions.length <= 1) return false;
26629
+ const idx = sessions.findIndex((s) => s.id === id || s.name === id);
26630
+ if (idx === -1) return false;
26631
+ const removed = sessions.splice(idx, 1)[0];
26632
+ if (this._activeTerminalSessionId === removed.id) {
26633
+ const next = sessions[Math.max(0, idx - 1)] || sessions[0];
26634
+ this._activeTerminalSessionId = next.id;
26635
+ this.terminalLogs = next.logs;
26636
+ }
26637
+ this._renderDrawerBody();
26638
+ return true;
26639
+ }
26640
+
23657
26641
  getFiles() {
23658
26642
  return { ...this.files };
23659
26643
  }
@@ -23661,7 +26645,7 @@ declare module 'bun:sqlite' {
23661
26645
  setFiles(filesMap) {
23662
26646
  if (!filesMap || typeof filesMap !== 'object') return;
23663
26647
  for (const model of this.models.values()) {
23664
- try { model.dispose(); } catch (_) {}
26648
+ try { model.dispose(); } catch (err) { this.logger.debug('model.dispose failed during setFiles.', err); }
23665
26649
  }
23666
26650
  this.models.clear();
23667
26651
  this.files = {};
@@ -23751,7 +26735,9 @@ declare module 'bun:sqlite' {
23751
26735
  if (this.shell && this.shell.vfs && typeof this.shell.vfs.writeFile === 'function') {
23752
26736
  try {
23753
26737
  this.shell.vfs.writeFile('/workspace/' + clean, updated);
23754
- } catch (_) {}
26738
+ } catch (err) {
26739
+ this.logger.warn(`Failed to sync markdown task toggle for "${clean}" to VFS.`, err);
26740
+ }
23755
26741
  }
23756
26742
  this._notifyCodeChange(clean, updated);
23757
26743
  }
@@ -23971,9 +26957,26 @@ declare module 'bun:sqlite' {
23971
26957
 
23972
26958
  destroy() {
23973
26959
  this.stopExecution();
26960
+ if (this._previewReloadTimer) {
26961
+ clearTimeout(this._previewReloadTimer);
26962
+ this._previewReloadTimer = null;
26963
+ }
23974
26964
  if (this._escHandler && typeof document !== 'undefined') {
23975
26965
  document.removeEventListener('keydown', this._escHandler);
23976
26966
  }
26967
+ if (this._beforeUnloadHandler && typeof document !== 'undefined') {
26968
+ document.removeEventListener('visibilitychange', this._beforeUnloadHandler);
26969
+ }
26970
+ this._beforeUnloadHandler = null;
26971
+ if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
26972
+ window.removeEventListener('message', this._previewViolationHandler);
26973
+ }
26974
+ this._previewViolationHandler = null;
26975
+ if (this._swMessageHandler && typeof navigator !== 'undefined' && navigator.serviceWorker &&
26976
+ typeof navigator.serviceWorker.removeEventListener === 'function') {
26977
+ navigator.serviceWorker.removeEventListener('message', this._swMessageHandler);
26978
+ }
26979
+ this._swMessageHandler = null;
23977
26980
  if (this._themeObserver) {
23978
26981
  this._themeObserver.disconnect();
23979
26982
  }
@@ -24034,7 +27037,9 @@ declare module 'bun:sqlite' {
24034
27037
  if (jsonScript && jsonScript.textContent) {
24035
27038
  try {
24036
27039
  inlineConfig = JSON.parse(jsonScript.textContent);
24037
- } catch (_) {}
27040
+ } catch (err) {
27041
+ DEFAULT_LOGGER.warn('Failed to parse <script type="application/json"> inside <code-lab>.', err);
27042
+ }
24038
27043
  }
24039
27044
 
24040
27045
  // Parse optional files JSON attribute
@@ -24043,7 +27048,9 @@ declare module 'bun:sqlite' {
24043
27048
  if (filesAttr) {
24044
27049
  try {
24045
27050
  attrFiles = JSON.parse(filesAttr);
24046
- } catch (_) {}
27051
+ } catch (err) {
27052
+ DEFAULT_LOGGER.warn('Failed to parse files="" attribute on <code-lab>.', err);
27053
+ }
24047
27054
  }
24048
27055
 
24049
27056
  const labId = this.getAttribute('lab-id') || this.getAttribute('build-id') || this.dataset.labId || this.dataset.buildId || inlineConfig.id || inlineConfig.labId || 'custom-lab';
@@ -24086,6 +27093,19 @@ declare module 'bun:sqlite' {
24086
27093
  reset() { if (this._instance) this._instance.reset(); }
24087
27094
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
24088
27095
  importWorkspace(snap) { return this._instance ? this._instance.importWorkspace(snap) : false; }
27096
+ exportProjectZip(opts) { return this._instance ? this._instance.exportProjectZip(opts) : null; }
27097
+ importProjectZip(bytes) { return this._instance ? this._instance.importProjectZip(bytes) : false; }
27098
+ searchWorkspace(opts) { return this._instance ? this._instance.searchWorkspace(opts) : null; }
27099
+ replaceInWorkspace(opts) { return this._instance ? this._instance.replaceInWorkspace(opts) : null; }
27100
+ getGitStatus() { return this._instance ? this._instance.getGitStatus() : []; }
27101
+ getDiagnostics() { return this._instance ? this._instance.getDiagnostics() : []; }
27102
+ showSearchModal(q) { if (this._instance) this._instance.showSearchModal(q); }
27103
+ showScmModal() { if (this._instance) this._instance.showScmModal(); }
27104
+ showProblemsModal() { if (this._instance) this._instance.showProblemsModal(); }
27105
+ listTerminalSessions() { return this._instance ? this._instance.listTerminalSessions() : []; }
27106
+ createTerminalSession(name) { return this._instance ? this._instance.createTerminalSession(name) : null; }
27107
+ switchTerminalSession(id) { return this._instance ? this._instance.switchTerminalSession(id) : false; }
27108
+ closeTerminalSession(id) { return this._instance ? this._instance.closeTerminalSession(id) : false; }
24089
27109
  on(ev, fn) { return this._instance ? this._instance.on(ev, fn) : () => {}; }
24090
27110
  off(ev, fn) { if (this._instance) this._instance.off(ev, fn); }
24091
27111
  use(plugin, opts) { if (this._instance) this._instance.use(plugin, opts); return this; }
@@ -24120,9 +27140,42 @@ declare module 'bun:sqlite' {
24120
27140
  Workbench: CodeLabWorkbench,
24121
27141
  CodeLabWorkbench,
24122
27142
  CodeLabElement: CodeLabElementClass,
27143
+ CodeLabError,
27144
+ isCodeLabError,
27145
+ createLogger,
27146
+ Logger: _sharedLoggerMod || { LOG_PREFIX, CodeLabError, isCodeLabError, createLogger, DEFAULT_LOGGER },
27147
+ html,
27148
+ raw,
27149
+ isSafeHtml,
27150
+ escapeHtml,
27151
+ Html: _sharedHtmlMod || { html, raw, isSafeHtml, escapeHtml },
24123
27152
  Runtime: root.CodeLabRuntime,
24124
27153
  Shell: root.CodeLabShell,
24125
27154
  Terminal: root.CodeLabTerminal,
27155
+ zip: root.CodeLabZip || null,
27156
+ createZip: root.CodeLabZip ? root.CodeLabZip.createZip : null,
27157
+ extractZip: root.CodeLabZip ? root.CodeLabZip.extractZip : null,
27158
+ computeCrc32: root.CodeLabZip ? root.CodeLabZip.computeCrc32 : null,
27159
+ sanitizeZipPath: root.CodeLabZip ? root.CodeLabZip.sanitizeZipPath : null,
27160
+ storage: root.CodeLabStorage || null,
27161
+ WorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.WorkspaceStorage : null,
27162
+ createWorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.createWorkspaceStorage : null,
27163
+ search: root.CodeLabSearch || null,
27164
+ searchInFiles: root.CodeLabSearch ? root.CodeLabSearch.searchInFiles : null,
27165
+ replaceInFiles: root.CodeLabSearch ? root.CodeLabSearch.replaceInFiles : null,
27166
+ matchesGlob: root.CodeLabSearch ? root.CodeLabSearch.matchesGlob : null,
27167
+ escapeRegex: root.CodeLabSearch ? root.CodeLabSearch.escapeRegex : null,
27168
+ normalizeSearchPath: root.CodeLabSearch ? root.CodeLabSearch.normalizeSearchPath : null,
27169
+ diagnostics: root.CodeLabDiagnostics || null,
27170
+ DiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.DiagnosticsStore : null,
27171
+ createDiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.createDiagnosticsStore : null,
27172
+ scm: root.CodeLabScm || null,
27173
+ createGitState: root.CodeLabScm ? root.CodeLabScm.createGitState : null,
27174
+ computeGitStatus: root.CodeLabScm ? root.CodeLabScm.computeGitStatus : null,
27175
+ stageFile: root.CodeLabScm ? root.CodeLabScm.stageFile : null,
27176
+ unstageFile: root.CodeLabScm ? root.CodeLabScm.unstageFile : null,
27177
+ commitChanges: root.CodeLabScm ? root.CodeLabScm.commitChanges : null,
27178
+ computeShortCommitHash: root.CodeLabScm ? root.CodeLabScm.computeShortCommitHash : null,
24126
27179
  renderMarkdown: renderSimpleMarkdown,
24127
27180
  renderSimpleMarkdown: renderSimpleMarkdown,
24128
27181
  extensions: {
@@ -24185,6 +27238,48 @@ declare module 'bun:sqlite' {
24185
27238
  createVirtualHttp: CodeLabRuntime.createVirtualHttp,
24186
27239
  createVirtualNet: CodeLabRuntime.createVirtualNet,
24187
27240
  createVirtualPortTable: CodeLabRuntime.createVirtualPortTable,
27241
+ createWorkerRuntimeSource: CodeLabRuntime.createWorkerRuntimeSource,
27242
+ CodeLabCsp: CodeLabCsp,
27243
+ CodeLabLogger: CodeLabLogger,
27244
+ CodeLabHtml: CodeLabHtml,
27245
+ html: CodeLabHtml.html,
27246
+ raw: CodeLabHtml.raw,
27247
+ isSafeHtml: CodeLabHtml.isSafeHtml,
27248
+ escapeHtml: CodeLabHtml.escapeHtml,
27249
+ CodeLabError: CodeLabLogger.CodeLabError,
27250
+ isCodeLabError: CodeLabLogger.isCodeLabError,
27251
+ createLogger: CodeLabLogger.createLogger,
27252
+ DEFAULT_LOGGER: CodeLabLogger.DEFAULT_LOGGER,
27253
+ LOG_PREFIX: CodeLabLogger.LOG_PREFIX,
27254
+ CodeLabZip: CodeLabZip,
27255
+ zip: CodeLabZip,
27256
+ createZip: CodeLabZip.createZip,
27257
+ extractZip: CodeLabZip.extractZip,
27258
+ computeCrc32: CodeLabZip.computeCrc32,
27259
+ sanitizeZipPath: CodeLabZip.sanitizeZipPath,
27260
+ CodeLabStorage: CodeLabStorage,
27261
+ storage: CodeLabStorage,
27262
+ WorkspaceStorage: CodeLabStorage.WorkspaceStorage,
27263
+ createWorkspaceStorage: CodeLabStorage.createWorkspaceStorage,
27264
+ CodeLabSearch: CodeLabSearch,
27265
+ search: CodeLabSearch,
27266
+ searchInFiles: CodeLabSearch.searchInFiles,
27267
+ replaceInFiles: CodeLabSearch.replaceInFiles,
27268
+ matchesGlob: CodeLabSearch.matchesGlob,
27269
+ escapeRegex: CodeLabSearch.escapeRegex,
27270
+ normalizeSearchPath: CodeLabSearch.normalizeSearchPath,
27271
+ CodeLabDiagnostics: CodeLabDiagnostics,
27272
+ diagnostics: CodeLabDiagnostics,
27273
+ DiagnosticsStore: CodeLabDiagnostics.DiagnosticsStore,
27274
+ createDiagnosticsStore: CodeLabDiagnostics.createDiagnosticsStore,
27275
+ CodeLabScm: CodeLabScm,
27276
+ scm: CodeLabScm,
27277
+ createGitState: CodeLabScm.createGitState,
27278
+ computeGitStatus: CodeLabScm.computeGitStatus,
27279
+ stageFile: CodeLabScm.stageFile,
27280
+ unstageFile: CodeLabScm.unstageFile,
27281
+ commitChanges: CodeLabScm.commitChanges,
27282
+ computeShortCommitHash: CodeLabScm.computeShortCommitHash,
24188
27283
  default: CodeLab
24189
27284
  });
24190
27285
  }