@innovatorved/code-lab 0.1.7 → 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.
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 || {};
@@ -44,7 +57,7 @@
44
57
 
45
58
  // The bundler rewrites this literal from package.json at build time. Keeping
46
59
  // the fallback in sync lets tests require src/workbench.js directly.
47
- const CODELAB_VERSION = '0.1.7';
60
+ const CODELAB_VERSION = '0.1.8';
48
61
 
49
62
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
50
63
  const NODE_AMBIENT_DTS = `
@@ -372,7 +385,14 @@ declare module 'bun:sqlite' {
372
385
  }
373
386
  `;
374
387
 
388
+ const _sharedHtmlMod = (typeof CodeLabHtml !== 'undefined' && CodeLabHtml) ||
389
+ (root && root.CodeLabHtml) ||
390
+ null;
391
+
375
392
  function escapeHtml(str) {
393
+ if (_sharedHtmlMod && typeof _sharedHtmlMod.escapeHtml === 'function') {
394
+ return _sharedHtmlMod.escapeHtml(str);
395
+ }
376
396
  if (str == null) return '';
377
397
  return String(str)
378
398
  .replace(/&/g, '&')
@@ -382,6 +402,18 @@ declare module 'bun:sqlite' {
382
402
  .replace(/'/g, ''');
383
403
  }
384
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
+
385
417
  // Schemes that may appear in a rendered href. Everything else
386
418
  // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
387
419
  const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
@@ -600,11 +632,11 @@ declare module 'bun:sqlite' {
600
632
  if (!str) return '';
601
633
  let text = String(str);
602
634
 
603
- // Markdown Links: [label](url "title") or [label](url)
604
- text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
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) => {
605
637
  const cleanUrl = sanitizeUrl(url);
606
- const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
607
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
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>`);
608
640
  });
609
641
 
610
642
  // Strikethrough: ~~del~~
@@ -1131,23 +1163,24 @@ declare module 'bun:sqlite' {
1131
1163
  let _workbenchInstanceCounter = 0;
1132
1164
  const _fallbackStorage = new Map();
1133
1165
 
1134
- // CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
1135
- // in src/preview-sw.js — keep both copies in sync.
1136
- const PREVIEW_CSP = [
1137
- "default-src 'self' data: blob:",
1138
- "base-uri 'self'",
1139
- "object-src 'none'",
1140
- "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
1141
- "style-src 'self' 'unsafe-inline'",
1142
- "img-src 'self' data: blob:",
1143
- "font-src 'self' data:",
1144
- "connect-src 'self' data: blob:",
1145
- "media-src 'self' data: blob:",
1146
- "worker-src 'self' blob:",
1147
- "frame-src 'self' data: blob:",
1148
- "form-action 'self'",
1149
- "frame-ancestors 'self'"
1150
- ].join('; ');
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;
1151
1184
 
1152
1185
  function normalizePreviewOrigin(raw) {
1153
1186
  if (raw === null || raw === undefined || raw === '') return null;
@@ -1160,12 +1193,26 @@ declare module 'bun:sqlite' {
1160
1193
  }
1161
1194
  }
1162
1195
 
1163
- const LOG_PREFIX = '[code-lab]';
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'));
1164
1208
 
1165
1209
  // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
1166
1210
  // into their own telemetry; `options.debug` enables verbose output. Errors
1167
1211
  // are never silently discarded.
1168
1212
  function createLogger(options = {}) {
1213
+ if (_sharedLoggerMod && typeof _sharedLoggerMod.createLogger === 'function') {
1214
+ return _sharedLoggerMod.createLogger({ module: 'workbench', ...options });
1215
+ }
1169
1216
  const sink = options.logger;
1170
1217
  const debugEnabled = options.debug === true;
1171
1218
 
@@ -1175,8 +1222,9 @@ declare module 'bun:sqlite' {
1175
1222
  try {
1176
1223
  sink[level](...args);
1177
1224
  return;
1178
- } catch (_) {
1179
- // A broken host logger must not break the IDE; fall through.
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);
1180
1228
  }
1181
1229
  }
1182
1230
  const fn = typeof console !== 'undefined' ? console[level] : null;
@@ -1208,7 +1256,7 @@ declare module 'bun:sqlite' {
1208
1256
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
1209
1257
  }
1210
1258
 
1211
- function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
1259
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER, onError = null) {
1212
1260
  const str = String(value);
1213
1261
  try {
1214
1262
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
@@ -1216,6 +1264,9 @@ declare module 'bun:sqlite' {
1216
1264
  return true;
1217
1265
  }
1218
1266
  } catch (err) {
1267
+ if (typeof onError === 'function') {
1268
+ onError(err);
1269
+ }
1219
1270
  if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
1220
1271
  if (!safeStorageSet._warnedKeys.has(key)) {
1221
1272
  safeStorageSet._warnedKeys.add(key);
@@ -1239,6 +1290,8 @@ declare module 'bun:sqlite' {
1239
1290
  this.options = options || {};
1240
1291
  this.logger = createLogger({ logger: options.logger, debug: options.debug });
1241
1292
  this._persistenceFailureReported = false;
1293
+ this.saveStatusState = 'saved';
1294
+ this.saveStatusError = null;
1242
1295
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
1243
1296
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
1244
1297
  this.title = options.title || this.labId;
@@ -1246,6 +1299,7 @@ declare module 'bun:sqlite' {
1246
1299
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
1247
1300
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
1248
1301
  this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
1302
+ this.previewCsp = normalizePreviewCspOption(options.previewCsp);
1249
1303
  this._previewIsolationWarned = false;
1250
1304
  if (options.previewOrigin && !this.previewOrigin) {
1251
1305
  this.logger.warn(
@@ -1324,12 +1378,15 @@ declare module 'bun:sqlite' {
1324
1378
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
1325
1379
  loading: false,
1326
1380
  error: null,
1327
- srcdoc: ''
1381
+ srcdoc: '',
1382
+ violations: []
1328
1383
  };
1329
1384
  this.previewHistory = [];
1330
1385
  this.previewHistoryIdx = -1;
1331
1386
  this._previewSwReady = false;
1332
1387
  this._previewSwRegistration = null;
1388
+ this._previewViolationHandler = null;
1389
+ this._swMessageHandler = null;
1333
1390
  this._portToasts = new Map();
1334
1391
  this.isFullscreen = false;
1335
1392
  this.isRunning = false;
@@ -1429,7 +1486,9 @@ declare module 'bun:sqlite' {
1429
1486
  onCommand: (cmd) => this._handleReplCommand(cmd),
1430
1487
  onInterrupt: () => this._handleInterrupt()
1431
1488
  });
1432
- } catch (_) {}
1489
+ } catch (err) {
1490
+ this.logger.debug('PTY engine initialization skipped.', err);
1491
+ }
1433
1492
  }
1434
1493
 
1435
1494
  this.shell = null;
@@ -1455,7 +1514,7 @@ declare module 'bun:sqlite' {
1455
1514
  intoRoot: options.cloneIntoRoot !== false,
1456
1515
  branch: options.branch || undefined,
1457
1516
  fetchImpl: options.fetchImpl || undefined
1458
- }).catch(() => {});
1517
+ }).catch((err) => this.logger.warn('Initial cloneRepo failed.', err));
1459
1518
  }
1460
1519
  }
1461
1520
 
@@ -1480,7 +1539,9 @@ declare module 'bun:sqlite' {
1480
1539
  }
1481
1540
  });
1482
1541
  this._syncFilesToShellVfs();
1483
- } catch (_) {}
1542
+ } catch (err) {
1543
+ this.logger.debug('POSIX shell initialization skipped.', err);
1544
+ }
1484
1545
  }
1485
1546
  }
1486
1547
 
@@ -1506,7 +1567,9 @@ declare module 'bun:sqlite' {
1506
1567
  const u = new URL(fullUrl);
1507
1568
  parsedPort = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
1508
1569
  reqPath = u.pathname + (u.search || '');
1509
- } catch (_) {}
1570
+ } catch (err) {
1571
+ this.logger.debug('Could not parse portTable dispatch URL.', err);
1572
+ }
1510
1573
  const method = String((init && init.method) || 'GET').toUpperCase();
1511
1574
  try {
1512
1575
  const res = await origDispatch(url, init);
@@ -1518,7 +1581,9 @@ declare module 'bun:sqlite' {
1518
1581
  } else if (res && res.body !== undefined) {
1519
1582
  bodyText = String(res.body);
1520
1583
  }
1521
- } catch (_) {}
1584
+ } catch (err) {
1585
+ this.logger.debug('Could not read response body for HTTP trace.', err);
1586
+ }
1522
1587
  const responseHeaders = {};
1523
1588
  if (res && res.headers) {
1524
1589
  if (typeof res.headers.forEach === 'function') {
@@ -1530,7 +1595,9 @@ declare module 'bun:sqlite' {
1530
1595
  let formattedBody = bodyText;
1531
1596
  try {
1532
1597
  formattedBody = JSON.stringify(JSON.parse(bodyText), null, 2);
1533
- } catch (_) {}
1598
+ } catch (err) {
1599
+ void err;
1600
+ }
1534
1601
  if (!Array.isArray(this.lastHttpTrace)) this.lastHttpTrace = [];
1535
1602
  this.lastHttpTrace.push({
1536
1603
  id: 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
@@ -1579,7 +1646,9 @@ declare module 'bun:sqlite' {
1579
1646
  vfs.writeFileSync(absPath, String(content ?? ''));
1580
1647
  }
1581
1648
  }
1582
- } catch (_) {}
1649
+ } catch (err) {
1650
+ this.logger.debug('Could not sync files to shell VFS.', err);
1651
+ }
1583
1652
  }
1584
1653
 
1585
1654
  _emitEvent(name, detail) {
@@ -1601,7 +1670,9 @@ declare module 'bun:sqlite' {
1601
1670
  if (shortName !== fullName) {
1602
1671
  this.container.dispatchEvent(new CustomEvent(shortName, { detail, bubbles: true, composed: true }));
1603
1672
  }
1604
- } catch (_) {}
1673
+ } catch (err) {
1674
+ this.logger.debug(`CustomEvent dispatch for "${name}" failed.`, err);
1675
+ }
1605
1676
  }
1606
1677
 
1607
1678
  _resolvedTheme() {
@@ -1635,13 +1706,26 @@ declare module 'bun:sqlite' {
1635
1706
  }
1636
1707
  }
1637
1708
 
1638
- _reportPersistenceFailure() {
1639
- if (this._persistenceFailureReported) return;
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;
1640
1722
  this._persistenceFailureReported = true;
1641
1723
  this.logger.warn(
1642
1724
  'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
1643
1725
  );
1644
- this._emitEvent('persistence-error', { labId: this.labId });
1726
+ this._emitEvent('persistence-error', { labId: this.labId, error });
1727
+ this._emitEvent('error', error);
1728
+ return error;
1645
1729
  }
1646
1730
 
1647
1731
  _saveState() {
@@ -1665,22 +1749,35 @@ declare module 'bun:sqlite' {
1665
1749
  };
1666
1750
  this.savedState = state;
1667
1751
  if (this.options && this.options.persistState === false) {
1752
+ this.saveStatusState = 'saved';
1753
+ this.saveStatusError = null;
1754
+ this._updateStatusBar();
1668
1755
  return;
1669
1756
  }
1757
+ this._emitEvent('save-state', { status: 'saving', state: 'saving', labId: this.labId });
1670
1758
  const serialized = JSON.stringify(state);
1759
+ safeStorageSet._lastError = null;
1760
+ const recordErr = (err) => { safeStorageSet._lastError = err; };
1671
1761
  const persisted = [
1672
- safeStorageSet(this._storageKey(), serialized, this.logger),
1762
+ safeStorageSet(this._storageKey(), serialized, this.logger, recordErr),
1673
1763
  // Sync with host app sidebar & build overview progress trackers
1674
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
1675
- safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
1764
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
1765
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
1676
1766
  ];
1677
- if (persisted.includes(false)) this._reportPersistenceFailure();
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
+ }
1678
1775
  } catch (err) {
1679
1776
  this.logger.error(
1680
1777
  'Failed to save workbench state.',
1681
1778
  err && err.message ? err.message : err
1682
1779
  );
1683
- this._reportPersistenceFailure();
1780
+ this._reportPersistenceFailure(err);
1684
1781
  }
1685
1782
  }
1686
1783
 
@@ -1703,7 +1800,9 @@ declare module 'bun:sqlite' {
1703
1800
  for (const [dep, ver] of Object.entries(pkgJsonDeps)) {
1704
1801
  npmSet.add(ver && ver !== '*' && ver !== 'latest' ? `${dep}@${String(ver).replace(/^[\^~]/, '')}` : dep);
1705
1802
  }
1706
- } catch (_) {}
1803
+ } catch (err) {
1804
+ this.logger.debug('Malformed package.json while detecting dependencies.', err);
1805
+ }
1707
1806
  }
1708
1807
 
1709
1808
  const reqRe = /\brequire\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -1750,6 +1849,7 @@ declare module 'bun:sqlite' {
1750
1849
  const dotEl = this.container.querySelector('#cl-status-dot');
1751
1850
  const textEl = this.container.querySelector('#cl-status-text');
1752
1851
  const fileEl = this.container.querySelector('#cl-status-file');
1852
+ const saveEl = this.container.querySelector('#cl-status-save');
1753
1853
  const durEl = this.container.querySelector('#cl-status-duration');
1754
1854
  const curEl = this.container.querySelector('#cl-status-cursor');
1755
1855
  const langEl = this.container.querySelector('#cl-status-lang');
@@ -1761,6 +1861,24 @@ declare module 'bun:sqlite' {
1761
1861
  }
1762
1862
  if (textEl) textEl.textContent = this.runtimeStatusText;
1763
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
+ }
1764
1882
  if (durEl) {
1765
1883
  if (typeof this.lastRunDurationMs === 'number' && !Number.isNaN(this.lastRunDurationMs)) {
1766
1884
  durEl.style.display = 'inline-flex';
@@ -2068,6 +2186,7 @@ declare module 'bun:sqlite' {
2068
2186
  </span>
2069
2187
  <span class="codelab-statusbar__sep">·</span>
2070
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>
2071
2190
  </div>
2072
2191
  <div class="codelab-statusbar__right">
2073
2192
  <span class="codelab-statusbar__item" id="cl-status-duration" style="display:none"></span>
@@ -3322,7 +3441,9 @@ declare module 'bun:sqlite' {
3322
3441
  if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
3323
3442
  try {
3324
3443
  this.ptyEngine.writeStreamChunk(rawText, type);
3325
- } catch (_) {}
3444
+ } catch (err) {
3445
+ this.logger.debug('ptyEngine.writeStreamChunk failed.', err);
3446
+ }
3326
3447
  }
3327
3448
 
3328
3449
  this._activeStreamType = type;
@@ -3454,14 +3575,18 @@ declare module 'bun:sqlite' {
3454
3575
  if (this._activeCommandAbortController) {
3455
3576
  try {
3456
3577
  this._activeCommandAbortController.abort('SIGINT');
3457
- } catch (_) {}
3578
+ } catch (err) {
3579
+ this.logger.debug('AbortController.abort failed.', err);
3580
+ }
3458
3581
  this._activeCommandAbortController = null;
3459
3582
  }
3460
3583
 
3461
3584
  if (typeof root.CodeLabRuntime?.cancelWorkerExecution === 'function') {
3462
3585
  try {
3463
3586
  root.CodeLabRuntime.cancelWorkerExecution('SIGINT: Interrupted by user (Ctrl+C)', this.instanceId);
3464
- } catch (_) {}
3587
+ } catch (err) {
3588
+ this.logger.debug('cancelWorkerExecution failed.', err);
3589
+ }
3465
3590
  }
3466
3591
 
3467
3592
  this.isRunning = false;
@@ -4030,7 +4155,9 @@ declare module 'bun:sqlite' {
4030
4155
  try {
4031
4156
  const parsed = JSON.parse(responseBody);
4032
4157
  formattedBody = JSON.stringify(parsed, null, 2);
4033
- } catch (_) {}
4158
+ } catch (_) {
4159
+ formattedBody = responseBody;
4160
+ }
4034
4161
 
4035
4162
  const traceId = 'trace_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
4036
4163
  const traceItem = {
@@ -4103,7 +4230,9 @@ declare module 'bun:sqlite' {
4103
4230
  if (this.drawerTab === 'ports') this._renderDrawerBody();
4104
4231
  this._dismissPortToast(port);
4105
4232
  }));
4106
- } catch (_) {}
4233
+ } catch (err) {
4234
+ this.logger.warn('Failed to attach portTable event listeners.', err);
4235
+ }
4107
4236
  }
4108
4237
 
4109
4238
  _updatePortsPill() {
@@ -4177,16 +4306,55 @@ declare module 'bun:sqlite' {
4177
4306
  const url = (this.options && this.options.previewSwUrl) || 'preview-sw.js';
4178
4307
  try {
4179
4308
  const onMessage = (event) => this._handleServiceWorkerMessage(event);
4309
+ this._swMessageHandler = onMessage;
4180
4310
  if (typeof navigator.serviceWorker.addEventListener === 'function') {
4181
4311
  navigator.serviceWorker.addEventListener('message', onMessage);
4182
4312
  } else {
4183
4313
  navigator.serviceWorker.onmessage = onMessage;
4184
4314
  }
4185
4315
  navigator.serviceWorker.register(url, { scope: (this.options && this.options.previewSwScope) || './' })
4186
- .then((reg) => { this._previewSwRegistration = reg; this._previewSwReady = true; })
4187
- .catch(() => { this._previewSwReady = false; });
4188
- } 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) {
4189
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));
4190
4358
  }
4191
4359
  }
4192
4360
 
@@ -4219,11 +4387,15 @@ declare module 'bun:sqlite' {
4219
4387
  } else if (res && res.headers) {
4220
4388
  Object.assign(outHeaders, res.headers);
4221
4389
  }
4222
- } catch (_) {}
4390
+ } catch (err) {
4391
+ this.logger.debug('Could not copy response headers in _dispatchPreviewRequest.', err);
4392
+ }
4223
4393
  let bodyText = '';
4224
4394
  try {
4225
4395
  bodyText = res && typeof res.text === 'function' ? await res.text() : String((res && res.body) || '');
4226
- } catch (_) {}
4396
+ } catch (err) {
4397
+ this.logger.debug('Could not read response body in _dispatchPreviewRequest.', err);
4398
+ }
4227
4399
  return {
4228
4400
  status: (res && res.status) || 200,
4229
4401
  statusText: (res && res.statusText) || 'OK',
@@ -4250,44 +4422,170 @@ declare module 'bun:sqlite' {
4250
4422
  const p = Number(port) || 3000;
4251
4423
  const rawPath = pathAndQuery || '/';
4252
4424
  const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
4253
- const base = this.previewOrigin || '';
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 : '';
4254
4428
  return `${base}/__preview/${p}${path}`;
4255
4429
  }
4256
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
+
4257
4448
  _warnPreviewIsolation() {
4258
- if (this.previewOrigin || this._previewIsolationWarned) return;
4449
+ if (!this.previewOrigin || this._previewIsolationWarned) return;
4259
4450
  this._previewIsolationWarned = true;
4260
- if (typeof console !== 'undefined' && typeof console.warn === 'function') {
4261
- console.warn(
4262
- '[code-lab] Web Preview runs on the host origin and can read host storage. ' +
4263
- 'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
4264
- );
4265
- }
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
+ );
4266
4457
  }
4267
4458
 
4268
4459
  _injectPreviewCsp(html, port) {
4269
4460
  if (typeof html !== 'string' || !html) return html;
4270
- if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
4271
4461
 
4272
- const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
4273
- (/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
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;
4274
4474
 
4475
+ const injection = tags.join('');
4275
4476
  if (/<head\b[^>]*>/i.test(html)) {
4276
- return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
4477
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
4277
4478
  }
4278
4479
  if (/<html\b[^>]*>/i.test(html)) {
4279
- return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
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;
4280
4571
  }
4281
- return `<head>${tags}</head>${html}`;
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');
4282
4578
  }
4283
4579
 
4284
4580
  _openWebPreview(port, path = '/') {
4285
4581
  const p = Number(port) || this._firstListeningPort() || 3000;
4286
4582
  this._warnPreviewIsolation();
4583
+ this._installPreviewViolationListener();
4287
4584
  this.previewState.port = p;
4288
4585
  this.previewState.path = path || '/';
4289
4586
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
4290
4587
  this.previewState.error = null;
4588
+ this.previewState.violations = [];
4291
4589
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
4292
4590
  this.previewHistory.push(this.previewState.url);
4293
4591
  this.previewHistoryIdx = this.previewHistory.length - 1;
@@ -4378,7 +4676,7 @@ declare module 'bun:sqlite' {
4378
4676
  try {
4379
4677
  const win = window.open(url, '_blank');
4380
4678
  if (win) {
4381
- try { win.opener = null; } catch (_) {}
4679
+ try { win.opener = null; } catch (err) { this.logger.debug('Could not clear win.opener.', err); }
4382
4680
  opened = true;
4383
4681
  }
4384
4682
  } catch (_) { opened = false; }
@@ -4400,7 +4698,9 @@ declare module 'bun:sqlite' {
4400
4698
  const u = new URL(url);
4401
4699
  port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
4402
4700
  path = u.pathname + (u.search || '') + (u.hash || '');
4403
- } catch (_) {}
4701
+ } catch (err) {
4702
+ this.logger.debug('Failed to parse preview URL; using fallback port/path.', err);
4703
+ }
4404
4704
  this.previewState.port = port;
4405
4705
  this.previewState.path = path;
4406
4706
  this.previewState.url = url;
@@ -4432,7 +4732,9 @@ declare module 'bun:sqlite' {
4432
4732
  const u = new URL(url);
4433
4733
  this.previewState.port = Number(u.port || 80);
4434
4734
  this.previewState.path = u.pathname + (u.search || '');
4435
- } catch (_) {}
4735
+ } catch (err) {
4736
+ this.logger.debug('Failed to parse preview history URL.', err);
4737
+ }
4436
4738
  const input = this.container.querySelector('#cl-preview-url-input');
4437
4739
  if (input) input.value = url;
4438
4740
  this._renderWebPreviewControls();
@@ -4466,9 +4768,11 @@ declare module 'bun:sqlite' {
4466
4768
  try {
4467
4769
  const u = new URL(url);
4468
4770
  popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
4469
- } catch (_) {}
4771
+ } catch (err) {
4772
+ this.logger.debug('Failed to parse popout preview URL.', err);
4773
+ }
4470
4774
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
4471
- 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); }
4472
4776
  }
4473
4777
  return popout;
4474
4778
  }
@@ -4495,6 +4799,19 @@ declare module 'bun:sqlite' {
4495
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('')
4496
4800
  : `<option value="${this.previewState.port || 3000}">Port ${this.previewState.port || 3000}</option>`;
4497
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
+
4498
4815
  bodyEl.innerHTML = `
4499
4816
  <div class="codelab-preview">
4500
4817
  <div class="codelab-preview-chrome">
@@ -4510,10 +4827,12 @@ declare module 'bun:sqlite' {
4510
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>
4511
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>
4512
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>
4513
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>
4514
4833
  </div>
4515
4834
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
4516
- <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>
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>
4517
4836
  </div>
4518
4837
  ${servers.length
4519
4838
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -4526,6 +4845,7 @@ declare module 'bun:sqlite' {
4526
4845
  </div>`}
4527
4846
  </div>
4528
4847
  `;
4848
+ this._updatePreviewCspStatus();
4529
4849
  this._loadPreviewFrame();
4530
4850
  }
4531
4851
 
@@ -4553,7 +4873,9 @@ declare module 'bun:sqlite' {
4553
4873
  iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
4554
4874
  this.previewState.loading = false;
4555
4875
  return Promise.resolve();
4556
- } catch (_) {}
4876
+ } catch (err) {
4877
+ this.logger.warn('Failed to set Service Worker preview URL; falling back to srcdoc.', err);
4878
+ }
4557
4879
  }
4558
4880
 
4559
4881
  // Fallback (no Service Worker): dispatch via the virtual port table and
@@ -4619,7 +4941,7 @@ declare module 'bun:sqlite' {
4619
4941
  const full = dir === '/' ? '/' + entry : dir + '/' + entry;
4620
4942
  const rel = relPrefix ? relPrefix + '/' + entry : entry;
4621
4943
  let isDir = false;
4622
- try { isDir = vfs.statSync(full).isDirectory(); } catch (_) {}
4944
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
4623
4945
  if (isDir) {
4624
4946
  shellWorkspaceFolders.add(rel);
4625
4947
  walk(full, rel);
@@ -4627,7 +4949,9 @@ declare module 'bun:sqlite' {
4627
4949
  try {
4628
4950
  const content = String(vfs.readFileSync(full, 'utf8') ?? '');
4629
4951
  shellWorkspaceFiles.set(rel, content);
4630
- } catch (_) {}
4952
+ } catch (err) {
4953
+ this.logger.debug(`Could not read VFS file "${full}" during snapshot sync.`, err);
4954
+ }
4631
4955
  }
4632
4956
  }
4633
4957
  };
@@ -4929,6 +5253,27 @@ declare module 'bun:sqlite' {
4929
5253
  }
4930
5254
 
4931
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
+ }
4932
5277
  if (this.onCodeChange) {
4933
5278
  try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
4934
5279
  }
