@innovatorved/code-lab 0.1.6 → 0.1.8

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.
Files changed (51) hide show
  1. package/ARCHITECTURE.md +34 -16
  2. package/README.md +17 -7
  3. package/dist/code-lab.css +26 -0
  4. package/dist/code-lab.d.ts +271 -1
  5. package/dist/code-lab.esm.js +2909 -166
  6. package/dist/code-lab.js +2869 -164
  7. package/dist/csp.d.ts +86 -0
  8. package/dist/diagnostics.d.ts +43 -0
  9. package/dist/extensions/guided-lab.esm.js +66 -0
  10. package/dist/extensions/guided-lab.js +66 -0
  11. package/dist/html.d.ts +24 -0
  12. package/dist/index.d.ts +9 -1
  13. package/dist/logger.d.ts +60 -0
  14. package/dist/preview-sw.js +425 -11
  15. package/dist/runtime.d.ts +6 -27
  16. package/dist/runtime.esm.js +171 -31
  17. package/dist/runtime.js +171 -31
  18. package/dist/schemas.d.ts +366 -25
  19. package/dist/schemas.esm.js +73 -0
  20. package/dist/schemas.js +73 -0
  21. package/dist/scm.d.ts +77 -0
  22. package/dist/search.d.ts +75 -0
  23. package/dist/shell.d.ts +18 -47
  24. package/dist/shell.esm.js +236 -37
  25. package/dist/shell.js +236 -37
  26. package/dist/storage.d.ts +57 -0
  27. package/dist/terminal.d.ts +11 -87
  28. package/dist/terminal.esm.js +124 -7
  29. package/dist/terminal.js +124 -7
  30. package/dist/zip.d.ts +42 -0
  31. package/package.json +11 -3
  32. package/src/code-lab.css +26 -0
  33. package/src/csp.ts +396 -0
  34. package/src/diagnostics.ts +116 -0
  35. package/src/html.ts +88 -0
  36. package/src/index.ts +39 -1
  37. package/src/logger.ts +139 -0
  38. package/src/preview-sw.js +97 -11
  39. package/src/runtime.ts +132 -105
  40. package/src/schemas.ts +94 -1
  41. package/src/scm.ts +268 -0
  42. package/src/search.ts +389 -0
  43. package/src/shell.ts +410 -369
  44. package/src/storage.ts +377 -0
  45. package/src/terminal.ts +898 -918
  46. package/src/workbench.ts +926 -89
  47. package/src/zip.ts +326 -0
  48. package/src/runtime.js +0 -8229
  49. package/src/shell.js +0 -7257
  50. package/src/terminal.js +0 -1046
  51. package/src/workbench.js +0 -7353
