@innovatorved/code-lab 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/code-lab.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v2.0.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.7 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -19,6 +19,7 @@
19
19
 
20
20
  // --- Module 1: Runtime Engine ---
21
21
  (function () {
22
+ // @ts-nocheck
22
23
  'use strict';
23
24
  if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined') {
24
25
  globalThis.Bun = { version: '1.1.20' };
@@ -8249,12 +8250,14 @@ if (typeof module !== 'undefined' && module.exports) {
8249
8250
  }
8250
8251
 
8251
8252
 
8253
+
8252
8254
  })();
8253
8255
 
8254
8256
  const CodeLabRuntime = root.CodeLabRuntime;
8255
8257
 
8256
8258
  // --- Module 2: POSIX Shell & Coreutils ---
8257
8259
  (function () {
8260
+ // @ts-nocheck
8258
8261
  /**
8259
8262
  * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
8260
8263
  *
@@ -10242,7 +10245,7 @@ if (typeof module !== 'undefined' && module.exports) {
10242
10245
  return 10 + depth * 0.1;
10243
10246
  }
10244
10247
 
10245
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
10248
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
10246
10249
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
10247
10250
  if (onProgress) {
10248
10251
  onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
@@ -10532,6 +10535,23 @@ if (typeof module !== 'undefined' && module.exports) {
10532
10535
  };
10533
10536
  }
10534
10537
 
10538
+ // Public wrapper: guarantee an `error` progress event when the clone fails
10539
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
10540
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
10541
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
10542
+ try {
10543
+ return await _cloneGitHubRepository(repoInput, vfs, options);
10544
+ } catch (err) {
10545
+ if (onProgress) {
10546
+ onProgress({
10547
+ phase: 'error',
10548
+ message: err && err.message ? err.message : String(err)
10549
+ });
10550
+ }
10551
+ throw err;
10552
+ }
10553
+ }
10554
+
10535
10555
  // =========================================================================
10536
10556
  // Package Management Helpers (npm / bun virtual modules & scripts)
10537
10557
  // =========================================================================
@@ -15513,12 +15533,14 @@ if (typeof module !== 'undefined' && module.exports) {
15513
15533
  };
15514
15534
  });
15515
15535
 
15536
+
15516
15537
  })();
15517
15538
 
15518
15539
  const CodeLabShell = root.CodeLabShell;
15519
15540
 
15520
15541
  // --- Module 3: PTY Terminal Engine ---
15521
15542
  (function () {
15543
+ // @ts-nocheck
15522
15544
  /**
15523
15545
  * @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
15524
15546
  *
@@ -16566,12 +16588,14 @@ if (typeof module !== 'undefined' && module.exports) {
16566
16588
  };
16567
16589
  });
16568
16590
 
16591
+
16569
16592
  })();
16570
16593
 
16571
16594
  const CodeLabTerminal = root.CodeLabTerminal;
16572
16595
 
16573
16596
  // --- Module 4: IDE Workbench & Web Component ---
16574
16597
  (function () {
16598
+ // @ts-nocheck
16575
16599
  /* ═══════════════════════════════════════════════════════════════════════════
16576
16600
  @innovatorved/code-lab — Interactive Monaco IDE Workbench & Guided Lab UI
16577
16601
  Supports <code-lab> Custom Element + window.CodeLab.mount() API
@@ -16615,6 +16639,10 @@ if (typeof module !== 'undefined' && module.exports) {
16615
16639
  const MONACO_BASE = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
16616
16640
  const STORAGE_PREFIX = 'sd-codelab-v1:';
16617
16641
 
16642
+ // The bundler rewrites this literal from package.json at build time. Keeping
16643
+ // the fallback in sync lets tests require src/workbench.js directly.
16644
+ const CODELAB_VERSION = '0.1.7';
16645
+
16618
16646
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
16619
16647
  const NODE_AMBIENT_DTS = `
16620
16648
  declare var require: (id: string) => any;
@@ -16951,6 +16979,33 @@ declare module 'bun:sqlite' {
16951
16979
  .replace(/'/g, '&#39;');
16952
16980
  }
16953
16981
 
16982
+ // Schemes that may appear in a rendered href. Everything else
16983
+ // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
16984
+ const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
16985
+
16986
+ function sanitizeUrl(raw) {
16987
+ if (raw === null || raw === undefined) return '#';
16988
+ const trimmed = String(raw).trim();
16989
+ if (!trimmed) return '#';
16990
+
16991
+ // Browsers ignore C0 controls and zero-width characters while resolving a
16992
+ // scheme, so `java\nscript:` and `java\u200Bscript:` still execute. Strip
16993
+ // them before deciding what the scheme is, but return the original value
16994
+ // when it is safe.
16995
+ const normalized = trimmed.replace(/[\u0000-\u0020\u007F\u200B-\u200D\uFEFF]/g, '');
16996
+ const schemeMatch = normalized.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
16997
+
16998
+ if (!schemeMatch) {
16999
+ // No scheme: a fragment, an absolute path, or a relative path.
17000
+ // Backslashes are treated as slashes by the URL parser and can turn a
17001
+ // "relative" URL into a protocol-relative one, so reject those.
17002
+ if (/^[\\/]{2}/.test(normalized) && !normalized.startsWith('/')) return '#';
17003
+ return trimmed;
17004
+ }
17005
+
17006
+ return SAFE_LINK_SCHEMES.has(schemeMatch[1].toLowerCase()) ? trimmed : '#';
17007
+ }
17008
+
16954
17009
  function formatErrorText(err) {
16955
17010
  if (!err) return '';
16956
17011
  if (typeof err === 'string') return err;
@@ -17144,14 +17199,9 @@ declare module 'bun:sqlite' {
17144
17199
 
17145
17200
  // Markdown Links: [label](url "title") or [label](url)
17146
17201
  text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
17147
- const cleanUrl = url.trim();
17202
+ const cleanUrl = sanitizeUrl(url);
17148
17203
  const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
17149
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`;
17150
- });
17151
-
17152
- // Autolinks: <https://...>
17153
- text = text.replace(/<(https?:\/\/[^>]+)>/g, (_, url) => {
17154
- return `<a href="${escapeHtml(url)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`;
17204
+ return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
17155
17205
  });
17156
17206
 
17157
17207
  // Strikethrough: ~~del~~
@@ -17346,8 +17396,9 @@ declare module 'bun:sqlite' {
17346
17396
  // Normalize CRLF to LF
17347
17397
  text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
17348
17398
 
17349
- // Prevent raw custom elements from executing within markdown previews
17350
- text = text.replace(/<\/?code-lab(\s[^>]*)?>/gi, (m) => escapeHtml(m));
17399
+ // NUL delimits internal placeholders. Strip author-supplied NULs so
17400
+ // markdown cannot forge a code-block or autolink placeholder.
17401
+ text = text.replace(/\u0000/g, '');
17351
17402
 
17352
17403
  // Phase 1: Fenced Code Block Extraction
17353
17404
  const codeBlocks = [];
@@ -17370,6 +17421,25 @@ declare module 'bun:sqlite' {
17370
17421
  return `\x00INLINECODE_${idx}\x00`;
17371
17422
  });
17372
17423
 
17424
+ // Phase 2b: Autolinks are the only inline construct that uses angle
17425
+ // brackets. Extract them before raw HTML is neutralized, then restore the
17426
+ // anchors in Phase 7.
17427
+ const autolinks = [];
17428
+ text = text.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => {
17429
+ const idx = autolinks.length;
17430
+ const safe = sanitizeUrl(url);
17431
+ autolinks.push(
17432
+ `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
17433
+ );
17434
+ return `\x00AUTOLINK_${idx}\x00`;
17435
+ });
17436
+
17437
+ // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
17438
+ // escaping that one character turns any author-supplied markup into text
17439
+ // without disturbing `>` blockquote syntax. From here on, every real tag
17440
+ // in the output is generated by this renderer.
17441
+ text = text.replace(/</g, '&lt;');
17442
+
17373
17443
  // Phase 3: GitHub Callout Alerts & Blockquotes
17374
17444
  const calloutBlocks = [];
17375
17445
  text = text.replace(/(?:^[ \t]*>.*(?:\n|$))+/gm, (match) => {
@@ -17447,7 +17517,8 @@ declare module 'bun:sqlite' {
17447
17517
  .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
17448
17518
  .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
17449
17519
  .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
17450
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '');
17520
+ .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
17521
+ .replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
17451
17522
 
17452
17523
  return finalHtml;
17453
17524
  }
@@ -17657,24 +17728,102 @@ declare module 'bun:sqlite' {
17657
17728
  let _workbenchInstanceCounter = 0;
17658
17729
  const _fallbackStorage = new Map();
17659
17730
 
17660
- function safeStorageGet(key) {
17731
+ // CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
17732
+ // in src/preview-sw.js — keep both copies in sync.
17733
+ const PREVIEW_CSP = [
17734
+ "default-src 'self' data: blob:",
17735
+ "base-uri 'self'",
17736
+ "object-src 'none'",
17737
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
17738
+ "style-src 'self' 'unsafe-inline'",
17739
+ "img-src 'self' data: blob:",
17740
+ "font-src 'self' data:",
17741
+ "connect-src 'self' data: blob:",
17742
+ "media-src 'self' data: blob:",
17743
+ "worker-src 'self' blob:",
17744
+ "frame-src 'self' data: blob:",
17745
+ "form-action 'self'",
17746
+ "frame-ancestors 'self'"
17747
+ ].join('; ');
17748
+
17749
+ function normalizePreviewOrigin(raw) {
17750
+ if (raw === null || raw === undefined || raw === '') return null;
17751
+ try {
17752
+ const parsed = new URL(String(raw));
17753
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
17754
+ return parsed.origin;
17755
+ } catch (_) {
17756
+ return null;
17757
+ }
17758
+ }
17759
+
17760
+ const LOG_PREFIX = '[code-lab]';
17761
+
17762
+ // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
17763
+ // into their own telemetry; `options.debug` enables verbose output. Errors
17764
+ // are never silently discarded.
17765
+ function createLogger(options = {}) {
17766
+ const sink = options.logger;
17767
+ const debugEnabled = options.debug === true;
17768
+
17769
+ const write = (level, args) => {
17770
+ if (level === 'debug' && !debugEnabled) return;
17771
+ if (sink && typeof sink[level] === 'function') {
17772
+ try {
17773
+ sink[level](...args);
17774
+ return;
17775
+ } catch (_) {
17776
+ // A broken host logger must not break the IDE; fall through.
17777
+ }
17778
+ }
17779
+ const fn = typeof console !== 'undefined' ? console[level] : null;
17780
+ if (typeof fn === 'function') fn(LOG_PREFIX, ...args);
17781
+ };
17782
+
17783
+ return {
17784
+ debug: (...args) => write('debug', args),
17785
+ info: (...args) => write('info', args),
17786
+ warn: (...args) => write('warn', args),
17787
+ error: (...args) => write('error', args)
17788
+ };
17789
+ }
17790
+
17791
+ const DEFAULT_LOGGER = createLogger();
17792
+
17793
+ function safeStorageGet(key, logger = DEFAULT_LOGGER) {
17661
17794
  try {
17662
17795
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17663
- return localStorage.getItem(key);
17796
+ const value = localStorage.getItem(key);
17797
+ if (value !== null && value !== undefined) return value;
17664
17798
  }
17665
- } catch (_) {}
17799
+ } catch (err) {
17800
+ logger.warn(
17801
+ `localStorage.getItem("${key}") failed; using in-memory state.`,
17802
+ err && err.message ? err.message : err
17803
+ );
17804
+ }
17666
17805
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
17667
17806
  }
17668
17807
 
17669
- function safeStorageSet(key, value) {
17808
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
17670
17809
  const str = String(value);
17671
17810
  try {
17672
17811
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17673
17812
  localStorage.setItem(key, str);
17674
- return;
17813
+ return true;
17675
17814
  }
17676
- } catch (_) {}
17815
+ } catch (err) {
17816
+ if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
17817
+ if (!safeStorageSet._warnedKeys.has(key)) {
17818
+ safeStorageSet._warnedKeys.add(key);
17819
+ logger.warn(
17820
+ `localStorage.setItem("${key}") failed; keeping state in memory for this session.`,
17821
+ err && err.message ? err.message : err
17822
+ );
17823
+ }
17824
+ }
17677
17825
  _fallbackStorage.set(key, str);
17826
+ return false;
17678
17827
  }
17679
17828
 
17680
17829
  // ── CodeLabWorkbench Instance Class ──────────────────────────────────────
@@ -17685,12 +17834,22 @@ declare module 'bun:sqlite' {
17685
17834
  throw new Error('CodeLabWorkbench requires a valid DOM container element.');
17686
17835
  }
17687
17836
  this.options = options || {};
17837
+ this.logger = createLogger({ logger: options.logger, debug: options.debug });
17838
+ this._persistenceFailureReported = false;
17688
17839
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
17689
17840
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
17690
17841
  this.title = options.title || this.labId;
17691
17842
  this.summary = options.summary || '';
17692
17843
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
17693
17844
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
17845
+ this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
17846
+ this._previewIsolationWarned = false;
17847
+ if (options.previewOrigin && !this.previewOrigin) {
17848
+ this.logger.warn(
17849
+ 'Ignoring invalid `previewOrigin`; expected an absolute http(s) origin ' +
17850
+ 'such as "https://preview.example.com".'
17851
+ );
17852
+ }
17694
17853
  this.explicitEntry = options.entry || null;
17695
17854
  this.explicitTestEntry = options.testEntry || options.testFile || null;
17696
17855
  this.backLabel = options.backLabel || 'Back to Build Guide';
@@ -18028,7 +18187,7 @@ declare module 'bun:sqlite' {
18028
18187
  const handlers = this._eventListeners.get(key);
18029
18188
  if (handlers) {
18030
18189
  for (const fn of Array.from(handlers)) {
18031
- try { fn(detail); } catch (_) {}
18190
+ try { fn(detail); } catch (err) { this.logger.error(`Listener for "${key}" threw.`, err); }
18032
18191
  }
18033
18192
  }
18034
18193
  }
@@ -18062,13 +18221,26 @@ declare module 'bun:sqlite' {
18062
18221
  return {};
18063
18222
  }
18064
18223
  try {
18065
- const raw = safeStorageGet(this._storageKey()) || safeStorageGet('sd_codelab_' + this.labId);
18224
+ const raw = safeStorageGet(this._storageKey(), this.logger) || safeStorageGet('sd_codelab_' + this.labId, this.logger);
18066
18225
  return raw ? JSON.parse(raw) : {};
18067
- } catch {
18226
+ } catch (err) {
18227
+ this.logger.warn(
18228
+ `Ignoring unreadable saved state for "${this.labId}".`,
18229
+ err && err.message ? err.message : err
18230
+ );
18068
18231
  return {};
18069
18232
  }
18070
18233
  }
18071
18234
 
18235
+ _reportPersistenceFailure() {
18236
+ if (this._persistenceFailureReported) return;
18237
+ this._persistenceFailureReported = true;
18238
+ this.logger.warn(
18239
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
18240
+ );
18241
+ this._emitEvent('persistence-error', { labId: this.labId });
18242
+ }
18243
+
18072
18244
  _saveState() {
18073
18245
  try {
18074
18246
  const key = `${this.mode}:${this.lang}`;
@@ -18093,11 +18265,20 @@ declare module 'bun:sqlite' {
18093
18265
  return;
18094
18266
  }
18095
18267
  const serialized = JSON.stringify(state);
18096
- safeStorageSet(this._storageKey(), serialized);
18097
- // Sync with host app sidebar & build overview progress trackers
18098
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr));
18099
- safeStorageSet('sd_codelab_' + this.labId, serialized);
18100
- } catch {}
18268
+ const persisted = [
18269
+ safeStorageSet(this._storageKey(), serialized, this.logger),
18270
+ // Sync with host app sidebar & build overview progress trackers
18271
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
18272
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
18273
+ ];
18274
+ if (persisted.includes(false)) this._reportPersistenceFailure();
18275
+ } catch (err) {
18276
+ this.logger.error(
18277
+ 'Failed to save workbench state.',
18278
+ err && err.message ? err.message : err
18279
+ );
18280
+ this._reportPersistenceFailure();
18281
+ }
18101
18282
  }
18102
18283
 
18103
18284
  _detectPackages() {
@@ -20662,8 +20843,44 @@ declare module 'bun:sqlite' {
20662
20843
  return `http://127.0.0.1:${port}${path}`;
20663
20844
  }
20664
20845
 
20846
+ _previewFrameUrl(port, pathAndQuery = '/') {
20847
+ const p = Number(port) || 3000;
20848
+ const rawPath = pathAndQuery || '/';
20849
+ const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
20850
+ const base = this.previewOrigin || '';
20851
+ return `${base}/__preview/${p}${path}`;
20852
+ }
20853
+
20854
+ _warnPreviewIsolation() {
20855
+ if (this.previewOrigin || this._previewIsolationWarned) return;
20856
+ this._previewIsolationWarned = true;
20857
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
20858
+ console.warn(
20859
+ '[code-lab] Web Preview runs on the host origin and can read host storage. ' +
20860
+ 'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
20861
+ );
20862
+ }
20863
+ }
20864
+
20865
+ _injectPreviewCsp(html, port) {
20866
+ if (typeof html !== 'string' || !html) return html;
20867
+ if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
20868
+
20869
+ const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
20870
+ (/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
20871
+
20872
+ if (/<head\b[^>]*>/i.test(html)) {
20873
+ return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
20874
+ }
20875
+ if (/<html\b[^>]*>/i.test(html)) {
20876
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
20877
+ }
20878
+ return `<head>${tags}</head>${html}`;
20879
+ }
20880
+
20665
20881
  _openWebPreview(port, path = '/') {
20666
20882
  const p = Number(port) || this._firstListeningPort() || 3000;
20883
+ this._warnPreviewIsolation();
20667
20884
  this.previewState.port = p;
20668
20885
  this.previewState.path = path || '/';
20669
20886
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
@@ -20842,10 +21059,10 @@ declare module 'bun:sqlite' {
20842
21059
 
20843
21060
  _popoutPreview() {
20844
21061
  const url = this._previewUrl();
20845
- let popout = '/__preview/';
21062
+ let popout = this._previewFrameUrl(this.previewState.port || 3000, '/');
20846
21063
  try {
20847
21064
  const u = new URL(url);
20848
- popout = `/__preview/${u.port}${u.pathname}${u.search || ''}`;
21065
+ popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
20849
21066
  } catch (_) {}
20850
21067
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
20851
21068
  try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
@@ -20855,6 +21072,7 @@ declare module 'bun:sqlite' {
20855
21072
 
20856
21073
  _renderWebPreview(bodyEl) {
20857
21074
  if (!bodyEl) return;
21075
+ this._warnPreviewIsolation();
20858
21076
  const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
20859
21077
  if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
20860
21078
  this._renderWebPreviewControls();
@@ -20892,7 +21110,7 @@ declare module 'bun:sqlite' {
20892
21110
  <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>
20893
21111
  </div>
20894
21112
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
20895
- <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
21113
+ <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" allow="camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'; usb 'none'" referrerpolicy="same-origin" title="Web Preview"></iframe>
20896
21114
  </div>
20897
21115
  ${servers.length
20898
21116
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -20929,7 +21147,7 @@ declare module 'bun:sqlite' {
20929
21147
  try {
20930
21148
  const u = new URL(fullUrl);
20931
21149
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
20932
- iframe.setAttribute('src', `/__preview/${u.port}${u.pathname}${u.search || ''}`);
21150
+ iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
20933
21151
  this.previewState.loading = false;
20934
21152
  return Promise.resolve();
20935
21153
  } catch (_) {}
@@ -20941,8 +21159,8 @@ declare module 'bun:sqlite' {
20941
21159
  .then((res) => {
20942
21160
  let body = res.body || '';
20943
21161
  const contentType = res.headers['content-type'] || res.headers['Content-Type'] || '';
20944
- if (/text\/html/i.test(contentType) && /<head\b/i.test(body) && !/<base\b/i.test(body)) {
20945
- body = body.replace(/<head\b[^>]*>/i, (m) => `${m}<base href="/__preview/${port}/">`);
21162
+ if (/text\/html/i.test(contentType)) {
21163
+ body = this._injectPreviewCsp(body, port);
20946
21164
  }
20947
21165
  this.previewState.srcdoc = body;
20948
21166
  this.previewState.loading = false;
@@ -20954,7 +21172,7 @@ declare module 'bun:sqlite' {
20954
21172
  this.previewState.loading = false;
20955
21173
  this.previewState.error = String((err && err.message) || err);
20956
21174
  const msg = `<body style="font-family:system-ui;padding:24px;color:#888"><h2>Preview unavailable</h2><p>${escapeHtml(this.previewState.error)}</p></body>`;
20957
- iframe.setAttribute('srcdoc', msg);
21175
+ iframe.setAttribute('srcdoc', this._injectPreviewCsp(msg, port));
20958
21176
  });
20959
21177
  }
20960
21178
 
@@ -21309,7 +21527,7 @@ declare module 'bun:sqlite' {
21309
21527
 
21310
21528
  _notifyCodeChange(filename, code) {
21311
21529
  if (this.onCodeChange) {
21312
- try { this.onCodeChange(filename, code); } catch (_) {}
21530
+ try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
21313
21531
  }
21314
21532
  const detail = { labId: this.labId, filename, path: filename, code, content: code };
21315
21533
  this._emitEvent('codelab:change', detail);
@@ -22948,7 +23166,7 @@ declare module 'bun:sqlite' {
22948
23166
  }
22949
23167
 
22950
23168
  if (this.onRun) {
22951
- try { this.onRun(res); } catch (_) {}
23169
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
22952
23170
  }
22953
23171
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'run', entry, result: res });
22954
23172
  } catch (err) {
@@ -23023,10 +23241,10 @@ declare module 'bun:sqlite' {
23023
23241
  }
23024
23242
 
23025
23243
  if (this.onTestResult) {
23026
- try { this.onTestResult(res); } catch (_) {}
23244
+ try { this.onTestResult(res); } catch (err) { this.logger.error('onTestResult callback threw.', err); }
23027
23245
  }
23028
23246
  if (this.onRun) {
23029
- try { this.onRun(res); } catch (_) {}
23247
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
23030
23248
  }
23031
23249
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'test', entry, result: res });
23032
23250
 
@@ -23040,7 +23258,7 @@ declare module 'bun:sqlite' {
23040
23258
  this.completedSteps.add(step.id);
23041
23259
  newlyCompleted = true;
23042
23260
  if (this.onStepComplete) {
23043
- try { this.onStepComplete(step, sIdx); } catch (_) {}
23261
+ try { this.onStepComplete(step, sIdx); } catch (err) { this.logger.error('onStepComplete callback threw.', err); }
23044
23262
  }
23045
23263
  const stepDetail = {
23046
23264
  labId: this.labId,
@@ -23059,7 +23277,7 @@ declare module 'bun:sqlite' {
23059
23277
  this._saveState();
23060
23278
  if (this.steps.length > 0 && this.completedSteps.size >= this.steps.length) {
23061
23279
  if (this.onLabComplete) {
23062
- try { this.onLabComplete(this.labId); } catch (_) {}
23280
+ try { this.onLabComplete(this.labId); } catch (err) { this.logger.error('onLabComplete callback threw.', err); }
23063
23281
  }
23064
23282
  this._emitEvent('codelab:lab-complete', {
23065
23283
  labId: this.labId,
@@ -23364,7 +23582,12 @@ declare module 'bun:sqlite' {
23364
23582
  a.click();
23365
23583
  setTimeout(() => URL.revokeObjectURL(url), 500);
23366
23584
  }
23367
- } catch (_) {}
23585
+ } catch (err) {
23586
+ this.logger.error(
23587
+ `Failed to start download for "${filename}".`,
23588
+ err && err.message ? err.message : err
23589
+ );
23590
+ }
23368
23591
  return content;
23369
23592
  }
23370
23593
 
@@ -23392,7 +23615,12 @@ declare module 'bun:sqlite' {
23392
23615
  a.click();
23393
23616
  setTimeout(() => URL.revokeObjectURL(url), 500);
23394
23617
  }
23395
- } catch (_) {}
23618
+ } catch (err) {
23619
+ this.logger.error(
23620
+ 'Failed to download workspace export.',
23621
+ err && err.message ? err.message : err
23622
+ );
23623
+ }
23396
23624
  }
23397
23625
  return snapshot;
23398
23626
  }
@@ -23888,7 +24116,7 @@ declare module 'bun:sqlite' {
23888
24116
  }
23889
24117
 
23890
24118
  const CodeLabSDK = {
23891
- version: '2.0.0',
24119
+ version: CODELAB_VERSION,
23892
24120
  Workbench: CodeLabWorkbench,
23893
24121
  CodeLabWorkbench,
23894
24122
  CodeLabElement: CodeLabElementClass,
@@ -4157,6 +4157,9 @@ var WorkbenchOptionsSchema = external_exports.object({
4157
4157
  testFile: external_exports.string().optional(),
4158
4158
  backLabel: external_exports.string().default("Back"),
4159
4159
  monacoUrl: external_exports.string().optional(),
4160
+ previewOrigin: external_exports.string().optional(),
4161
+ logger: external_exports.any().optional(),
4162
+ debug: external_exports.boolean().optional(),
4160
4163
  onClose: external_exports.function().returns(external_exports.void()).optional(),
4161
4164
  onRun: external_exports.function().args(external_exports.any()).returns(external_exports.void()).optional(),
4162
4165
  onTestResult: external_exports.function().args(external_exports.any()).returns(external_exports.void()).optional(),
@@ -4177,6 +4177,9 @@ var CodeLabGuidedLab = (() => {
4177
4177
  testFile: external_exports.string().optional(),
4178
4178
  backLabel: external_exports.string().default("Back"),
4179
4179
  monacoUrl: external_exports.string().optional(),
4180
+ previewOrigin: external_exports.string().optional(),
4181
+ logger: external_exports.any().optional(),
4182
+ debug: external_exports.boolean().optional(),
4180
4183
  onClose: external_exports.function().returns(external_exports.void()).optional(),
4181
4184
  onRun: external_exports.function().args(external_exports.any()).returns(external_exports.void()).optional(),
4182
4185
  onTestResult: external_exports.function().args(external_exports.any()).returns(external_exports.void()).optional(),
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @innovatorved/code-lab v2.0.0
2
+ * @innovatorved/code-lab v0.1.7
3
3
  * Browser-native IDE, POSIX Shell, Web Worker Node.js/Bun Runtime, and Git Engine.
4
4
  */
5
5
  export * from './schemas';