@@ -4986,7 +5331,7 @@ declare module 'bun:sqlite' {
4986
5331
  if (fallbackWrap) fallbackWrap.style.display = 'none';
4987
5332
  if (mdPreview) mdPreview.style.display = 'none';
4988
5333
  if (this.editor) {
4989
- try { this.editor.setModel(null); } catch (_) {}
5334
+ try { this.editor.setModel(null); } catch (err) { this.logger.debug('editor.setModel(null) failed.', err); }
4990
5335
  }
4991
5336
  if (emptyEl) {
4992
5337
  emptyEl.style.display = 'flex';
@@ -5298,7 +5643,9 @@ declare module 'bun:sqlite' {
5298
5643
  textarea.select();
5299
5644
  document.execCommand('copy');
5300
5645
  document.body.removeChild(textarea);
5301
- } catch (_) {}
5646
+ } catch (err) {
5647
+ this.logger.warn('Clipboard fallback (execCommand) failed.', err);
5648
+ }
5302
5649
  };
5303
5650
 
5304
5651
  if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
@@ -5656,6 +6003,7 @@ declare module 'bun:sqlite' {
5656
6003
  { id: 'rename-active', label: 'File: Rename Active File...', shortcut: 'F2', action: () => { if (this.activeFile) this.startInlineRename('file', this.activeFile); } },
5657
6004
  { id: 'delete-active', label: 'File: Delete Active File', action: () => { if (this.activeFile) this.deleteFile(this.activeFile); } },
5658
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 }) },
5659
6007
  { id: 'reset-workspace', label: 'Workspace: Reset Workspace to Clean State', action: () => this.resetLab() },