package/src/workbench.ts CHANGED
@@ -7,13 +7,26 @@
7
7
  (function (root) {
8
8
  'use strict';
9
9
 
10
- let terminalModule = null;
11
- let shellModule = null;
12
- let runtimeModule = null;
10
+ const _sharedLoggerMod = (typeof CodeLabLogger !== 'undefined' && CodeLabLogger) ||
11
+ (root && root.CodeLabLogger) ||
12
+ null;
13
+ const _bootDebug = (_sharedLoggerMod && _sharedLoggerMod.DEFAULT_LOGGER && typeof _sharedLoggerMod.DEFAULT_LOGGER.debug === 'function')
14
+ ? (...args) => _sharedLoggerMod.DEFAULT_LOGGER.debug(...args)
15
+ : () => {};
16
+
17
+ let terminalModule = (root && root.CodeLabTerminal) || null;
18
+ let shellModule = (root && root.CodeLabShell) || null;
19
+ let runtimeModule = (root && root.CodeLabRuntime) || null;
13
20
  if (typeof require === 'function') {
14
- try { terminalModule = require('./terminal.js'); } catch (_) {}
15
- try { shellModule = require('./shell.js'); } catch (_) {}
16
- try { runtimeModule = require('./runtime.js'); } catch (_) {}
21
+ if (!terminalModule) {
22
+ try { terminalModule = require('./terminal.js'); } catch (err) { _bootDebug('optional terminal.js require failed', err); }
23
+ }
24
+ if (!shellModule) {
25
+ try { shellModule = require('./shell.js'); } catch (err) { _bootDebug('optional shell.js require failed', err); }
26
+ }
27
+ if (!runtimeModule) {
28
+ try { runtimeModule = require('./runtime.js'); } catch (err) { _bootDebug('optional runtime.js require failed', err); }
29
+ }
17
30
  }
18
31
  const CodeLabTerminal = (root && root.CodeLabTerminal) || terminalModule || {};
19
32
  const CodeLabShell = (root && root.CodeLabShell) || shellModule || {};
@@ -42,6 +55,10 @@
42
55
  const MONACO_BASE = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
43
56
  const STORAGE_PREFIX = 'sd-codelab-v1:';
44
57
 
58
+ // The bundler rewrites this literal from package.json at build time. Keeping
59
+ // the fallback in sync lets tests require src/workbench.js directly.
60
+ const CODELAB_VERSION = '0.1.8';
61
+
45
62
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
46
63
  const NODE_AMBIENT_DTS = `
47
64
  declare var require: (id: string) => any;
@@ -368,7 +385,14 @@ declare module 'bun:sqlite' {
368
385
  }
369
386
  `;
370
387
 
388
+ const _sharedHtmlMod = (typeof CodeLabHtml !== 'undefined' && CodeLabHtml) ||
389
+ (root && root.CodeLabHtml) ||
390
+ null;
391
+
371
392
  function escapeHtml(str) {
393
+ if (_sharedHtmlMod && typeof _sharedHtmlMod.escapeHtml === 'function') {
394
+ return _sharedHtmlMod.escapeHtml(str);
395
+ }
372
396
  if (str == null) return '';
373
397
  return String(str)
374
398
  .replace(/&/g, '&')
@@ -378,6 +402,45 @@ declare module 'bun:sqlite' {
378
402
  .replace(/'/g, ''');
379
403
  }
380
404
 
405
+ const isSafeHtml = (_sharedHtmlMod && _sharedHtmlMod.isSafeHtml) || ((v) => Boolean(v && typeof v === 'object' && typeof v.__html === 'string'));
406
+ const raw = (_sharedHtmlMod && _sharedHtmlMod.raw) || ((trusted) => ({ __html: String(trusted), toString() { return this.__html; } }));
407
+ const html = (_sharedHtmlMod && _sharedHtmlMod.html) || ((strings, ...values) => {
408
+ let out = strings[0] || '';
409
+ for (let i = 0; i < values.length; i++) {
410
+ const val = values[i];
411
+ out += (val == null || val === false) ? '' : (isSafeHtml(val) ? val.__html : escapeHtml(val));
412
+ out += strings[i + 1] || '';
413
+ }
414
+ return raw(out);
415
+ });
416
+
417
+ // Schemes that may appear in a rendered href. Everything else
418
+ // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
419
+ const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
420
+
421
+ function sanitizeUrl(raw) {
422
+ if (raw === null || raw === undefined) return '#';
423
+ const trimmed = String(raw).trim();
424
+ if (!trimmed) return '#';
425
+
426
+ // Browsers ignore C0 controls and zero-width characters while resolving a
427
+ // scheme, so `java\nscript:` and `java\u200Bscript:` still execute. Strip
428
+ // them before deciding what the scheme is, but return the original value
429
+ // when it is safe.
430
+ const normalized = trimmed.replace(/[\u0000-\u0020\u007F\u200B-\u200D\uFEFF]/g, '');
431
+ const schemeMatch = normalized.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
432
+
433
+ if (!schemeMatch) {
434
+ // No scheme: a fragment, an absolute path, or a relative path.
435
+ // Backslashes are treated as slashes by the URL parser and can turn a
436
+ // "relative" URL into a protocol-relative one, so reject those.
437
+ if (/^[\\/]{2}/.test(normalized) && !normalized.startsWith('/')) return '#';
438
+ return trimmed;
439
+ }
440
+
441
+ return SAFE_LINK_SCHEMES.has(schemeMatch[1].toLowerCase()) ? trimmed : '#';
442
+ }
443
+
381
444
  function formatErrorText(err) {
382
445
  if (!err) return '';
383
446
  if (typeof err === 'string') return err;
@@ -569,16 +632,11 @@ declare module 'bun:sqlite' {
569
632
  if (!str) return '';
570
633
  let text = String(str);
571
634
 
572
- // Markdown Links: [label](url "title") or [label](url)
573
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
574
- const cleanUrl = url.trim();
575
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
576
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`;
577
- });
578
-
579
- // Autolinks: <https://...>
580
- text = text.replace(/<(https?:\/\/[^>]+)>/g, (_, url) => {
581
- return `<a href="${escapeHtml(url)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`;
635
+ // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
636
+ text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
637
+ const cleanUrl = sanitizeUrl(url);
638
+ const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
639
+ return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
582
640
  });
583
641
 
584
642
  // Strikethrough: ~~del~~
@@ -773,8 +831,9 @@ declare module 'bun:sqlite' {
773
831
  // Normalize CRLF to LF
774
832
  text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
775
833
 
776
- // Prevent raw custom elements from executing within markdown previews
777
- text = text.replace(/<\/?code-lab(\s[^>]*)?>/gi, (m) => escapeHtml(m));
834
+ // NUL delimits internal placeholders. Strip author-supplied NULs so
835
+ // markdown cannot forge a code-block or autolink placeholder.
836
+ text = text.replace(/\u0000/g, '');
778
837
 
779
838
  // Phase 1: Fenced Code Block Extraction
780
839
  const codeBlocks = [];
@@ -797,6 +856,25 @@ declare module 'bun:sqlite' {
797
856
  return `\x00INLINECODE_${idx}\x00`;
798
857
  });
799
858
 
859
+ // Phase 2b: Autolinks are the only inline construct that uses angle
860
+ // brackets. Extract them before raw HTML is neutralized, then restore the
861
+ // anchors in Phase 7.
862
+ const autolinks = [];
863
+ text = text.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => {
864
+ const idx = autolinks.length;
865
+ const safe = sanitizeUrl(url);
866
+ autolinks.push(
867
+ `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
868
+ );
869
+ return `\x00AUTOLINK_${idx}\x00`;
870
+ });
871
+
872
+ // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
873
+ // escaping that one character turns any author-supplied markup into text
874
+ // without disturbing `>` blockquote syntax. From here on, every real tag
875
+ // in the output is generated by this renderer.
876
+ text = text.replace(/</g, '&lt;');
877
+
800
878
  // Phase 3: GitHub Callout Alerts & Blockquotes
801
879
  const calloutBlocks = [];
802
880
  text = text.replace(/(?:^[ \t]*>.*(?:\n|$))+/gm, (match) => {
@@ -874,7 +952,8 @@ declare module 'bun:sqlite' {
874
952
  .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
875
953
  .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
876
954
  .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
877
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '');
955
+ .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
956
+ .replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
878
957
 
879
958
  return finalHtml;
880
959
  }
@@ -1084,24 +1163,121 @@ declare module 'bun:sqlite' {
1084
1163
  let _workbenchInstanceCounter = 0;
1085
1164
  const _fallbackStorage = new Map();
1086
1165
 
1087
- function safeStorageGet(key) {
1166
+ // Preview CSP, storage shims and violation reporting live in src/csp.ts.
1167
+ // The build embeds that module in this bundle (and in dist/preview-sw.js), so
1168
+ // there is exactly one policy implementation shared by both sides.
1169
+ const PreviewCsp = (typeof CodeLabCsp !== 'undefined' && CodeLabCsp) ||
1170
+ (root && root.CodeLabCsp) ||
1171
+ null;
1172
+
1173
+ function normalizePreviewCspOption(raw) {
1174
+ if (PreviewCsp && typeof PreviewCsp.normalizePreviewCspConfig === 'function') {
1175
+ return PreviewCsp.normalizePreviewCspConfig(raw);
1176
+ }
1177
+ return { mode: 'balanced', allow: {} };
1178
+ }
1179
+
1180
+ // `previewOrigin` needs a relay page + service worker on that origin. Until
1181
+ // that ships, using it would silently *pretend* to isolate previews while the
1182
+ // iframe gets a 503 from a worker that has no clients on the preview origin.
1183
+ const PREVIEW_RELAY_AVAILABLE = false;
1184
+
1185
+ function normalizePreviewOrigin(raw) {
1186
+ if (raw === null || raw === undefined || raw === '') return null;
1187
+ try {
1188
+ const parsed = new URL(String(raw));
1189
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
1190
+ return parsed.origin;
1191
+ } catch (_) {
1192
+ return null;
1193
+ }
1194
+ }
1195
+
1196
+ const LOG_PREFIX = (_sharedLoggerMod && _sharedLoggerMod.LOG_PREFIX) || '[code-lab]';
1197
+ const CodeLabError = (_sharedLoggerMod && _sharedLoggerMod.CodeLabError) || class CodeLabError extends Error {
1198
+ constructor(code, message, options = {}) {
1199
+ super(message);
1200
+ this.name = 'CodeLabError';
1201
+ this.code = code || 'E_CODELAB';
1202
+ this.module = options.module || 'workbench';
1203
+ this.context = options.context || {};
1204
+ if (options.cause !== undefined) this.cause = options.cause;
1205
+ }
1206
+ };
1207
+ const isCodeLabError = (_sharedLoggerMod && _sharedLoggerMod.isCodeLabError) || ((value) => Boolean(value && typeof value === 'object' && value.name === 'CodeLabError' && typeof value.code === 'string'));
1208
+
1209
+ // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
1210
+ // into their own telemetry; `options.debug` enables verbose output. Errors
1211
+ // are never silently discarded.
1212
+ function createLogger(options = {}) {
1213
+ if (_sharedLoggerMod && typeof _sharedLoggerMod.createLogger === 'function') {
1214
+ return _sharedLoggerMod.createLogger({ module: 'workbench', ...options });
1215
+ }
1216
+ const sink = options.logger;
1217
+ const debugEnabled = options.debug === true;
1218
+
1219
+ const write = (level, args) => {
1220
+ if (level === 'debug' && !debugEnabled) return;
1221
+ if (sink && typeof sink[level] === 'function') {
1222
+ try {
1223
+ sink[level](...args);
1224
+ return;
1225
+ } catch (sinkErr) {
1226
+ const fallbackWarn = typeof console !== 'undefined' && typeof console.warn === 'function' ? console.warn : null;
1227
+ if (fallbackWarn) fallbackWarn(LOG_PREFIX, 'Host logger sink threw; falling back to console.', sinkErr);
1228
+ }
1229
+ }
1230
+ const fn = typeof console !== 'undefined' ? console[level] : null;
1231
+ if (typeof fn === 'function') fn(LOG_PREFIX, ...args);
1232
+ };
1233
+
1234
+ return {
1235
+ debug: (...args) => write('debug', args),
1236
+ info: (...args) => write('info', args),
1237
+ warn: (...args) => write('warn', args),
1238
+ error: (...args) => write('error', args)
1239
+ };
1240
+ }
1241
+
1242
+ const DEFAULT_LOGGER = createLogger();
1243
+
1244
+ function safeStorageGet(key, logger = DEFAULT_LOGGER) {
1088
1245
  try {
1089
1246
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
1090
- return localStorage.getItem(key);
1247
+ const value = localStorage.getItem(key);
1248
+ if (value !== null && value !== undefined) return value;
1091
1249
  }
1092
- } catch (_) {}
1250
+ } catch (err) {
1251
+ logger.warn(
1252
+ `localStorage.getItem("${key}") failed; using in-memory state.`,
1253
+ err && err.message ? err.message : err
1254
+ );
1255
+ }
1093
1256
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
1094
1257
  }
1095
1258
 
1096
- function safeStorageSet(key, value) {
1259
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER, onError = null) {
1097
1260
  const str = String(value);
1098
1261
  try {
1099
1262
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
1100
1263
  localStorage.setItem(key, str);
1101
- return;
1264
+ return true;
1265
+ }
1266
+ } catch (err) {
1267
+ if (typeof onError === 'function') {
1268
+ onError(err);
1102
1269
  }
1103
- } catch (_) {}
1270
+ if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
1271
+ if (!safeStorageSet._warnedKeys.has(key)) {
1272
+ safeStorageSet._warnedKeys.add(key);
1273
+ logger.warn(
1274
+ `localStorage.setItem("${key}") failed; keeping state in memory for this session.`,
1275
+ err && err.message ? err.message : err
1276
+ );
1277
+ }
1278
+ }
1104
1279
  _fallbackStorage.set(key, str);
1280
+ return false;
1105
1281
  }
1106
1282
 
1107
1283
  // ── CodeLabWorkbench Instance Class ──────────────────────────────────────
@@ -1112,12 +1288,25 @@ declare module 'bun:sqlite' {
1112
1288
  throw new Error('CodeLabWorkbench requires a valid DOM container element.');
1113
1289
  }
1114
1290
  this.options = options || {};
1291
+ this.logger = createLogger({ logger: options.logger, debug: options.debug });
1292
+ this._persistenceFailureReported = false;
1293
+ this.saveStatusState = 'saved';
1294
+ this.saveStatusError = null;
1115
1295
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
1116
1296
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
1117
1297
  this.title = options.title || this.labId;
1118
1298
  this.summary = options.summary || '';
1119
1299
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
1120
1300
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
1301
+ this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
1302
+ this.previewCsp = normalizePreviewCspOption(options.previewCsp);
1303
+ this._previewIsolationWarned = false;
1304
+ if (options.previewOrigin && !this.previewOrigin) {
1305
+ this.logger.warn(
1306
+ 'Ignoring invalid `previewOrigin`; expected an absolute http(s) origin ' +
1307
+ 'such as "https://preview.example.com".'
1308
+ );
1309
+ }
1121
1310
  this.explicitEntry = options.entry || null;
1122
1311
  this.explicitTestEntry = options.testEntry || options.testFile || null;
1123
1312
  this.backLabel = options.backLabel || 'Back to Build Guide';
@@ -1189,12 +1378,15 @@ declare module 'bun:sqlite' {
1189
1378
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
1190
1379
  loading: false,
1191
1380
  error: null,
1192
- srcdoc: ''
1381
+ srcdoc: '',
1382
+ violations: []
1193
1383
  };
1194
1384
  this.previewHistory = [];
1195
1385
  this.previewHistoryIdx = -1;
1196
1386
  this._previewSwReady = false;
1197
1387
  this._previewSwRegistration = null;
1388
+ this._previewViolationHandler = null;
1389
+ this._swMessageHandler = null;
1198
1390
  this._portToasts = new Map();
1199
1391
  this.isFullscreen = false;
1200
1392
  this.isRunning = false;
@@ -1294,7 +1486,9 @@ declare module 'bun:sqlite' {
1294
1486
  onCommand: (cmd) => this._handleReplCommand(cmd),
1295
1487
  onInterrupt: () => this._handleInterrupt()
1296
1488
  });
1297
- } catch (_) {}
1489
+ } catch (err) {
1490
+ this.logger.debug('PTY engine initialization skipped.', err);
1491
+ }
1298
1492
  }
1299
1493
 
1300
1494
  this.shell = null;
@@ -1320,7 +1514,7 @@ declare module 'bun:sqlite' {
1320
1514
  intoRoot: options.cloneIntoRoot !== false,
1321
1515
  branch: options.branch || undefined,
1322
1516
  fetchImpl: options.fetchImpl || undefined
1323
- }).catch(() => {});
1517
+ }).catch((err) => this.logger.warn('Initial cloneRepo failed.', err));
1324
1518
  }
1325
1519
  }
1326
1520
 
@@ -1345,7 +1539,9 @@ declare module 'bun:sqlite' {
1345
1539
  }
1346
1540
  });
1347
1541
  this._syncFilesToShellVfs();
1348
- } catch (_) {}
1542
+ } catch (err) {
1543
+ this.logger.debug('POSIX shell initialization skipped.', err);
1544
+ }
1349
1545
  }
1350
1546
  }
1351
1547
 
@@ -1371,7 +1567,9 @@ declare module 'bun:sqlite' {
1371
1567
  const u = new URL(fullUrl);
1372
1568
  parsedPort = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
1373
1569
  reqPath = u.pathname + (u.search || '');
1374
- } catch (_) {}
1570
+ } catch (err) {
1571
+ this.logger.debug('Could not parse portTable dispatch URL.', err);
1572
+ }
1375
1573
  const method = String((init && init.method) || 'GET').toUpperCase();
1376
1574
  try {
1377
1575
  const res = await origDispatch(url, init);
@@ -1383,7 +1581,9 @@ declare module 'bun:sqlite' {
1383
1581
  } else if (res && res.body !== undefined) {
1384
1582
  bodyText = String(res.body);
1385
1583
  }
1386
- } catch (_) {}
1584
+ } catch (err) {
1585
+ this.logger.debug('Could not read response body for HTTP trace.', err);
1586
+ }
1387
1587
  const responseHeaders = {};
1388
1588
  if (res && res.headers) {
1389
1589
  if (typeof res.headers.forEach === 'function') {
@@ -1395,7 +1595,9 @@ declare module 'bun:sqlite' {
1395
1595
  let formattedBody = bodyText;
1396
1596
  try {
1397
1597
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
1398
- } catch (_) {}
1598
+ } catch (err) {
1599
+ void err;
1600
+ }
1399
1601
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
1400
1602
  this.lastHttpTrace.push({
1401
1603
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -1444,7 +1646,9 @@ declare module 'bun:sqlite' {
1444
1646
  vfs.writeFileSync(absPath, String(content ?? ''));
1445
1647
  }
1446
1648
  }
1447
- } catch (_) {}
1649
+ } catch (err) {
1650
+ this.logger.debug('Could not sync files to shell VFS.', err);
1651
+ }
1448
1652
  }
1449
1653
 
1450
1654
  _emitEvent(name, detail) {
@@ -1455,7 +1659,7 @@ declare module 'bun:sqlite' {
1455
1659
  const handlers = this._eventListeners.get(key);
1456
1660
  if (handlers) {
1457
1661
  for (const fn of Array.from(handlers)) {
1458
- try { fn(detail); } catch (_) {}
1662
+ try { fn(detail); } catch (err) { this.logger.error(`Listener for "${key}" threw.`, err); }
1459
1663
  }
1460
1664
  }
1461
1665
  }
@@ -1466,7 +1670,9 @@ declare module 'bun:sqlite' {
1466
1670
  if (shortName !== fullName) {
1467
1671
  this.container.dispatchEvent(new CustomEvent(shortName, { detail, bubbles: true, composed: true }));
1468
1672
  }
1469
- } catch (_) {}
1673
+ } catch (err) {
1674
+ this.logger.debug(`CustomEvent dispatch for "${name}" failed.`, err);
1675
+ }
1470
1676
  }
1471
1677
 
1472
1678
  _resolvedTheme() {
@@ -1489,13 +1695,39 @@ declare module 'bun:sqlite' {
1489
1695
  return {};
1490
1696
  }
1491
1697
  try {
1492
- const raw = safeStorageGet(this._storageKey()) || safeStorageGet('sd_codelab_' + this.labId);
1698
+ const raw = safeStorageGet(this._storageKey(), this.logger) || safeStorageGet('sd_codelab_' + this.labId, this.logger);
1493
1699
  return raw ? JSON.parse(raw) : {};
1494
- } catch {
1700
+ } catch (err) {
1701
+ this.logger.warn(
1702
+ `Ignoring unreadable saved state for "${this.labId}".`,
1703
+ err && err.message ? err.message : err
1704
+ );
1495
1705
  return {};
1496
1706
  }
1497
1707
  }
1498
1708
 
1709
+ _reportPersistenceFailure(cause) {
1710
+ const error = isCodeLabError(cause)
1711
+ ? cause
1712
+ : new CodeLabError(
1713
+ 'E_SAVE',
1714
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.',
1715
+ { cause, recoverable: true, details: { labId: this.labId } }
1716
+ );
1717
+ this.saveStatusState = 'failed';
1718
+ this.saveStatusError = error;
1719
+ this._updateStatusBar();
1720
+ this._emitEvent('save-state', { status: 'failed', state: 'failed', labId: this.labId, error });
1721
+ if (this._persistenceFailureReported) return error;
1722
+ this._persistenceFailureReported = true;
1723
+ this.logger.warn(
1724
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
1725
+ );
1726
+ this._emitEvent('persistence-error', { labId: this.labId, error });
1727
+ this._emitEvent('error', error);
1728
+ return error;
1729
+ }
1730
+
1499
1731
  _saveState() {
1500
1732
  try {
1501
1733
  const key = `${this.mode}:${this.lang}`;
@@ -1517,14 +1749,36 @@ declare module 'bun:sqlite' {
1517
1749
  };
1518
1750
  this.savedState = state;
1519
1751
  if (this.options && this.options.persistState === false) {
1752
+ this.saveStatusState = 'saved';
1753
+ this.saveStatusError = null;
1754
+ this._updateStatusBar();
1520
1755
  return;
1521
1756
  }
1757
+ this._emitEvent('save-state', { status: 'saving', state: 'saving', labId: this.labId });
1522
1758
  const serialized = JSON.stringify(state);
1523
- safeStorageSet(this._storageKey(), serialized);
1524
- // Sync with host app sidebar & build overview progress trackers
1525
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr));
1526
- safeStorageSet('sd_codelab_' + this.labId, serialized);
1527
- } catch {}
1759
+ safeStorageSet._lastError = null;
1760
+ const recordErr = (err) => { safeStorageSet._lastError = err; };
1761
+ const persisted = [
1762
+ safeStorageSet(this._storageKey(), serialized, this.logger, recordErr),
1763
+ // Sync with host app sidebar & build overview progress trackers
1764
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
1765
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
1766
+ ];
1767
+ if (persisted.includes(false)) {
1768
+ this._reportPersistenceFailure(safeStorageSet._lastError);
1769
+ } else {
1770
+ this.saveStatusState = 'saved';
1771
+ this.saveStatusError = null;
1772
+ this._updateStatusBar();
1773
+ this._emitEvent('save-state', { status: 'saved', state: 'saved', labId: this.labId });
1774
+ }
1775
+ } catch (err) {
1776
+ this.logger.error(
1777
+ 'Failed to save workbench state.',
1778
+ err && err.message ? err.message : err
1779
+ );
1780
+ this._reportPersistenceFailure(err);
1781
+ }
1528
1782
  }
1529
1783
 
1530
1784
  _detectPackages() {
@@ -1546,7 +1800,9 @@ declare module 'bun:sqlite' {
1546
1800
  for (const [dep, ver] of Object.entries(pkgJsonDeps)) {
1547
1801
  npmSet.add(ver && ver !== '*' && ver !== 'latest' ? `${dep}@${String(ver).replace(/^[\^~]/, '')}` : dep);
1548
1802
  }
1549
- } catch (_) {}
1803
+ } catch (err) {
1804
+ this.logger.debug('Malformed package.json while detecting dependencies.', err);
1805
+ }
1550
1806
  }
1551
1807
 
1552
1808
  const reqRe = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -1593,6 +1849,7 @@ declare module 'bun:sqlite' {
1593
1849
  const dotEl = this.container.querySelector('#cl-status-dot');
1594
1850
  const textEl = this.container.querySelector('#cl-status-text');
1595
1851
  const fileEl = this.container.querySelector('#cl-status-file');
1852
+ const saveEl = this.container.querySelector('#cl-status-save');
1596
1853
  const durEl = this.container.querySelector('#cl-status-duration');
1597
1854
  const curEl = this.container.querySelector('#cl-status-cursor');
1598
1855
  const langEl = this.container.querySelector('#cl-status-lang');
@@ -1604,6 +1861,24 @@ declare module 'bun:sqlite' {
1604
1861
  }
1605
1862
  if (textEl) textEl.textContent = this.runtimeStatusText;
1606
1863
  if (fileEl) fileEl.textContent = this.activeFile || 'workspace';
1864
+ if (saveEl) {
1865
+ if (this.saveStatusState === 'failed') {
1866
+ saveEl.style.display = 'inline-flex';
1867
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save is-failed';
1868
+ saveEl.textContent = '⚠ Save failed (session-only)';
1869
+ const reason = this.saveStatusError && this.saveStatusError.message
1870
+ ? this.saveStatusError.message
1871
+ : 'localStorage is unavailable or quota exceeded';
1872
+ saveEl.setAttribute('title', `State is stored in memory only: ${reason}`);
1873
+ saveEl.setAttribute('data-save-state', 'failed');
1874
+ } else {
1875
+ saveEl.style.display = 'none';
1876
+ saveEl.className = 'codelab-statusbar__item codelab-statusbar__save';
1877
+ saveEl.textContent = '';
1878
+ saveEl.removeAttribute('title');
1879
+ saveEl.setAttribute('data-save-state', 'saved');
1880
+ }
1881
+ }
1607
1882
  if (durEl) {
1608
1883
  if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
1609
1884
  durEl.style.display = 'inline-flex';
@@ -1911,6 +2186,7 @@ declare module 'bun:sqlite' {
1911
2186
  </span>
1912
2187
  <span class="codelab-statusbar__sep">·</span>
1913
2188
  <span class="codelab-statusbar__item" id="cl-status-file">${escapeHtml(this.activeFile || 'workspace')}</span>
2189
+ <span class="codelab-statusbar__item codelab-statusbar__save" id="cl-status-save" data-save-state="saved" style="display:none"></span>
1914
2190
  </div>
1915
2191
  <div class="codelab-statusbar__right">
1916
2192
  <span class="codelab-statusbar__item" id="cl-status-duration" style="display:none"></span>
@@ -3165,7 +3441,9 @@ declare module 'bun:sqlite' {
3165
3441
  if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
3166
3442
  try {
3167
3443
  this.ptyEngine.writeStreamChunk(rawText, type);
3168
- } catch (_) {}
3444
+ } catch (err) {
3445
+ this.logger.debug('ptyEngine.writeStreamChunk failed.', err);
3446
+ }
3169
3447
  }
3170
3448
 
3171
3449
  this._activeStreamType = type;
@@ -3297,14 +3575,18 @@ declare module 'bun:sqlite' {
3297
3575
  if (this._activeCommandAbortController) {
3298
3576
  try {
3299
3577
  this._activeCommandAbortController.abort('SIGINT');
3300
- } catch (_) {}
3578
+ } catch (err) {
3579
+ this.logger.debug('AbortController.abort failed.', err);
3580
+ }
3301
3581
  this._activeCommandAbortController = null;
3302
3582
  }
3303
3583
 
3304
3584
  if (typeof root.CodeLabRuntime?.cancelWorkerExecution === 'function') {
3305
3585
  try {
3306
3586
  root.CodeLabRuntime.cancelWorkerExecution('SIGINT: Interrupted by user (Ctrl+C)', this.instanceId);
3307
- } catch (_) {}
3587
+ } catch (err) {
3588
+ this.logger.debug('cancelWorkerExecution failed.', err);
3589
+ }
3308
3590
  }
3309
3591
 
3310
3592
  this.isRunning = false;
@@ -3873,7 +4155,9 @@ declare module 'bun:sqlite' {
3873
4155
  try {
3874
4156
  const parsed = JSON.parse(responseBody);
3875
4157
  formattedBody = JSON.stringify(parsed, null, 2);
3876
- } catch (_) {}
4158
+ } catch (_) {
4159
+ formattedBody = responseBody;
4160
+ }
3877
4161
 
3878
4162
  const traceId = 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
3879
4163
  const traceItem = {
@@ -3946,7 +4230,9 @@ declare module 'bun:sqlite' {
3946
4230
  if (this.drawerTab === 'ports') this._renderDrawerBody();
3947
4231
  this._dismissPortToast(port);
3948
4232
  }));
3949
- } catch (_) {}
4233
+ } catch (err) {
4234
+ this.logger.warn('Failed to attach portTable event listeners.', err);
4235
+ }
3950
4236
  }
3951
4237
 
3952
4238
  _updatePortsPill() {
@@ -4020,16 +4306,55 @@ declare module 'bun:sqlite' {
4020
4306
  const url = (this.options && this.options.previewSwUrl) || 'preview-sw.js';
4021
4307
  try {
4022
4308
  const onMessage = (event) => this._handleServiceWorkerMessage(event);
4309
+ this._swMessageHandler = onMessage;
4023
4310
  if (typeof navigator.serviceWorker.addEventListener === 'function') {
4024
4311
  navigator.serviceWorker.addEventListener('message', onMessage);
4025
4312
  } else {
4026
4313
  navigator.serviceWorker.onmessage = onMessage;
4027
4314
  }
4028
4315
  navigator.serviceWorker.register(url, { scope: (this.options && this.options.previewSwScope) || './' })
4029
- .then((reg) => { this._previewSwRegistration = reg; this._previewSwReady = true; })
4030
- .catch(() => { this._previewSwReady = false; });
4031
- } catch (_) {
4316
+ .then((reg) => {
4317
+ this._previewSwRegistration = reg;
4318
+ this._previewSwReady = true;
4319
+ this._pushPreviewCsp(reg);
4320
+ })
4321
+ .catch((err) => {
4322
+ this._previewSwReady = false;
4323
+ this.logger.warn('Preview service worker registration failed; using the srcdoc fallback.', err);
4324
+ });
4325
+ } catch (err) {
4032
4326
  this._previewSwReady = false;
4327
+ this.logger.warn('Preview service worker is unavailable in this context.', err);
4328
+ }
4329
+ }
4330
+
4331
+ /**
4332
+ * The service worker cannot read workbench options, so the resolved policy
4333
+ * is pushed to it. Without this, `previewCsp: 'strict'` would only change
4334
+ * the srcdoc fallback and silently not the served previews.
4335
+ */
4336
+ _pushPreviewCsp(registration) {
4337
+ const policy = this._previewPolicy();
4338
+ const send = (worker) => {
4339
+ if (!worker || typeof worker.postMessage !== 'function') return;
4340
+ try {
4341
+ worker.postMessage({ type: 'codelab:config', csp: policy });
4342
+ } catch (err) {
4343
+ this.logger.warn('Could not deliver the preview CSP to the service worker.', err);
4344
+ }
4345
+ };
4346
+
4347
+ if (registration) {
4348
+ send(registration.active);
4349
+ send(registration.installing);
4350
+ send(registration.waiting);
4351
+ }
4352
+
4353
+ const sw = (typeof navigator !== 'undefined' && navigator.serviceWorker) ? navigator.serviceWorker : null;
4354
+ if (sw && sw.ready && typeof sw.ready.then === 'function') {
4355
+ sw.ready
4356
+ .then((readyReg) => { if (readyReg) send(readyReg.active); })
4357
+ .catch((err) => this.logger.warn('Preview service worker never became ready.', err));
4033
4358
  }
4034
4359
  }
4035
4360
 
@@ -4062,11 +4387,15 @@ declare module 'bun:sqlite' {
4062
4387
  } else if (res && res.headers) {
4063
4388
  Object.assign(outHeaders, res.headers);
4064
4389
  }
4065
- } catch (_) {}
4390
+ } catch (err) {
4391
+ this.logger.debug('Could not copy response headers in _dispatchPreviewRequest.', err);
4392
+ }
4066
4393
  let bodyText = '';
4067
4394
  try {
4068
4395
  bodyText = res && typeof res.text === 'function' ? await res.text() : String((res && res.body) || '');
4069
- } catch (_) {}
4396
+ } catch (err) {
4397
+ this.logger.debug('Could not read response body in _dispatchPreviewRequest.', err);
4398
+ }
4070
4399
  return {
4071
4400
  status: (res && res.status) || 200,
4072
4401
  statusText: (res && res.statusText) || 'OK',
@@ -4089,12 +4418,174 @@ declare module 'bun:sqlite' {
4089
4418
  return `http://127.0.0.1:${port}${path}`;
4090
4419
  }
4091
4420
 
4421
+ _previewFrameUrl(port, pathAndQuery = '/') {
4422
+ const p = Number(port) || 3000;
4423
+ const rawPath = pathAndQuery || '/';
4424
+ const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
4425
+ // Same-origin loopback by default. `previewOrigin` is only honoured once a
4426
+ // relay exists on that origin; pretending otherwise yields a 503.
4427
+ const base = (PREVIEW_RELAY_AVAILABLE && this.previewOrigin) ? this.previewOrigin : '';
4428
+ return `${base}/__preview/${p}${path}`;
4429
+ }
4430
+
4431
+ /** Resolved CSP for preview documents served by this workbench. */
4432
+ _previewPolicy() {
4433
+ const origin = (typeof location !== 'undefined' && location && location.origin) ? location.origin : '';
4434
+ if (!PreviewCsp || typeof PreviewCsp.buildPreviewPolicy !== 'function') {
4435
+ return "default-src 'self'; object-src 'none'";
4436
+ }
4437
+ return PreviewCsp.buildPreviewPolicy(
4438
+ Object.assign({ hostOrigin: origin }, this.previewCsp.allow, { mode: this.previewCsp.mode })
4439
+ );
4440
+ }
4441
+
4442
+ /** Remote origins the current policy allows, for the preview toolbar. */
4443
+ _previewNetworkHosts() {
4444
+ if (!PreviewCsp || typeof PreviewCsp.describePreviewNetwork !== 'function') return [];
4445
+ return PreviewCsp.describePreviewNetwork(this.previewCsp);
4446
+ }
4447
+
4448
+ _warnPreviewIsolation() {
4449
+ if (!this.previewOrigin || this._previewIsolationWarned) return;
4450
+ this._previewIsolationWarned = true;
4451
+ if (PREVIEW_RELAY_AVAILABLE) return;
4452
+ this.logger.warn(
4453
+ '`previewOrigin` was ignored: cross-origin previews need the preview relay ' +
4454
+ '(apps/preview-origin), which has not shipped yet. Previews run sandboxed on ' +
4455
+ 'the host origin: no host DOM, no host storage.'
4456
+ );
4457
+ }
4458
+
4459
+ _injectPreviewCsp(html, port) {
4460
+ if (typeof html !== 'string' || !html) return html;
4461
+
4462
+ const tags = [];
4463
+ if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
4464
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
4465
+ }
4466
+ if (!/<base\b/i.test(html)) {
4467
+ tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
4468
+ }
4469
+ if (html.indexOf('data-codelab-preview-shims') === -1 &&
4470
+ PreviewCsp && typeof PreviewCsp.buildPreviewShims === 'function') {
4471
+ tags.push(PreviewCsp.buildPreviewShims());
4472
+ }
4473
+ if (tags.length === 0) return html;
4474
+
4475
+ const injection = tags.join('');
4476
+ if (/<head\b[^>]*>/i.test(html)) {
4477
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
4478
+ }
4479
+ if (/<html\b[^>]*>/i.test(html)) {
4480
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
4481
+ }
4482
+ return `<head>${injection}</head>${html}`;
4483
+ }
4484
+
4485
+ /**
4486
+ * Preview documents are sandboxed (opaque origin), so `event.origin` is the
4487
+ * string `"null"` and cannot be used to authenticate the sender. Match the
4488
+ * message source against the preview frame instead.
4489
+ */
4490
+ _installPreviewViolationListener() {
4491
+ if (this._previewViolationHandler) return;
4492
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
4493
+
4494
+ this._previewViolationHandler = (event) => {
4495
+ const data = event && event.data;
4496
+ if (!data || typeof data.type !== 'string') return;
4497
+ const iframe = this.container ? this.container.querySelector('#cl-preview-iframe') : null;
4498
+ if (!iframe) return;
4499
+ // `contentWindow` is unavailable on the mock DOM used by unit tests.
4500
+ if (iframe.contentWindow && event.source !== iframe.contentWindow) return;
4501
+
4502
+ if (data.type === 'codelab:preview-violation') {
4503
+ this._reportPreviewViolation(data);
4504
+ } else if (data.type === 'codelab:preview-console') {
4505
+ const level = ['log', 'warn', 'error', 'info'].includes(data.level) ? data.level : 'log';
4506
+ const args = Array.isArray(data.args) ? data.args : [data.args];
4507
+ const text = args.map((a) => String(a ?? '')).join(' ');
4508
+ this.terminalLogs.push({
4509
+ type: level === 'error' ? 'stderr' : 'stdout',
4510
+ text: `[Preview ${level.toUpperCase()}] ${text}`
4511
+ });
4512
+ this._emitEvent('preview-console', { level, text, args });
4513
+ } else if (data.type === 'codelab:preview-error') {
4514
+ const msg = String(data.message || 'Uncaught runtime error');
4515
+ this.previewState.runtimeError = {
4516
+ message: msg,
4517
+ file: data.file ? String(data.file) : null,
4518
+ line: typeof data.line === 'number' ? data.line : null,
4519
+ col: typeof data.col === 'number' ? data.col : null,
4520
+ stack: data.stack ? String(data.stack) : null
4521
+ };
4522
+ this.terminalLogs.push({
4523
+ type: 'stderr',
4524
+ text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
4525
+ });
4526
+ this._emitEvent('preview-error', this.previewState.runtimeError);
4527
+ } else if (data.type === 'codelab:preview-error-clear') {
4528
+ this.previewState.runtimeError = null;
4529
+ }
4530
+ };
4531
+ window.addEventListener('message', this._previewViolationHandler);
4532
+ }
4533
+
4534
+ _reportPreviewViolation(violation) {
4535
+ const blockedURI = String((violation && violation.blockedURI) || 'unknown');
4536
+ const directive = String((violation && violation.directive) || '');
4537
+ const key = `${directive}|${blockedURI}`;
4538
+ const state = this.previewState;
4539
+ state.violations = state.violations || [];
4540
+ if (state.violations.length < 20 && !state.violations.some((v) => v.key === key)) {
4541
+ state.violations.push({ key, directive, blockedURI });
4542
+ this._showToast(`Blocked by Content-Security-Policy: ${this._shortPreviewUrl(blockedURI)}`, 'error');
4543
+ this._emitEvent('preview-violation', { directive, blockedURI, violations: state.violations.slice() });
4544
+ }
4545
+ this._updatePreviewCspStatus();
4546
+ }
4547
+
4548
+ _shortPreviewUrl(raw) {
4549
+ const value = String(raw || '');
4550
+ try {
4551
+ const parsed = new URL(value);
4552
+ const path = parsed.pathname.length > 32 ? `${parsed.pathname.slice(0, 32)}…` : parsed.pathname;
4553
+ return `${parsed.host}${path === '/' ? '' : path}`;
4554
+ } catch (_) {
4555
+ // Not a URL (e.g. "inline" or "eval"); show it verbatim, truncated.
4556
+ return value.length > 48 ? `${value.slice(0, 48)}…` : value;
4557
+ }
4558
+ }
4559
+
4560
+ /** Update (or create) the CSP status chip in the preview toolbar. */
4561
+ _updatePreviewCspStatus() {
4562
+ if (!this.container) return;
4563
+ const chip = this.container.querySelector('#cl-preview-csp-status');
4564
+ if (!chip) return;
4565
+ const violations = (this.previewState && this.previewState.violations) || [];
4566
+ if (!violations.length) {
4567
+ chip.hidden = true;
4568
+ chip.textContent = '';
4569
+ chip.removeAttribute('title');
4570
+ return;
4571
+ }
4572
+ const last = violations[violations.length - 1];
4573
+ chip.hidden = false;
4574
+ chip.textContent = `Blocked: ${this._shortPreviewUrl(last.blockedURI)}`;
4575
+ chip.title = violations
4576
+ .map((v) => `${v.directive} → ${v.blockedURI}`)
4577
+ .join('\n');
4578
+ }
4579
+
4092
4580
  _openWebPreview(port, path = '/') {
4093
4581
  const p = Number(port) || this._firstListeningPort() || 3000;
4582
+ this._warnPreviewIsolation();
4583
+ this._installPreviewViolationListener();
4094
4584
  this.previewState.port = p;
4095
4585
  this.previewState.path = path || '/';
4096
4586
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
4097
4587
  this.previewState.error = null;
4588
+ this.previewState.violations = [];
4098
4589
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
4099
4590
  this.previewHistory.push(this.previewState.url);
4100
4591
  this.previewHistoryIdx = this.previewHistory.length - 1;
@@ -4185,7 +4676,7 @@ declare module 'bun:sqlite' {
4185
4676
  try {
4186
4677
  const win = window.open(url, '_blank');
4187
4678
  if (win) {
4188
- try { win.opener = null; } catch (_) {}
4679
+ try { win.opener = null; } catch (err) { this.logger.debug('Could not clear win.opener.', err); }
4189
4680
  opened = true;
4190
4681
  }
4191
4682
  } catch (_) { opened = false; }
@@ -4207,7 +4698,9 @@ declare module 'bun:sqlite' {
4207
4698
  const u = new URL(url);
4208
4699
  port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
4209
4700
  path = u.pathname + (u.search || '') + (u.hash || '');
4210
- } catch (_) {}
4701
+ } catch (err) {
4702
+ this.logger.debug('Failed to parse preview URL; using fallback port/path.', err);
4703
+ }
4211
4704
  this.previewState.port = port;
4212
4705
  this.previewState.path = path;
4213
4706
  this.previewState.url = url;
@@ -4239,7 +4732,9 @@ declare module 'bun:sqlite' {
4239
4732
  const u = new URL(url);
4240
4733
  this.previewState.port = Number(u.port || 80);
4241
4734
  this.previewState.path = u.pathname + (u.search || '');
4242
- } catch (_) {}
4735
+ } catch (err) {
4736
+ this.logger.debug('Failed to parse preview history URL.', err);
4737
+ }
4243
4738
  const input = this.container.querySelector('#cl-preview-url-input');
4244
4739
  if (input) input.value = url;
4245
4740
  this._renderWebPreviewControls();
@@ -4269,19 +4764,22 @@ declare module 'bun:sqlite' {
4269
4764
 
4270
4765
  _popoutPreview() {
4271
4766
  const url = this._previewUrl();
4272
- let popout = '/__preview/';
4767
+ let popout = this._previewFrameUrl(this.previewState.port || 3000, '/');
4273
4768
  try {
4274
4769
  const u = new URL(url);
4275
- popout = `/__preview/${u.port}${u.pathname}${u.search || ''}`;
4276
- } catch (_) {}
4770
+ popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
4771
+ } catch (err) {
4772
+ this.logger.debug('Failed to parse popout preview URL.', err);
4773
+ }
4277
4774
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
4278
- try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
4775
+ try { window.open(popout, '_blank', 'noopener'); } catch (err) { this.logger.warn('window.open failed for preview popout.', err); }
4279
4776
  }
4280
4777
  return popout;
4281
4778
  }
4282
4779
 
4283
4780
  _renderWebPreview(bodyEl) {
4284
4781
  if (!bodyEl) return;
4782
+ this._warnPreviewIsolation();
4285
4783
  const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
4286
4784
  if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
4287
4785
  this._renderWebPreviewControls();
@@ -4301,6 +4799,19 @@ declare module 'bun:sqlite' {
4301
4799
  ? servers.map(s => `<option value="${s.port}" ${Number(s.port) === Number(this.previewState.port) ? 'selected' : ''}>Port ${s.port} · ${escapeHtml(s.name || 'server')}</option>`).join('')
4302
4800
  : `<option value="${this.previewState.port || 3000}">Port ${this.previewState.port || 3000}</option>`;
4303
4801
 
4802
+ const cspMode = (this.previewCsp && this.previewCsp.mode) || 'balanced';
4803
+ const cspHosts = this._previewNetworkHosts();
4804
+ const cspBadge = cspMode === 'strict'
4805
+ ? 'CSP: strict'
4806
+ : !cspHosts.length
4807
+ ? 'CSP: custom'
4808
+ : cspHosts.length === 1
4809
+ ? `CSP: ${cspHosts[0]}`
4810
+ : `CSP: ${cspHosts[0]} +${cspHosts.length - 1}`;
4811
+ const cspBadgeTitle = cspMode === 'strict'
4812
+ ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
4813
+ : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
4814
+
4304
4815
  bodyEl.innerHTML = `
4305
4816
  <div class="codelab-preview">
4306
4817
  <div class="codelab-preview-chrome">
@@ -4316,10 +4827,12 @@ declare module 'bun:sqlite' {
4316
4827
  <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>
4317
4828
  <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>
4318
4829
  </div>
4830
+ <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
4831
+ <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
4319
4832
  <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>
4320
4833
  </div>
4321
4834
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
4322
- <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
4835
+ <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>
4323
4836
  </div>
4324
4837
  ${servers.length
4325
4838
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -4332,6 +4845,7 @@ declare module 'bun:sqlite' {
4332
4845
  </div>`}
4333
4846
  </div>
4334
4847
  `;
4848
+ this._updatePreviewCspStatus();
4335
4849
  this._loadPreviewFrame();
4336
4850
  }
4337
4851
 
@@ -4356,10 +4870,12 @@ declare module 'bun:sqlite' {
4356
4870
  try {
4357
4871
  const u = new URL(fullUrl);
4358
4872
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
4359
- iframe.setAttribute('src', `/__preview/${u.port}${u.pathname}${u.search || ''}`);
4873
+ iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
4360
4874
  this.previewState.loading = false;
4361
4875
  return Promise.resolve();
4362
- } catch (_) {}
4876
+ } catch (err) {
4877
+ this.logger.warn('Failed to set Service Worker preview URL; falling back to srcdoc.', err);
4878
+ }
4363
4879
  }
4364
4880
 
4365
4881
  // Fallback (no Service Worker): dispatch via the virtual port table and
@@ -4368,8 +4884,8 @@ declare module 'bun:sqlite' {
4368
4884
  .then((res) => {
4369
4885
  let body = res.body || '';
4370
4886
  const contentType = res.headers['content-type'] || res.headers['Content-Type'] || '';
4371
- if (/text\/html/i.test(contentType) && /<head\b/i.test(body) && !/<base\b/i.test(body)) {
4372
- body = body.replace(/<head\b[^>]*>/i, (m) => `${m}<base href="/__preview/${port}/">`);
4887
+ if (/text\/html/i.test(contentType)) {
4888
+ body = this._injectPreviewCsp(body, port);
4373
4889
  }
4374
4890
  this.previewState.srcdoc = body;
4375
4891
  this.previewState.loading = false;
@@ -4381,7 +4897,7 @@ declare module 'bun:sqlite' {
4381
4897
  this.previewState.loading = false;
4382
4898
  this.previewState.error = String((err && err.message) || err);
4383
4899
  const msg = `<body style="font-family:system-ui;padding:24px;color:#888"><h2>Preview unavailable</h2><p>${escapeHtml(this.previewState.error)}</p></body>`;
4384
- iframe.setAttribute('srcdoc', msg);
4900
+ iframe.setAttribute('srcdoc', this._injectPreviewCsp(msg, port));
4385
4901
  });
4386
4902
  }
4387
4903
 
@@ -4425,7 +4941,7 @@ declare module 'bun:sqlite' {
4425
4941
  const full = dir === '/' ? '/' + entry : dir + '/' + entry;
4426
4942
  const rel = relPrefix ? relPrefix + '/' + entry : entry;
4427
4943
  let isDir = false;
4428
- try { isDir = vfs.statSync(full).isDirectory(); } catch (_) {}
4944
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
4429
4945
  if (isDir) {
4430
4946
  shellWorkspaceFolders.add(rel);
4431
4947
  walk(full, rel);
@@ -4433,7 +4949,9 @@ declare module 'bun:sqlite' {
4433
4949
  try {
4434
4950
  const content = String(vfs.readFileSync(full, 'utf8') ?? '');
4435
4951
  shellWorkspaceFiles.set(rel, content);
4436
- } catch (_) {}
4952
+ } catch (err) {
4953
+ this.logger.debug(`Could not read VFS file "${full}" during snapshot sync.`, err);
4954
+ }
4437
4955
  }
4438
4956
  }
4439
4957
  };
@@ -4735,8 +5253,29 @@ declare module 'bun:sqlite' {
4735
5253
  }
4736
5254
 
4737
5255
  _notifyCodeChange(filename, code) {
5256
+ if (this.shell && this.shell.vfs && filename && typeof this.shell.vfs.writeFileSync === 'function') {
5257
+ try {
5258
+ const clean = String(filename).replace(/^\/+/, '');
5259
+ const parts = clean.split('/');
5260
+ if (parts.length > 1 && typeof this.shell.vfs.mkdirSync === 'function') {
5261
+ this.shell.vfs.mkdirSync('/workspace/' + parts.slice(0, -1).join('/'), { recursive: true });
5262
+ }
5263
+ this.shell.vfs.writeFileSync('/workspace/' + clean, String(code ?? ''));
5264
+ } catch (err) {
5265
+ this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
5266
+ }
5267
+ }
5268
+ if (this.drawerTab === 'preview' && this.previewState && this.previewState.port) {
5269
+ if (this._previewReloadTimer) {
5270
+ clearTimeout(this._previewReloadTimer);
5271
+ }
5272
+ this._previewReloadTimer = setTimeout(() => {
5273
+ this._previewReloadTimer = null;
5274
+ this._previewReload();
5275
+ }, 300);
5276
+ }
4738
5277
  if (this.onCodeChange) {
4739
- try { this.onCodeChange(filename, code); } catch (_) {}
5278
+ try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
4740
5279
  }
4741
5280
  const detail = { labId: this.labId, filename, path: filename, code, content: code };
4742
5281
  this._emitEvent('codelab:change', detail);
@@ -4792,7 +5331,7 @@ declare module 'bun:sqlite' {
4792
5331
  if (fallbackWrap) fallbackWrap.style.display = 'none';
4793
5332
  if (mdPreview) mdPreview.style.display = 'none';
4794
5333
  if (this.editor) {
4795
- try { this.editor.setModel(null); } catch (_) {}
5334
+ try { this.editor.setModel(null); } catch (err) { this.logger.debug('editor.setModel(null) failed.', err); }
4796
5335
  }
4797
5336
  if (emptyEl) {
4798
5337
  emptyEl.style.display = 'flex';
@@ -5104,7 +5643,9 @@ declare module 'bun:sqlite' {
5104
5643
  textarea.select();
5105
5644
  document.execCommand('copy');
5106
5645
  document.body.removeChild(textarea);
5107
- } catch (_) {}
5646
+ } catch (err) {
5647
+ this.logger.warn('Clipboard fallback (execCommand) failed.', err);
5648
+ }
5108
5649
  };
5109
5650
 
5110
5651
  if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
@@ -5462,6 +6003,7 @@ declare module 'bun:sqlite' {
5462
6003
  { id: 'rename-active', label: 'File: Rename Active File...', shortcut: 'F2', action: () => { if (this.activeFile) this.startInlineRename('file', this.activeFile); } },
5463
6004
  { id: 'delete-active', label: 'File: Delete Active File', action: () => { if (this.activeFile) this.deleteFile(this.activeFile); } },
5464
6005
  { id: 'export-workspace', label: 'Workspace: Export Workspace as JSON', action: () => this.exportWorkspace({ download: true }) },
6006
+ { id: 'export-workspace-zip', label: 'Workspace: Export Project as ZIP Archive', action: () => this.exportProjectZip({ download: true }) },
5465
6007
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
5466
6008
  { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
5467
6009
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
@@ -5472,6 +6014,9 @@ declare module 'bun:sqlite' {
5472
6014
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
5473
6015
  } },
5474
6016
  { id: 'toggle-fullscreen', label: 'View: Toggle Fullscreen Workbench', action: () => this.toggleFullscreen() },
6017
+ { id: 'search-workspace', label: 'Search: Find & Replace Across Files...', shortcut: '⇧⌘F', action: () => this.showSearchModal() },
6018
+ { id: 'open-scm', label: 'Git: Source Control (Status, Stage & Commit)...', action: () => this.showScmModal() },
6019
+ { id: 'open-problems', label: 'View: Show Problems & Diagnostics...', action: () => this.showProblemsModal() },
5475
6020
  { id: 'open-packages', label: 'Packages: Manage NPM Dependencies & Runtime', action: () => this.showPackagesModal() },
5476
6021
  { id: 'git-clone', label: 'Git: Clone Public GitHub Repository...', action: () => this.showCloneRepoModal() }
5477
6022
  ];
@@ -5504,7 +6049,9 @@ declare module 'bun:sqlite' {
5504
6049
  input.focus();
5505
6050
  try {
5506
6051
  input.setSelectionRange(initialVal.length, initialVal.length);
5507
- } catch (_) {}
6052
+ } catch (err) {
6053
+ this.logger.debug('input.setSelectionRange failed in command palette.', err);
6054
+ }
5508
6055
 
5509
6056
  input.addEventListener('input', () => {
5510
6057
  this.paletteSelectedIndex = 0;
@@ -5777,7 +6324,7 @@ declare module 'bun:sqlite' {
5777
6324
  const onUp = ev => {
5778
6325
  vSplitter.classList.remove('is-dragging');
5779
6326
  shell.classList.remove('is-resizing');
5780
- try { vSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
6327
+ try { vSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
5781
6328
  vSplitter.removeEventListener('pointermove', onMove);
5782
6329
  vSplitter.removeEventListener('pointerup', onUp);
5783
6330
  };
@@ -5818,7 +6365,7 @@ declare module 'bun:sqlite' {
5818
6365
  const onUp = ev => {
5819
6366
  hSplitter.classList.remove('is-dragging');
5820
6367
  shell.classList.remove('is-resizing-row');
5821
- try { hSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
6368
+ try { hSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
5822
6369
  hSplitter.removeEventListener('pointermove', onMove);
5823
6370
  hSplitter.removeEventListener('pointerup', onUp);
5824
6371
  };
@@ -5845,7 +6392,7 @@ declare module 'bun:sqlite' {
5845
6392
  e.preventDefault();
5846
6393
  fSplitter.classList.add('is-dragging');
5847
6394
  shell.classList.add('is-resizing');
5848
- try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
6395
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
5849
6396
 
5850
6397
  const onMove = ev => {
5851
6398
  const ws = this.container.querySelector('.codelab-workspace');
@@ -5859,7 +6406,7 @@ declare module 'bun:sqlite' {
5859
6406
  const onUp = ev => {
5860
6407
  fSplitter.classList.remove('is-dragging');
5861
6408
  shell.classList.remove('is-resizing');
5862
- try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
6409
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
5863
6410
  fSplitter.removeEventListener('pointermove', onMove);
5864
6411
  fSplitter.removeEventListener('pointerup', onUp);
5865
6412
  this._saveState();
@@ -6202,7 +6749,9 @@ declare module 'bun:sqlite' {
6202
6749
  if (this.files['package.json']) {
6203
6750
  try {
6204
6751
  pkgJson = JSON.parse(this.files['package.json']);
6205
- } catch (_) {}
6752
+ } catch (err) {
6753
+ this.logger.warn('Malformed package.json when adding dependency; reinitializing.', err);
6754
+ }
6206
6755
  }
6207
6756
  if (!pkgJson.dependencies || typeof pkgJson.dependencies !== 'object') {
6208
6757
  pkgJson.dependencies = {};
@@ -6375,7 +6924,7 @@ declare module 'bun:sqlite' {
6375
6924
  }
6376
6925
 
6377
6926
  if (this.onRun) {
6378
- try { this.onRun(res); } catch (_) {}
6927
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
6379
6928
  }
6380
6929
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'run', entry, result: res });
6381
6930
  } catch (err) {
@@ -6450,10 +6999,10 @@ declare module 'bun:sqlite' {
6450
6999
  }
6451
7000
 
6452
7001
  if (this.onTestResult) {
6453
- try { this.onTestResult(res); } catch (_) {}
7002
+ try { this.onTestResult(res); } catch (err) { this.logger.error('onTestResult callback threw.', err); }
6454
7003
  }
6455
7004
  if (this.onRun) {
6456
- try { this.onRun(res); } catch (_) {}
7005
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
6457
7006
  }
6458
7007
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'test', entry, result: res });
6459
7008
 
@@ -6467,7 +7016,7 @@ declare module 'bun:sqlite' {
6467
7016
  this.completedSteps.add(step.id);
6468
7017
  newlyCompleted = true;
6469
7018
  if (this.onStepComplete) {
6470
- try { this.onStepComplete(step, sIdx); } catch (_) {}
7019
+ try { this.onStepComplete(step, sIdx); } catch (err) { this.logger.error('onStepComplete callback threw.', err); }
6471
7020
  }
6472
7021
  const stepDetail = {
6473
7022
  labId: this.labId,
@@ -6486,7 +7035,7 @@ declare module 'bun:sqlite' {
6486
7035
  this._saveState();
6487
7036
  if (this.steps.length > 0 && this.completedSteps.size >= this.steps.length) {
6488
7037
  if (this.onLabComplete) {
6489
- try { this.onLabComplete(this.labId); } catch (_) {}
7038
+ try { this.onLabComplete(this.labId); } catch (err) { this.logger.error('onLabComplete callback threw.', err); }
6490
7039
  }
6491
7040
  this._emitEvent('codelab:lab-complete', {
6492
7041
  labId: this.labId,
@@ -6791,7 +7340,12 @@ declare module 'bun:sqlite' {
6791
7340
  a.click();
6792
7341
  setTimeout(() => URL.revokeObjectURL(url), 500);
6793
7342
  }
6794
- } catch (_) {}
7343
+ } catch (err) {
7344
+ this.logger.error(
7345
+ `Failed to start download for "${filename}".`,
7346
+ err && err.message ? err.message : err
7347
+ );
7348
+ }
6795
7349
  return content;
6796
7350
  }
6797
7351
 
@@ -6819,7 +7373,12 @@ declare module 'bun:sqlite' {
6819
7373
  a.click();
6820
7374
  setTimeout(() => URL.revokeObjectURL(url), 500);
6821
7375
  }
6822
- } catch (_) {}
7376
+ } catch (err) {
7377
+ this.logger.error(
7378
+ 'Failed to download workspace export.',
7379
+ err && err.message ? err.message : err
7380
+ );
7381
+ }
6823
7382
  }
6824
7383
  return snapshot;
6825
7384
  }
@@ -6853,6 +7412,219 @@ declare module 'bun:sqlite' {
6853
7412
  return true;
6854
7413
  }
6855
7414
 
7415
+ exportProjectZip(options = {}) {
7416
+ const zipMod = root.CodeLabZip;
7417
+ if (!zipMod || typeof zipMod.createZip !== 'function') {
7418
+ throw new Error('CodeLabZip engine is not loaded');
7419
+ }
7420
+ const bytes = zipMod.createZip(this.files || {});
7421
+ if (options && options.download) {
7422
+ try {
7423
+ if (typeof Blob !== 'undefined' && typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function' && typeof document !== 'undefined') {
7424
+ const blob = new Blob([bytes], { type: 'application/zip' });
7425
+ const url = URL.createObjectURL(blob);
7426
+ const a = document.createElement('a');
7427
+ a.href = url;
7428
+ a.download = `${this.labId || 'workspace'}.zip`;
7429
+ a.click();
7430
+ setTimeout(() => URL.revokeObjectURL(url), 500);
7431
+ }
7432
+ } catch (err) {
7433
+ this.logger.error('Failed to download project ZIP export.', err);
7434
+ }
7435
+ }
7436
+ return bytes;
7437
+ }
7438
+
7439
+ importProjectZip(zipBytes) {
7440
+ const zipMod = root.CodeLabZip;
7441
+ if (!zipMod || typeof zipMod.extractZip !== 'function') {
7442
+ throw new Error('CodeLabZip engine is not loaded');
7443
+ }
7444
+ const extracted = zipMod.extractZip(zipBytes);
7445
+ if (!extracted || typeof extracted !== 'object') return false;
7446
+ this.setFiles(extracted);
7447
+ this._syncFilesToShellVfs();
7448
+ return true;
7449
+ }
7450
+
7451
+ searchWorkspace(options) {
7452
+ const searchMod = root.CodeLabSearch;
7453
+ if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
7454
+ throw new Error('CodeLabSearch engine is not loaded');
7455
+ }
7456
+ return searchMod.searchInFiles(this.files || {}, options);
7457
+ }
7458
+
7459
+ replaceInWorkspace(options) {
7460
+ const searchMod = root.CodeLabSearch;
7461
+ if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
7462
+ throw new Error('CodeLabSearch engine is not loaded');
7463
+ }
7464
+ const res = searchMod.replaceInFiles(this.files || {}, options);
7465
+ if (res && res.files && res.filesModified > 0) {
7466
+ this.setFiles(res.files);
7467
+ this._syncFilesToShellVfs();
7468
+ }
7469
+ return res;
7470
+ }
7471
+
7472
+ getGitStatus() {
7473
+ const scmMod = root.CodeLabScm;
7474
+ if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
7475
+ return [];
7476
+ }
7477
+ const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
7478
+ return scmMod.computeGitStatus(gs, this.files || {});
7479
+ }
7480
+
7481
+ getDiagnostics() {
7482
+ const diagMod = root.CodeLabDiagnostics;
7483
+ if (!this._diagnosticsStore && diagMod && typeof diagMod.createDiagnosticsStore === 'function') {
7484
+ this._diagnosticsStore = diagMod.createDiagnosticsStore();
7485
+ }
7486
+ if (this._diagnosticsStore && typeof this._diagnosticsStore.getAll === 'function') {
7487
+ return this._diagnosticsStore.getAll();
7488
+ }
7489
+ return [];
7490
+ }
7491
+
7492
+ showSearchModal(initialQuery = '') {
7493
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
7494
+ if (!slot) return;
7495
+ const q = String(initialQuery || '');
7496
+ const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
7497
+ const rowsHtml = (results.matches || []).map((m) => `
7498
+ <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;">
7499
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
7500
+ </div>
7501
+ `).join('');
7502
+ slot.innerHTML = `
7503
+ <div class="codelab-modal-backdrop">
7504
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
7505
+ <div class="codelab-modal__header">
7506
+ <span>Search &amp; Replace Across Workspace</span>
7507
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
7508
+ </div>
7509
+ <div class="codelab-modal__body">
7510
+ <div style="display:flex;gap:8px;margin-bottom:8px;">
7511
+ <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
7512
+ <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
7513
+ </div>
7514
+ <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>
7515
+ </div>
7516
+ </div>
7517
+ </div>
7518
+ `;
7519
+ }
7520
+
7521
+ showScmModal() {
7522
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
7523
+ if (!slot) return;
7524
+ const statusList = this.getGitStatus();
7525
+ const rowsHtml = statusList.map((entry) => `
7526
+ <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;">
7527
+ <span>${escapeHtml(entry.path)}</span>
7528
+ <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
7529
+ </div>
7530
+ `).join('');
7531
+ slot.innerHTML = `
7532
+ <div class="codelab-modal-backdrop">
7533
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
7534
+ <div class="codelab-modal__header">
7535
+ <span>Source Control (Git Status)</span>
7536
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
7537
+ </div>
7538
+ <div class="codelab-modal__body">
7539
+ <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
7540
+ </div>
7541
+ </div>
7542
+ </div>
7543
+ `;
7544
+ }
7545
+
7546
+ showProblemsModal() {
7547
+ const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
7548
+ if (!slot) return;
7549
+ const items = this.getDiagnostics();
7550
+ const rowsHtml = items.map((d) => `
7551
+ <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;">
7552
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
7553
+ </div>
7554
+ `).join('');
7555
+ slot.innerHTML = `
7556
+ <div class="codelab-modal-backdrop">
7557
+ <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
7558
+ <div class="codelab-modal__header">
7559
+ <span>Problems (${items.length})</span>
7560
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
7561
+ </div>
7562
+ <div class="codelab-modal__body">
7563
+ <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>
7564
+ </div>
7565
+ </div>
7566
+ </div>
7567
+ `;
7568
+ }
7569
+
7570
+ _ensureTerminalSessions() {
7571
+ if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
7572
+ this._terminalSessions = [
7573
+ { id: 'session-1', name: 'bash-1', logs: this.terminalLogs || [] }
7574
+ ];
7575
+ this._activeTerminalSessionId = 'session-1';
7576
+ }
7577
+ return this._terminalSessions;
7578
+ }
7579
+
7580
+ listTerminalSessions() {
7581
+ const sessions = this._ensureTerminalSessions();
7582
+ return sessions.map((s) => ({
7583
+ id: s.id,
7584
+ name: s.name,
7585
+ active: s.id === this._activeTerminalSessionId,
7586
+ logCount: Array.isArray(s.logs) ? s.logs.length : 0
7587
+ }));
7588
+ }
7589
+
7590
+ createTerminalSession(name) {
7591
+ const sessions = this._ensureTerminalSessions();
7592
+ const nextNum = sessions.length + 1;
7593
+ const id = `session-${Date.now()}-${nextNum}`;
7594
+ const label = name ? String(name).trim() : `bash-${nextNum}`;
7595
+ const newLogs = [];
7596
+ sessions.push({ id, name: label, logs: newLogs });
7597
+ this._activeTerminalSessionId = id;
7598
+ this.terminalLogs = newLogs;
7599
+ this._renderDrawerBody();
7600
+ return id;
7601
+ }
7602
+
7603
+ switchTerminalSession(id) {
7604
+ const sessions = this._ensureTerminalSessions();
7605
+ const target = sessions.find((s) => s.id === id || s.name === id);
7606
+ if (!target) return false;
7607
+ this._activeTerminalSessionId = target.id;
7608
+ this.terminalLogs = target.logs;
7609
+ this._renderDrawerBody();
7610
+ return true;
7611
+ }
7612
+
7613
+ closeTerminalSession(id) {
7614
+ const sessions = this._ensureTerminalSessions();
7615
+ if (sessions.length <= 1) return false;
7616
+ const idx = sessions.findIndex((s) => s.id === id || s.name === id);
7617
+ if (idx === -1) return false;
7618
+ const removed = sessions.splice(idx, 1)[0];
7619
+ if (this._activeTerminalSessionId === removed.id) {
7620
+ const next = sessions[Math.max(0, idx - 1)] || sessions[0];
7621
+ this._activeTerminalSessionId = next.id;
7622
+ this.terminalLogs = next.logs;
7623
+ }
7624
+ this._renderDrawerBody();
7625
+ return true;
7626
+ }
7627
+
6856
7628
  getFiles() {
6857
7629
  return { ...this.files };
6858
7630
  }
@@ -6860,7 +7632,7 @@ declare module 'bun:sqlite' {
6860
7632
  setFiles(filesMap) {
6861
7633
  if (!filesMap || typeof filesMap !== 'object') return;
6862
7634
  for (const model of this.models.values()) {
6863
- try { model.dispose(); } catch (_) {}
7635
+ try { model.dispose(); } catch (err) { this.logger.debug('model.dispose failed during setFiles.', err); }
6864
7636
  }
6865
7637
  this.models.clear();
6866
7638
  this.files = {};
@@ -6950,7 +7722,9 @@ declare module 'bun:sqlite' {
6950
7722
  if (this.shell && this.shell.vfs && typeof this.shell.vfs.writeFile === 'function') {
6951
7723
  try {
6952
7724
  this.shell.vfs.writeFile('/workspace/' + clean, updated);
6953
- } catch (_) {}
7725
+ } catch (err) {
7726
+ this.logger.warn(`Failed to sync markdown task toggle for "${clean}" to VFS.`, err);
7727
+ }
6954
7728
  }
6955
7729
  this._notifyCodeChange(clean, updated);
6956
7730
  }
@@ -7170,9 +7944,22 @@ declare module 'bun:sqlite' {
7170
7944
 
7171
7945
  destroy() {
7172
7946
  this.stopExecution();
7947
+ if (this._previewReloadTimer) {
7948
+ clearTimeout(this._previewReloadTimer);
7949
+ this._previewReloadTimer = null;
7950
+ }
7173
7951
  if (this._escHandler && typeof document !== 'undefined') {
7174
7952
  document.removeEventListener('keydown', this._escHandler);
7175
7953
  }
7954
+ if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
7955
+ window.removeEventListener('message', this._previewViolationHandler);
7956
+ }
7957
+ this._previewViolationHandler = null;
7958
+ if (this._swMessageHandler && typeof navigator !== 'undefined' && navigator.serviceWorker &&
7959
+ typeof navigator.serviceWorker.removeEventListener === 'function') {
7960
+ navigator.serviceWorker.removeEventListener('message', this._swMessageHandler);
7961
+ }
7962
+ this._swMessageHandler = null;
7176
7963
  if (this._themeObserver) {
7177
7964
  this._themeObserver.disconnect();
7178
7965
  }
@@ -7233,7 +8020,9 @@ declare module 'bun:sqlite' {
7233
8020
  if (jsonScript && jsonScript.textContent) {
7234
8021
  try {
7235
8022
  inlineConfig = JSON.parse(jsonScript.textContent);
7236
- } catch (_) {}
8023
+ } catch (err) {
8024
+ DEFAULT_LOGGER.warn('Failed to parse <script type="application/json"> inside <code-lab>.', err);
8025
+ }
7237
8026
  }
7238
8027
 
7239
8028
  // Parse optional files JSON attribute
@@ -7242,7 +8031,9 @@ declare module 'bun:sqlite' {
7242
8031
  if (filesAttr) {
7243
8032
  try {
7244
8033
  attrFiles = JSON.parse(filesAttr);
7245
- } catch (_) {}
8034
+ } catch (err) {
8035
+ DEFAULT_LOGGER.warn('Failed to parse files="" attribute on <code-lab>.', err);
8036
+ }
7246
8037
  }
7247
8038
 
7248
8039
  const labId = this.getAttribute('lab-id') || this.getAttribute('build-id') || this.dataset.labId || this.dataset.buildId || inlineConfig.id || inlineConfig.labId || 'custom-lab';
@@ -7285,6 +8076,19 @@ declare module 'bun:sqlite' {
7285
8076
  reset() { if (this._instance) this._instance.reset(); }
7286
8077
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
7287
8078
  importWorkspace(snap) { return this._instance ? this._instance.importWorkspace(snap) : false; }
8079
+ exportProjectZip(opts) { return this._instance ? this._instance.exportProjectZip(opts) : null; }
8080
+ importProjectZip(bytes) { return this._instance ? this._instance.importProjectZip(bytes) : false; }
8081
+ searchWorkspace(opts) { return this._instance ? this._instance.searchWorkspace(opts) : null; }
8082
+ replaceInWorkspace(opts) { return this._instance ? this._instance.replaceInWorkspace(opts) : null; }
8083
+ getGitStatus() { return this._instance ? this._instance.getGitStatus() : []; }
8084
+ getDiagnostics() { return this._instance ? this._instance.getDiagnostics() : []; }
8085
+ showSearchModal(q) { if (this._instance) this._instance.showSearchModal(q); }
8086
+ showScmModal() { if (this._instance) this._instance.showScmModal(); }
8087
+ showProblemsModal() { if (this._instance) this._instance.showProblemsModal(); }
8088
+ listTerminalSessions() { return this._instance ? this._instance.listTerminalSessions() : []; }
8089
+ createTerminalSession(name) { return this._instance ? this._instance.createTerminalSession(name) : null; }
8090
+ switchTerminalSession(id) { return this._instance ? this._instance.switchTerminalSession(id) : false; }
8091
+ closeTerminalSession(id) { return this._instance ? this._instance.closeTerminalSession(id) : false; }
7288
8092
  on(ev, fn) { return this._instance ? this._instance.on(ev, fn) : () => {}; }
7289
8093
  off(ev, fn) { if (this._instance) this._instance.off(ev, fn); }
7290
8094
  use(plugin, opts) { if (this._instance) this._instance.use(plugin, opts); return this; }
@@ -7315,13 +8119,46 @@ declare module 'bun:sqlite' {
7315
8119
  }
7316
8120
 
7317
8121
  const CodeLabSDK = {
7318
- version: '2.0.0',
8122
+ version: CODELAB_VERSION,
7319
8123
  Workbench: CodeLabWorkbench,
7320
8124
  CodeLabWorkbench,
7321
8125
  CodeLabElement: CodeLabElementClass,
8126
+ CodeLabError,
8127
+ isCodeLabError,
8128
+ createLogger,
8129
+ Logger: _sharedLoggerMod || { LOG_PREFIX, CodeLabError, isCodeLabError, createLogger, DEFAULT_LOGGER },
8130
+ html,
8131
+ raw,
8132
+ isSafeHtml,
8133
+ escapeHtml,
8134
+ Html: _sharedHtmlMod || { html, raw, isSafeHtml, escapeHtml },
7322
8135
  Runtime: root.CodeLabRuntime,
7323
8136
  Shell: root.CodeLabShell,
7324
8137
  Terminal: root.CodeLabTerminal,
8138
+ zip: root.CodeLabZip || null,
8139
+ createZip: root.CodeLabZip ? root.CodeLabZip.createZip : null,
8140
+ extractZip: root.CodeLabZip ? root.CodeLabZip.extractZip : null,
8141
+ computeCrc32: root.CodeLabZip ? root.CodeLabZip.computeCrc32 : null,
8142
+ sanitizeZipPath: root.CodeLabZip ? root.CodeLabZip.sanitizeZipPath : null,
8143
+ storage: root.CodeLabStorage || null,
8144
+ WorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.WorkspaceStorage : null,
8145
+ createWorkspaceStorage: root.CodeLabStorage ? root.CodeLabStorage.createWorkspaceStorage : null,
8146
+ search: root.CodeLabSearch || null,
8147
+ searchInFiles: root.CodeLabSearch ? root.CodeLabSearch.searchInFiles : null,
8148
+ replaceInFiles: root.CodeLabSearch ? root.CodeLabSearch.replaceInFiles : null,
8149
+ matchesGlob: root.CodeLabSearch ? root.CodeLabSearch.matchesGlob : null,
8150
+ escapeRegex: root.CodeLabSearch ? root.CodeLabSearch.escapeRegex : null,
8151
+ normalizeSearchPath: root.CodeLabSearch ? root.CodeLabSearch.normalizeSearchPath : null,
8152
+ diagnostics: root.CodeLabDiagnostics || null,
8153
+ DiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.DiagnosticsStore : null,
8154
+ createDiagnosticsStore: root.CodeLabDiagnostics ? root.CodeLabDiagnostics.createDiagnosticsStore : null,
8155
+ scm: root.CodeLabScm || null,
8156
+ createGitState: root.CodeLabScm ? root.CodeLabScm.createGitState : null,
8157
+ computeGitStatus: root.CodeLabScm ? root.CodeLabScm.computeGitStatus : null,
8158
+ stageFile: root.CodeLabScm ? root.CodeLabScm.stageFile : null,
8159
+ unstageFile: root.CodeLabScm ? root.CodeLabScm.unstageFile : null,
8160
+ commitChanges: root.CodeLabScm ? root.CodeLabScm.commitChanges : null,
8161
+ computeShortCommitHash: root.CodeLabScm ? root.CodeLabScm.computeShortCommitHash : null,
7325
8162
  renderMarkdown: renderSimpleMarkdown,
7326
8163
  renderSimpleMarkdown: renderSimpleMarkdown,
7327
8164
  extensions: {