5660
6008
  { id: 'switch-lang', label: 'Language: Switch JavaScript / TypeScript', action: () => this.setLanguage(this.lang === 'js' ? 'ts' : 'js') },
5661
6009
  { id: 'switch-mode', label: 'Mode: Switch Guided / Sandbox Mode', action: () => this.setMode(this.mode === 'guided' ? 'sandbox' : 'guided') },
@@ -5666,6 +6014,9 @@ declare module 'bun:sqlite' {
5666
6014
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
5667
6015
  } },
5668
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() },
5669
6020
  { id: 'open-packages', label: 'Packages: Manage NPM Dependencies & Runtime', action: () => this.showPackagesModal() },
5670
6021
  { id: 'git-clone', label: 'Git: Clone Public GitHub Repository...', action: () => this.showCloneRepoModal() }
5671
6022
  ];
@@ -5698,7 +6049,9 @@ declare module 'bun:sqlite' {
5698
6049
  input.focus();
5699
6050
  try {
5700
6051
  input.setSelectionRange(initialVal.length, initialVal.length);
5701
- } catch (_) {}
6052
+ } catch (err) {
6053
+ this.logger.debug('input.setSelectionRange failed in command palette.', err);
6054
+ }
5702
6055
 
5703
6056
  input.addEventListener('input', () => {
5704
6057
  this.paletteSelectedIndex = 0;
@@ -5971,7 +6324,7 @@ declare module 'bun:sqlite' {
5971
6324
  const onUp = ev => {
5972
6325
  vSplitter.classList.remove('is-dragging');
5973
6326
  shell.classList.remove('is-resizing');
5974
- try { vSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
6327
+ try { vSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
5975
6328
  vSplitter.removeEventListener('pointermove', onMove);
5976
6329
  vSplitter.removeEventListener('pointerup', onUp);
5977
6330
  };
@@ -6012,7 +6365,7 @@ declare module 'bun:sqlite' {
6012
6365
  const onUp = ev => {
6013
6366
  hSplitter.classList.remove('is-dragging');
6014
6367
  shell.classList.remove('is-resizing-row');
6015
- try { hSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
6368
+ try { hSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
6016
6369
  hSplitter.removeEventListener('pointermove', onMove);
6017
6370
  hSplitter.removeEventListener('pointerup', onUp);
6018
6371
  };
@@ -6039,7 +6392,7 @@ declare module 'bun:sqlite' {
6039
6392
  e.preventDefault();
6040
6393
  fSplitter.classList.add('is-dragging');
6041
6394
  shell.classList.add('is-resizing');
6042
- try { fSplitter.setPointerCapture(e.pointerId); } catch (_) {}
6395
+ try { fSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
6043
6396
 
6044
6397
  const onMove = ev => {
6045
6398
  const ws = this.container.querySelector('.codelab-workspace');
@@ -6053,7 +6406,7 @@ declare module 'bun:sqlite' {
6053
6406
  const onUp = ev => {
6054
6407
  fSplitter.classList.remove('is-dragging');
6055
6408
  shell.classList.remove('is-resizing');
6056
- try { fSplitter.releasePointerCapture(ev.pointerId); } catch (_) {}
6409
+ try { fSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
6057
6410
  fSplitter.removeEventListener('pointermove', onMove);
6058
6411
  fSplitter.removeEventListener('pointerup', onUp);
6059
6412
  this._saveState();
@@ -6396,7 +6749,9 @@ declare module 'bun:sqlite' {
6396
6749
  if (this.files['package.json']) {
6397
6750
  try {
6398
6751
  pkgJson = JSON.parse(this.files['package.json']);
6399
- } catch (_) {}
6752
+ } catch (err) {
6753
+ this.logger.warn('Malformed package.json when adding dependency; reinitializing.', err);
6754
+ }
6400
6755
  }
6401
6756
  if (!pkgJson.dependencies || typeof pkgJson.dependencies !== 'object') {
6402
6757
  pkgJson.dependencies = {};
@@ -7057,6 +7412,219 @@ declare module 'bun:sqlite' {
7057
7412
  return true;
7058
7413
  }
7059
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
+
7060
7628
  getFiles() {
7061
7629
  return { ...this.files };
7062
7630
  }
@@ -7064,7 +7632,7 @@ declare module 'bun:sqlite' {
7064
7632
  setFiles(filesMap) {
7065
7633
  if (!filesMap || typeof filesMap !== 'object') return;
7066
7634
  for (const model of this.models.values()) {
7067
- try { model.dispose(); } catch (_) {}
7635
+ try { model.dispose(); } catch (err) { this.logger.debug('model.dispose failed during setFiles.', err); }
7068
7636
  }
7069
7637
  this.models.clear();
7070
7638
  this.files = {};
@@ -7154,7 +7722,9 @@ declare module 'bun:sqlite' {
7154
7722
  if (this.shell && this.shell.vfs && typeof this.shell.vfs.writeFile === 'function') {
7155
7723
  try {
7156
7724
  this.shell.vfs.writeFile('/workspace/' + clean, updated);
7157
- } catch (_) {}
7725
+ } catch (err) {
7726
+ this.logger.warn(`Failed to sync markdown task toggle for "${clean}" to VFS.`, err);
7727
+ }
7158
7728
  }
7159
7729
  this._notifyCodeChange(clean, updated);
7160
7730
  }
@@ -7374,9 +7944,22 @@ declare module 'bun:sqlite' {
7374
7944
 
7375
7945
  destroy() {
7376
7946
  this.stopExecution();
7947
+ if (this._previewReloadTimer) {
7948
+ clearTimeout(this._previewReloadTimer);
7949
+ this._previewReloadTimer = null;
7950
+ }
7377
7951
  if (this._escHandler && typeof document !== 'undefined') {
7378
7952
  document.removeEventListener('keydown', this._escHandler);
7379
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;
7380
7963
  if (this._themeObserver) {
7381
7964
  this._themeObserver.disconnect();
7382
7965
  }
@@ -7437,7 +8020,9 @@ declare module 'bun:sqlite' {
7437
8020
  if (jsonScript && jsonScript.textContent) {
7438
8021
  try {
7439
8022
  inlineConfig = JSON.parse(jsonScript.textContent);
7440
- } catch (_) {}
8023
+ } catch (err) {
8024
+ DEFAULT_LOGGER.warn('Failed to parse <script type="application/json"> inside <code-lab>.', err);
8025
+ }
7441
8026
  }
7442
8027
 
7443
8028
  // Parse optional files JSON attribute
@@ -7446,7 +8031,9 @@ declare module 'bun:sqlite' {
7446
8031
  if (filesAttr) {
7447
8032
  try {
7448
8033
  attrFiles = JSON.parse(filesAttr);
7449
- } catch (_) {}
8034
+ } catch (err) {
8035
+ DEFAULT_LOGGER.warn('Failed to parse files="" attribute on <code-lab>.', err);
8036
+ }
7450
8037
  }
7451
8038
 
7452
8039
  const labId = this.getAttribute('lab-id') || this.getAttribute('build-id') || this.dataset.labId || this.dataset.buildId || inlineConfig.id || inlineConfig.labId || 'custom-lab';
@@ -7489,6 +8076,19 @@ declare module 'bun:sqlite' {
7489
8076
  reset() { if (this._instance) this._instance.reset(); }
7490
8077
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
7491
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; }
7492
8092
  on(ev, fn) { return this._instance ? this._instance.on(ev, fn) : () => {}; }
7493
8093
  off(ev, fn) { if (this._instance) this._instance.off(ev, fn); }
7494
8094
  use(plugin, opts) { if (this._instance) this._instance.use(plugin, opts); return this; }
@@ -7523,9 +8123,42 @@ declare module 'bun:sqlite' {
7523
8123
  Workbench: CodeLabWorkbench,
7524
8124
  CodeLabWorkbench,
7525
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 },
7526
8135
  Runtime: root.CodeLabRuntime,
7527
8136
  Shell: root.CodeLabShell,
7528
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,
7529
8162
  renderMarkdown: renderSimpleMarkdown,
7530
8163
  renderSimpleMarkdown: renderSimpleMarkdown,
7531
8164
  extensions: {