@innovatorved/code-lab 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/code-lab.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.1.8 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.10 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -147,7 +147,7 @@ var CodeLabCsp = (() => {
147
147
  const host = normalizeOrigin(options.hostOrigin);
148
148
  const self = host || "'self'";
149
149
  const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
150
- const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
150
+ const script = () => [self, "data:", "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
151
151
  const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
152
152
  const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
153
153
  return [
@@ -268,13 +268,22 @@ var CodeLabCsp = (() => {
268
268
  document.body.appendChild(existing);
269
269
  }
270
270
  existing.textContent = '';
271
+ var topBar = document.createElement('div');
272
+ topBar.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;padding-bottom:10px;border-bottom:1px solid rgba(248,113,113,0.28);';
271
273
  var header = document.createElement('div');
272
- header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
274
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
273
275
  header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
276
+ var closeBtn = document.createElement('button');
277
+ closeBtn.type = 'button';
278
+ closeBtn.textContent = 'Dismiss \xD7';
279
+ closeBtn.style.cssText = 'background:rgba(255,255,255,0.08);color:#e2e8f0;border:1px solid rgba(255,255,255,0.16);border-radius:6px;padding:4px 10px;font-size:11px;cursor:pointer;font-family:inherit;';
280
+ closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
281
+ topBar.appendChild(header);
282
+ topBar.appendChild(closeBtn);
274
283
  var pre = document.createElement('pre');
275
- pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
284
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
276
285
  pre.textContent = String(stack || msg || '');
277
- existing.appendChild(header);
286
+ existing.appendChild(topBar);
278
287
  existing.appendChild(pre);
279
288
  } catch (err) {
280
289
  void err;
@@ -315,6 +324,189 @@ var CodeLabCsp = (() => {
315
324
  void err;
316
325
  }
317
326
  });
327
+
328
+ // Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
329
+ var pendingFetches = new Map();
330
+ var fetchSeq = 0;
331
+ function parseLoopbackTarget(rawUrl) {
332
+ if (!rawUrl || typeof rawUrl !== 'string') return null;
333
+ var trimmed = rawUrl.trim();
334
+ if (!trimmed) return null;
335
+ var lower = trimmed.toLowerCase();
336
+ if (lower.indexOf('data:') === 0 || lower.indexOf('blob:') === 0 || lower.indexOf('mailto:') === 0 || lower.indexOf('tel:') === 0 || lower.indexOf('javascript:') === 0 || trimmed.charAt(0) === '#') return null;
337
+ if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
338
+ try {
339
+ var u = new URL(trimmed);
340
+ if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
341
+ return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
342
+ }
343
+ if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
344
+ var rest = u.pathname.slice('/__preview/'.length);
345
+ var slashIdx = rest.indexOf('/');
346
+ var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
347
+ var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
348
+ var portNum = Number(portStr);
349
+ if (portNum > 0) {
350
+ return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
351
+ }
352
+ }
353
+ } catch (e) { void e; }
354
+ return null;
355
+ }
356
+ if (trimmed.indexOf('/__preview/') === 0) {
357
+ var restRel = trimmed.slice('/__preview/'.length);
358
+ var sIdx = restRel.indexOf('/');
359
+ var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
360
+ var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
361
+ var pNum = Number(pStr);
362
+ if (pNum > 0) {
363
+ return { port: pNum, path: sPath || '/' };
364
+ }
365
+ }
366
+ var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
367
+ var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
368
+ return { port: null, path: pathPart };
369
+ }
370
+
371
+ window.addEventListener('message', function (event) {
372
+ var data = event && event.data;
373
+ if (!data || typeof data !== 'object') return;
374
+ if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
375
+ var entry = pendingFetches.get(data.reqId);
376
+ if (!entry) return;
377
+ pendingFetches.delete(data.reqId);
378
+ entry.resolve(data);
379
+ }
380
+ });
381
+
382
+ if (typeof window.fetch === 'function') {
383
+ var origFetch = window.fetch.bind(window);
384
+ window.fetch = function (input, init) {
385
+ var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
386
+ var target = parseLoopbackTarget(urlStr);
387
+ // Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
388
+ var isOpaque = false;
389
+ try {
390
+ var lowerUrl = urlStr.toLowerCase();
391
+ var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
392
+ isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
393
+ } catch (e) { isOpaque = true; void e; }
394
+ if (!target || !isOpaque || window.parent === window) {
395
+ return origFetch(input, init);
396
+ }
397
+ return new Promise(function (resolve, reject) {
398
+ var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
399
+ var method = (init && init.method) || (input && input.method) || 'GET';
400
+ var headersObj = {};
401
+ try {
402
+ var rawH = (init && init.headers) || (input && input.headers);
403
+ if (rawH) {
404
+ if (typeof rawH.forEach === 'function') {
405
+ rawH.forEach(function (v, k) { headersObj[k] = v; });
406
+ } else if (Array.isArray(rawH)) {
407
+ rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
408
+ } else if (typeof rawH === 'object') {
409
+ Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
410
+ }
411
+ }
412
+ } catch (e) { void e; }
413
+ var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
414
+ var timer = setTimeout(function () {
415
+ if (pendingFetches.has(reqId)) {
416
+ pendingFetches.delete(reqId);
417
+ origFetch(input, init).then(resolve, reject);
418
+ }
419
+ }, 5000);
420
+ pendingFetches.set(reqId, {
421
+ resolve: function (payload) {
422
+ clearTimeout(timer);
423
+ if (payload && payload.error) {
424
+ reject(new TypeError(String(payload.error)));
425
+ return;
426
+ }
427
+ var status = Number(payload && payload.status) || 200;
428
+ var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
429
+ var body = payload && payload.body !== undefined ? String(payload.body) : '';
430
+ try {
431
+ resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
432
+ } catch (err) {
433
+ void err;
434
+ resolve({
435
+ ok: status >= 200 && status < 300,
436
+ status: status,
437
+ headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
438
+ text: function () { return Promise.resolve(body); },
439
+ json: function () { return Promise.resolve(JSON.parse(body)); }
440
+ });
441
+ }
442
+ }
443
+ });
444
+ try {
445
+ parent.postMessage({
446
+ type: 'codelab:preview-fetch',
447
+ reqId: reqId,
448
+ port: target.port,
449
+ path: target.path,
450
+ method: String(method).toUpperCase(),
451
+ headers: headersObj,
452
+ body: bodyStr
453
+ }, '*');
454
+ } catch (err) {
455
+ clearTimeout(timer);
456
+ pendingFetches.delete(reqId);
457
+ origFetch(input, init).then(resolve, reject);
458
+ }
459
+ });
460
+ };
461
+ }
462
+
463
+ // Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
464
+ document.addEventListener('click', function (event) {
465
+ if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
466
+ var el = event.target;
467
+ while (el && el.tagName !== 'A') el = el.parentElement;
468
+ if (!el || !el.getAttribute) return;
469
+ var href = el.getAttribute('href');
470
+ var targetAttr = el.getAttribute('target');
471
+ if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
472
+ var lowerHref = href.toLowerCase();
473
+ if (href.charAt(0) === '#' || lowerHref.indexOf('mailto:') === 0 || lowerHref.indexOf('tel:') === 0 || lowerHref.indexOf('javascript:') === 0 || lowerHref.indexOf('data:') === 0 || lowerHref.indexOf('blob:') === 0) return;
474
+ var parsed = parseLoopbackTarget(href);
475
+ if (!parsed) return;
476
+ event.preventDefault();
477
+ try {
478
+ parent.postMessage({
479
+ type: 'codelab:preview-navigate',
480
+ port: parsed.port,
481
+ path: parsed.path
482
+ }, '*');
483
+ } catch (e) { void e; }
484
+ });
485
+
486
+ // Sync SPA history.pushState / replaceState with the preview omni-address bar
487
+ try {
488
+ ['pushState', 'replaceState'].forEach(function (method) {
489
+ var orig = history[method];
490
+ if (typeof orig !== 'function') return;
491
+ history[method] = function (state, title, url) {
492
+ var ret;
493
+ try { ret = orig.apply(history, arguments); } catch (e) { void e; }
494
+ if (url !== undefined && url !== null) {
495
+ var parsed = parseLoopbackTarget(String(url));
496
+ if (parsed) {
497
+ try {
498
+ parent.postMessage({
499
+ type: 'codelab:preview-url-change',
500
+ path: parsed.path,
501
+ replace: method === 'replaceState'
502
+ }, '*');
503
+ } catch (e) { void e; }
504
+ }
505
+ }
506
+ return ret;
507
+ };
508
+ });
509
+ } catch (e) { void e; }
318
510
  })();
319
511
  <\/script>`;
320
512
  }
@@ -12992,10 +13184,40 @@ if (typeof module !== 'undefined' && module.exports) {
12992
13184
  return imports;
12993
13185
  }
12994
13186
 
12995
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
12996
- const scripts = [];
13187
+ // Some templates pin a CDN URL in the source instead of importing a bare
13188
+ // specifier, e.g. `import React from "https://cdn.jsdelivr.net/npm/react@19.3.1/+esm"`.
13189
+ // Those URL specifiers are resolved by the browser directly, so they bypass the
13190
+ // generated import map (and with it the project's declared version and the
13191
+ // multi-CDN fallback). Import maps can remap URL specifiers, so alias each
13192
+ // literal URL found in the project to the resolved bare-specifier URL.
13193
+ // The pinned version is kept when the project has no dependency to resolve.
13194
+ const PINNED_CDN_URL_RE = /https?:\/\/(?:cdn\.jsdelivr\.net\/npm|esm\.sh)\/((?:@[^\/'"`@\s]+\/)?[^\/'"`@\s]+)@([^\s'"`),;]+)/g;
13195
+
13196
+ function aliasPinnedCdnUrls(vfs, rootDir, text, importMap) {
13197
+ if (!text || typeof text !== 'string') return;
13198
+ const re = new RegExp(PINNED_CDN_URL_RE.source, 'g');
13199
+ let match;
13200
+ while ((match = re.exec(text)) !== null) {
13201
+ const url = match[0];
13202
+ const pkgName = decodeURIComponent(match[1]);
13203
+ const rest = match[2];
13204
+ const pinnedVersion = rest.split(/[\/?]/)[0];
13205
+ const tail = rest.slice(pinnedVersion.length);
13206
+ const rawSubpath = tail.startsWith('/') && tail !== '/+esm' ? tail.slice(1).split(/[?#]/)[0] : '';
13207
+ const subpath = rawSubpath.replace(/^\/+|\/+$/g, '');
13208
+ const bare = subpath ? `${pkgName}/${subpath}` : pkgName;
13209
+
13210
+ const declared = resolveBareVersion(vfs, rootDir, pkgName);
13211
+ const version = declared && declared !== 'latest' ? declared : decodeURIComponent(pinnedVersion);
13212
+ const target = importMap[bare] || cdnEsmUrl(pkgName, version, subpath || undefined);
13213
+ if (target && target !== url) importMap[url] = target;
13214
+ }
13215
+ }
13216
+
13217
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
13218
+ const files = [];
12997
13219
  const walk = (dir, depth) => {
12998
- if (depth > 8 || scripts.length >= maxFiles) return;
13220
+ if (depth > 8 || files.length >= maxFiles) return;
12999
13221
  let entries = [];
13000
13222
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
13001
13223
  for (const name of entries) {
@@ -13006,13 +13228,23 @@ if (typeof module !== 'undefined' && module.exports) {
13006
13228
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
13007
13229
  if (dirFlag) {
13008
13230
  walk(full, depth + 1);
13009
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
13010
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
13231
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
13232
+ try {
13233
+ const content = vfs.readFileSync(full, 'utf8');
13234
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
13235
+ files.push({ full, rel, content });
13236
+ } catch (err) {
13237
+ _shellLogger.debug('Preview script read skipped.', full, err);
13238
+ }
13011
13239
  }
13012
13240
  }
13013
13241
  };
13014
13242
  walk(rootDir, 0);
13015
- return scripts;
13243
+ return files;
13244
+ }
13245
+
13246
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
13247
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
13016
13248
  }
13017
13249
 
13018
13250
  function injectPreviewExtras(html, importMap) {
@@ -13037,12 +13269,6 @@ if (typeof module !== 'undefined' && module.exports) {
13037
13269
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
13038
13270
  while (taken.has(port)) port++;
13039
13271
 
13040
- const specifiers = new Set();
13041
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
13042
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
13043
- }
13044
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
13045
-
13046
13272
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
13047
13273
  const isDir = (p) => {
13048
13274
  try {
@@ -13050,8 +13276,111 @@ if (typeof module !== 'undefined' && module.exports) {
13050
13276
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
13051
13277
  } catch (_) { return false; }
13052
13278
  };
13279
+ const isFile = (p) => exists(p) && !isDir(p);
13053
13280
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
13054
13281
 
13282
+ const resolveLocalTarget = (baseDir, rawSpec) => {
13283
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
13284
+ const clean = rawSpec.split(/[?#]/)[0].trim();
13285
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
13286
+ const candidateBase = clean.startsWith('/')
13287
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
13288
+ : PosixPath.join(baseDir, clean);
13289
+ if (isFile(candidateBase)) return candidateBase;
13290
+ const cands = [
13291
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
13292
+ candidateBase + '.mjs', candidateBase + '.cjs',
13293
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
13294
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
13295
+ ];
13296
+ for (const c of cands) {
13297
+ if (isFile(c)) return c;
13298
+ }
13299
+ return null;
13300
+ };
13301
+
13302
+ const toLocalImportKey = (fullPath) => {
13303
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
13304
+ return `@codelab-local/${rel}`;
13305
+ };
13306
+
13307
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
13308
+ let out = code;
13309
+ try {
13310
+ const rm = getRuntimeModule();
13311
+ if (rm && typeof rm.transpileForBrowser === 'function') {
13312
+ out = rm.transpileForBrowser(out, sourcePath);
13313
+ }
13314
+ } catch (err) {
13315
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
13316
+ }
13317
+ const fromDir = PosixPath.dirname(sourcePath);
13318
+ const rewriteSpec = (spec) => {
13319
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
13320
+ const resolved = resolveLocalTarget(fromDir, spec);
13321
+ return resolved ? toLocalImportKey(resolved) : spec;
13322
+ };
13323
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13324
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13325
+ return out;
13326
+ };
13327
+
13328
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
13329
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
13330
+ const specifiers = new Set();
13331
+ for (const f of scriptFiles) {
13332
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
13333
+ }
13334
+ // Also scan inline module scripts in HTML for bare specifiers
13335
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
13336
+ let inlineMatch;
13337
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
13338
+ if (inlineMatch[1]) {
13339
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
13340
+ }
13341
+ }
13342
+
13343
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
13344
+ for (const f of scriptFiles) aliasPinnedCdnUrls(ctx.vfs, rootDir, f.content, importMap);
13345
+ aliasPinnedCdnUrls(ctx.vfs, rootDir, htmlBody, importMap);
13346
+ for (const f of scriptFiles) {
13347
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
13348
+ const key = toLocalImportKey(f.full);
13349
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
13350
+ }
13351
+
13352
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
13353
+ let transformedHtml = htmlBody;
13354
+
13355
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
13356
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
13357
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
13358
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
13359
+ if (!hrefMatch) return fullTag;
13360
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
13361
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
13362
+ const cssContent = readText(cssTarget);
13363
+ if (cssContent === null) return fullTag;
13364
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
13365
+ });
13366
+
13367
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
13368
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
13369
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
13370
+ if (!srcMatch) return fullTag;
13371
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
13372
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
13373
+ const rawScript = readText(scriptTarget);
13374
+ if (rawScript === null) return fullTag;
13375
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
13376
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
13377
+ const typeAttr = isMod ? ' type="module"' : '';
13378
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
13379
+ });
13380
+
13381
+ return injectPreviewExtras(transformedHtml, importMap);
13382
+ };
13383
+
13055
13384
  const handler = async (request) => {
13056
13385
  let pathname = '/';
13057
13386
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
@@ -13086,7 +13415,7 @@ if (typeof module !== 'undefined' && module.exports) {
13086
13415
  let body = readText(target);
13087
13416
  if (body === null) body = '';
13088
13417
  if (/\.html?$/i.test(target)) {
13089
- body = injectPreviewExtras(body, importMap);
13418
+ body = buildHtmlPreviewResponse(body, target);
13090
13419
  } else if (isPreviewScriptPath(target)) {
13091
13420
  try {
13092
13421
  const rm = getRuntimeModule();
@@ -18456,7 +18785,7 @@ if (typeof module !== 'undefined' && module.exports) {
18456
18785
 
18457
18786
  // The bundler rewrites this literal from package.json at build time. Keeping
18458
18787
  // the fallback in sync lets tests require src/workbench.js directly.
18459
- const CODELAB_VERSION = '0.1.8';
18788
+ const CODELAB_VERSION = '0.1.10';
18460
18789
 
18461
18790
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
18462
18791
  const NODE_AMBIENT_DTS = `
@@ -19763,6 +20092,11 @@ declare module 'bun:sqlite' {
19763
20092
  this.explorerWidth = (typeof this.savedState?.explorerWidth === 'number' && this.savedState.explorerWidth >= 120)
19764
20093
  ? this.savedState.explorerWidth
19765
20094
  : 196;
20095
+ // 0 = use the default 44% track; otherwise a pixel width chosen by dragging
20096
+ // the preview splitter.
20097
+ this.previewSplitWidth = (typeof this.savedState?.previewSplitWidth === 'number' && this.savedState.previewSplitWidth >= 200)
20098
+ ? this.savedState.previewSplitWidth
20099
+ : 0;
19766
20100
  this.folderSwitcherOpen = false;
19767
20101
  this.creatingItem = null; // { type: 'file' | 'folder', parentFolder: string } | null
19768
20102
  this.renamingItem = null;
@@ -19775,6 +20109,10 @@ declare module 'bun:sqlite' {
19775
20109
  path: '/',
19776
20110
  url: '',
19777
20111
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
20112
+ dockMode: (options && options.previewDock === 'split') ? 'split' : 'bottom', // 'bottom' | 'split'
20113
+ maximized: false,
20114
+ consoleOpen: false,
20115
+ consoleLogs: [],
19778
20116
  loading: false,
19779
20117
  error: null,
19780
20118
  srcdoc: '',
@@ -19786,6 +20124,7 @@ declare module 'bun:sqlite' {
19786
20124
  this._previewSwRegistration = null;
19787
20125
  this._previewViolationHandler = null;
19788
20126
  this._swMessageHandler = null;
20127
+ this._beforeUnloadHandler = null;
19789
20128
  this._portToasts = new Map();
19790
20129
  this.isFullscreen = false;
19791
20130
  this.isRunning = false;
@@ -20132,6 +20471,11 @@ declare module 'bun:sqlite' {
20132
20471
  const key = `${this.mode}:${this.lang}`;
20133
20472
  const customFiles = (this.savedState && this.savedState.customFiles) || {};
20134
20473
  customFiles[key] = { ...this.files };
20474
+ const hasSnapshot = Object.assign(
20475
+ {},
20476
+ (this.savedState && this.savedState.hasSnapshot) || {},
20477
+ { [key]: true }
20478
+ );
20135
20479
  const completedArr = Array.from(this.completedSteps);
20136
20480
  const state = {
20137
20481
  mode: this.mode,
@@ -20139,12 +20483,14 @@ declare module 'bun:sqlite' {
20139
20483
  activeStepIndex: this.activeStepIndex,
20140
20484
  completedSteps: completedArr,
20141
20485
  customFiles,
20486
+ hasSnapshot,
20142
20487
  openTabs: Array.isArray(this.openTabs) ? [...this.openTabs] : undefined,
20143
20488
  activeFile: this.activeFile,
20144
20489
  folders: Array.from(this.folders || []),
20145
20490
  collapsedFolders: Array.from(this.collapsedFolders || []),
20146
20491
  explorerFolder: this.explorerFolder || '',
20147
- explorerWidth: typeof this.explorerWidth === 'number' ? this.explorerWidth : undefined
20492
+ explorerWidth: typeof this.explorerWidth === 'number' ? this.explorerWidth : undefined,
20493
+ previewSplitWidth: this.previewSplitWidth || undefined
20148
20494
  };
20149
20495
  this.savedState = state;
20150
20496
  if (this.options && this.options.persistState === false) {
@@ -20163,6 +20509,20 @@ declare module 'bun:sqlite' {
20163
20509
  safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
20164
20510
  safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
20165
20511
  ];
20512
+ if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
20513
+ try {
20514
+ if (!this._idbStorage) {
20515
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
20516
+ }
20517
+ if (this._idbStorage && typeof this._idbStorage.save === 'function') {
20518
+ Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
20519
+ this.logger.debug('Async WorkspaceStorage save skipped.', err);
20520
+ });
20521
+ }
20522
+ } catch (err) {
20523
+ this.logger.debug('WorkspaceStorage initialization skipped.', err);
20524
+ }
20525
+ }
20166
20526
  if (persisted.includes(false)) {
20167
20527
  this._reportPersistenceFailure(safeStorageSet._lastError);
20168
20528
  } else {
@@ -20315,6 +20675,9 @@ declare module 'bun:sqlite' {
20315
20675
  const key = `${this.mode}:${this.lang}`;
20316
20676
  const saved = this.savedState.customFiles?.[key];
20317
20677
  const base = this._getBaseFilesForModeAndLang(this.mode, this.lang);
20678
+ if (this.savedState && this.savedState.hasSnapshot && this.savedState.hasSnapshot[key] && saved && typeof saved === 'object') {
20679
+ return { ...saved };
20680
+ }
20318
20681
  if (saved && Object.keys(saved).length > 0) {
20319
20682
  return { ...base, ...saved };
20320
20683
  }
@@ -20389,7 +20752,9 @@ declare module 'bun:sqlite' {
20389
20752
  const themeAttr = this.themeOption !== 'auto' ? `data-theme="${escapeHtml(this.themeOption)}"` : '';
20390
20753
  const brandLabel = (this.title && this.title !== 'custom-lab' && this.title !== this.labId) ? this.title : 'code-lab';
20391
20754
  const isGuideCollapsed = !this.hasGuidedLab || this.mode === 'sandbox' || !this.steps.length;
20392
- const explorerStyle = `style="--cl-explorer-width:${Math.round(this.explorerWidth || 196)}px"`;
20755
+ const shellVars = [`--cl-explorer-width:${Math.round(this.explorerWidth || 196)}px`];
20756
+ if (this.previewSplitWidth) shellVars.push(`--cl-preview-split-width:${Math.round(this.previewSplitWidth)}px`);
20757
+ const explorerStyle = `style="${shellVars.join(';')}"`;
20393
20758
  this.container.innerHTML = `
20394
20759
  <div class="codelab codelab-workbench ${isGuideCollapsed ? 'guide-collapsed' : ''}" id="codelab-${escapeHtml(this.labId)}" ${themeAttr} ${explorerStyle}>
20395
20760
  <!-- Top Bar -->
@@ -20527,6 +20892,10 @@ declare module 'bun:sqlite' {
20527
20892
  <div class="codelab-empty-editor" id="cl-empty-editor" style="display:none"></div>
20528
20893
  </div>
20529
20894
  </div>
20895
+
20896
+ <!-- Right-Hand Split Web Preview Pane -->
20897
+ <div class="codelab-splitter-preview" id="cl-splitter-preview" role="separator" aria-orientation="vertical" title="Drag to resize web preview (double-click to reset)" style="display:none"></div>
20898
+ <div class="codelab-preview-split" id="cl-preview-split" aria-label="In-Browser Web Preview" style="display:none"></div>
20530
20899
  </div>
20531
20900
 
20532
20901
  <!-- Interactive Horizontal Splitter -->
@@ -21780,6 +22149,7 @@ declare module 'bun:sqlite' {
21780
22149
  }
21781
22150
 
21782
22151
  if (this.drawerTab === 'preview') {
22152
+ bodyEl.scrollTop = 0;
21783
22153
  this._renderWebPreview(bodyEl);
21784
22154
  return;
21785
22155
  }
@@ -22908,6 +23278,10 @@ declare module 'bun:sqlite' {
22908
23278
  type: level === 'error' ? 'stderr' : 'stdout',
22909
23279
  text: `[Preview ${level.toUpperCase()}] ${text}`
22910
23280
  });
23281
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23282
+ this.previewState.consoleLogs.push({ level, text, timestamp: new Date().toLocaleTimeString() });
23283
+ if (this.previewState.consoleLogs.length > 200) this.previewState.consoleLogs.shift();
23284
+ this._updatePreviewConsoleUI();
22911
23285
  this._emitEvent('preview-console', { level, text, args });
22912
23286
  } else if (data.type === 'codelab:preview-error') {
22913
23287
  const msg = String(data.message || 'Uncaught runtime error');
@@ -22922,9 +23296,66 @@ declare module 'bun:sqlite' {
22922
23296
  type: 'stderr',
22923
23297
  text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
22924
23298
  });
23299
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23300
+ this.previewState.consoleLogs.push({
23301
+ level: 'error',
23302
+ text: `${msg}${data.stack ? '\n' + String(data.stack) : ''}`,
23303
+ timestamp: new Date().toLocaleTimeString()
23304
+ });
23305
+ this._updatePreviewConsoleUI();
22925
23306
  this._emitEvent('preview-error', this.previewState.runtimeError);
22926
23307
  } else if (data.type === 'codelab:preview-error-clear') {
22927
23308
  this.previewState.runtimeError = null;
23309
+ } else if (data.type === 'codelab:preview-fetch') {
23310
+ const reqId = data.reqId || data.id;
23311
+ const targetPort = Number(data.port) || this.previewState.port || this._firstListeningPort() || 3000;
23312
+ const reqPath = data.path ? (String(data.path).startsWith('/') ? String(data.path) : '/' + String(data.path)) : '/';
23313
+ const targetUrl = String(data.url || `http://127.0.0.1:${targetPort}${reqPath}`);
23314
+ this._dispatchPreviewRequest({
23315
+ port: targetPort,
23316
+ url: targetUrl,
23317
+ method: data.method || 'GET',
23318
+ headers: data.headers || {},
23319
+ body: data.body !== undefined ? data.body : null
23320
+ })
23321
+ .then((res) => {
23322
+ const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
23323
+ if (netPill) netPill.textContent = `${(this.lastHttpTrace || []).length} reqs`;
23324
+ if (this.drawerTab === 'network') this._renderDrawerBody();
23325
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23326
+ iframe.contentWindow.postMessage({
23327
+ type: 'codelab:preview-fetch-res',
23328
+ reqId,
23329
+ id: reqId,
23330
+ status: res.status || 200,
23331
+ statusText: res.statusText || 'OK',
23332
+ headers: res.headers || {},
23333
+ body: res.body || ''
23334
+ }, '*');
23335
+ }
23336
+ })
23337
+ .catch((err) => {
23338
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23339
+ iframe.contentWindow.postMessage({
23340
+ type: 'codelab:preview-fetch-res',
23341
+ reqId,
23342
+ id: reqId,
23343
+ error: String((err && err.message) || err)
23344
+ }, '*');
23345
+ }
23346
+ });
23347
+ } else if (data.type === 'codelab:preview-navigate') {
23348
+ const navHref = data.href || (data.path ? (data.port ? `http://127.0.0.1:${data.port}${data.path}` : String(data.path)) : '');
23349
+ if (navHref) {
23350
+ this._previewGo(String(navHref));
23351
+ }
23352
+ } else if (data.type === 'codelab:preview-url-change') {
23353
+ if (data.path && typeof data.path === 'string') {
23354
+ this.previewState.path = data.path.startsWith('/') ? data.path : '/' + data.path;
23355
+ this.previewState.url = this._previewUrl();
23356
+ const input = this.container ? this.container.querySelector('#cl-preview-url-input') : null;
23357
+ if (input) input.value = this.previewState.url;
23358
+ }
22928
23359
  }
22929
23360
  };
22930
23361
  window.addEventListener('message', this._previewViolationHandler);
@@ -22988,7 +23419,12 @@ declare module 'bun:sqlite' {
22988
23419
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
22989
23420
  this.previewHistory.push(this.previewState.url);
22990
23421
  this.previewHistoryIdx = this.previewHistory.length - 1;
22991
- this.switchDrawerTab('preview');
23422
+ if (this.previewState.dockMode === 'split') {
23423
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23424
+ if (splitHost) this._renderWebPreview(splitHost);
23425
+ } else {
23426
+ this.switchDrawerTab('preview');
23427
+ }
22992
23428
  return this._previewLoadPromise || Promise.resolve();
22993
23429
  }
22994
23430
 
@@ -23107,7 +23543,12 @@ declare module 'bun:sqlite' {
23107
23543
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
23108
23544
  this.previewHistory.push(url);
23109
23545
  this.previewHistoryIdx = this.previewHistory.length - 1;
23110
- this.switchDrawerTab('preview');
23546
+ if (this.previewState.dockMode === 'split') {
23547
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23548
+ if (splitHost) this._renderWebPreview(splitHost);
23549
+ } else {
23550
+ this.switchDrawerTab('preview');
23551
+ }
23111
23552
  return this._previewLoadPromise || Promise.resolve();
23112
23553
  }
23113
23554
 
@@ -23148,6 +23589,97 @@ declare module 'bun:sqlite' {
23148
23589
  if (!['desktop', 'tablet', 'mobile'].includes(mode)) return;
23149
23590
  this.previewState.frameMode = mode;
23150
23591
  this._renderDrawerBody();
23592
+ if (this.previewState.dockMode === 'split') {
23593
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23594
+ if (splitHost) this._renderWebPreview(splitHost);
23595
+ }
23596
+ }
23597
+
23598
+ _togglePreviewDock() {
23599
+ this.previewState.dockMode = this.previewState.dockMode === 'split' ? 'bottom' : 'split';
23600
+ this._previewRenderKey = null;
23601
+ const ws = this.container ? this.container.querySelector('.codelab-workspace') : null;
23602
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23603
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23604
+ if (this.previewState.dockMode === 'split') {
23605
+ if (ws) ws.classList.add('has-preview-split');
23606
+ if (splitBar) splitBar.style.display = 'block';
23607
+ if (splitHost) {
23608
+ splitHost.style.display = 'flex';
23609
+ this._renderWebPreview(splitHost);
23610
+ }
23611
+ if (this.drawerTab === 'preview') {
23612
+ this.switchDrawerTab('terminal');
23613
+ } else {
23614
+ this._renderDrawerBody();
23615
+ }
23616
+ } else {
23617
+ if (ws) ws.classList.remove('has-preview-split');
23618
+ if (splitBar) splitBar.style.display = 'none';
23619
+ if (splitHost) {
23620
+ splitHost.style.display = 'none';
23621
+ splitHost.innerHTML = '';
23622
+ }
23623
+ this.switchDrawerTab('preview');
23624
+ }
23625
+ if (this.editor && typeof this.editor.layout === 'function') {
23626
+ setTimeout(() => {
23627
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
23628
+ }, 30);
23629
+ }
23630
+ }
23631
+
23632
+ _togglePreviewMaximize() {
23633
+ this.previewState.maximized = !this.previewState.maximized;
23634
+ const previewEl = this.container ? this.container.querySelector('.codelab-preview') : null;
23635
+ if (previewEl) {
23636
+ previewEl.classList.toggle('is-maximized', Boolean(this.previewState.maximized));
23637
+ }
23638
+ const maxBtn = this.container ? this.container.querySelector('[data-cl-action="preview-maximize"]') : null;
23639
+ if (maxBtn) {
23640
+ maxBtn.classList.toggle('active', Boolean(this.previewState.maximized));
23641
+ }
23642
+ }
23643
+
23644
+ _togglePreviewConsole() {
23645
+ this.previewState.consoleOpen = !this.previewState.consoleOpen;
23646
+ this._updatePreviewConsoleUI();
23647
+ }
23648
+
23649
+ _clearPreviewConsole() {
23650
+ this.previewState.consoleLogs = [];
23651
+ this._updatePreviewConsoleUI();
23652
+ }
23653
+
23654
+ _updatePreviewConsoleUI() {
23655
+ if (!this.container) return;
23656
+ const consoleDrawer = this.container.querySelector('#cl-preview-console');
23657
+ const consoleBody = this.container.querySelector('#cl-preview-console-body');
23658
+ const consolePill = this.container.querySelector('#cl-preview-console-pill');
23659
+ const consoleBtn = this.container.querySelector('[data-cl-action="preview-console-toggle"]');
23660
+ const logs = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs : [];
23661
+ if (consolePill) {
23662
+ consolePill.textContent = String(logs.length);
23663
+ }
23664
+ if (consoleBtn) {
23665
+ consoleBtn.classList.toggle('active', Boolean(this.previewState.consoleOpen));
23666
+ }
23667
+ if (consoleDrawer) {
23668
+ consoleDrawer.style.display = this.previewState.consoleOpen ? 'flex' : 'none';
23669
+ }
23670
+ if (consoleBody) {
23671
+ if (logs.length === 0) {
23672
+ consoleBody.innerHTML = `<div class="codelab-preview-console__empty">No console output from preview frame yet.</div>`;
23673
+ } else {
23674
+ consoleBody.innerHTML = logs.map((entry) => `
23675
+ <div class="codelab-preview-console__row codelab-preview-console__row--${escapeHtml(entry.level || 'log')}">
23676
+ <span class="codelab-preview-console__time">${escapeHtml(entry.timestamp || '')}</span>
23677
+ <span class="codelab-preview-console__text">${escapeHtml(entry.text || '')}</span>
23678
+ </div>
23679
+ `).join('');
23680
+ consoleBody.scrollTop = consoleBody.scrollHeight;
23681
+ }
23682
+ }
23151
23683
  }
23152
23684
 
23153
23685
  _renderWebPreviewControls() {
@@ -23159,6 +23691,7 @@ declare module 'bun:sqlite' {
23159
23691
  if (backBtn) backBtn.disabled = this.previewHistoryIdx <= 0;
23160
23692
  const fwdBtn = this.container.querySelector('[data-cl-action="preview-forward"]');
23161
23693
  if (fwdBtn) fwdBtn.disabled = this.previewHistoryIdx >= this.previewHistory.length - 1;
23694
+ this._updatePreviewConsoleUI();
23162
23695
  }
23163
23696
 
23164
23697
  _popoutPreview() {
@@ -23179,8 +23712,35 @@ declare module 'bun:sqlite' {
23179
23712
  _renderWebPreview(bodyEl) {
23180
23713
  if (!bodyEl) return;
23181
23714
  this._warnPreviewIsolation();
23182
- const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
23183
- if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
23715
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23716
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23717
+ const ws = this.container ? this.container.querySelector('.codelab-workspace') : null;
23718
+
23719
+ let targetHost = bodyEl;
23720
+ if (this.previewState.dockMode === 'split' && splitHost) {
23721
+ if (ws) ws.classList.add('has-preview-split');
23722
+ if (splitBar) splitBar.style.display = 'block';
23723
+ splitHost.style.display = 'flex';
23724
+ if (bodyEl !== splitHost) {
23725
+ bodyEl.innerHTML = `
23726
+ <div class="codelab-preview-split-notice">
23727
+ <span>Web Preview is docked to the right split pane.</span>
23728
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-dock-toggle">Dock to Bottom Drawer</button>
23729
+ </div>
23730
+ `;
23731
+ }
23732
+ targetHost = splitHost;
23733
+ } else {
23734
+ if (ws) ws.classList.remove('has-preview-split');
23735
+ if (splitBar) splitBar.style.display = 'none';
23736
+ if (splitHost && bodyEl !== splitHost) {
23737
+ splitHost.style.display = 'none';
23738
+ splitHost.innerHTML = '';
23739
+ }
23740
+ }
23741
+
23742
+ const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this.previewState.dockMode}|${this._previewSwReady}`;
23743
+ if (targetHost.querySelector && targetHost.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
23184
23744
  this._renderWebPreviewControls();
23185
23745
  return;
23186
23746
  }
@@ -23211,8 +23771,11 @@ declare module 'bun:sqlite' {
23211
23771
  ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
23212
23772
  : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
23213
23773
 
23214
- bodyEl.innerHTML = `
23215
- <div class="codelab-preview">
23774
+ const logsCount = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs.length : 0;
23775
+ const isSplit = this.previewState.dockMode === 'split';
23776
+
23777
+ targetHost.innerHTML = `
23778
+ <div class="codelab-preview ${this.previewState.maximized ? 'is-maximized' : ''}">
23216
23779
  <div class="codelab-preview-chrome">
23217
23780
  <div class="codelab-preview-nav">
23218
23781
  <button type="button" class="codelab-preview-btn" data-cl-action="preview-back" title="Back" ${this.previewHistoryIdx <= 0 ? 'disabled' : ''}>${CL_ICONS.arrowLeft || '←'}</button>
@@ -23228,11 +23791,30 @@ declare module 'bun:sqlite' {
23228
23791
  </div>
23229
23792
  <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
23230
23793
  <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
23794
+ <button type="button" class="codelab-preview-btn ${this.previewState.consoleOpen ? 'active' : ''}" data-cl-action="preview-console-toggle" title="Toggle Preview Console">
23795
+ ${CL_ICONS.terminal || '>_'} <span class="codelab-preview-console-pill" id="cl-preview-console-pill">${logsCount}</span>
23796
+ </button>
23797
+ <button type="button" class="codelab-preview-btn ${isSplit ? 'active' : ''}" data-cl-action="preview-dock-toggle" title="${isSplit ? 'Dock Preview to Bottom Drawer' : 'Dock Preview to Right Split Pane'}">
23798
+ ${CL_ICONS.layout || '◫'}
23799
+ </button>
23800
+ <button type="button" class="codelab-preview-btn ${this.previewState.maximized ? 'active' : ''}" data-cl-action="preview-maximize" title="Maximize / Restore Preview">
23801
+ ${CL_ICONS.maximize || '⛶'}
23802
+ </button>
23231
23803
  <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>
23232
23804
  </div>
23233
23805
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
23234
23806
  <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>
23235
23807
  </div>
23808
+ <div class="codelab-preview-console" id="cl-preview-console" style="display:${this.previewState.consoleOpen ? 'flex' : 'none'}">
23809
+ <div class="codelab-preview-console__bar">
23810
+ <span>Preview Console</span>
23811
+ <div style="display:flex;align-items:center;gap:6px;">
23812
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-clear">Clear</button>
23813
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-toggle">Close</button>
23814
+ </div>
23815
+ </div>
23816
+ <div class="codelab-preview-console__body" id="cl-preview-console-body"></div>
23817
+ </div>
23236
23818
  ${servers.length
23237
23819
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
23238
23820
  : `<div class="codelab-preview-empty">
@@ -23245,6 +23827,7 @@ declare module 'bun:sqlite' {
23245
23827
  </div>
23246
23828
  `;
23247
23829
  this._updatePreviewCspStatus();
23830
+ this._updatePreviewConsoleUI();
23248
23831
  this._loadPreviewFrame();
23249
23832
  }
23250
23833
 
@@ -23261,11 +23844,12 @@ declare module 'bun:sqlite' {
23261
23844
  this.previewState.error = 'No port selected';
23262
23845
  return Promise.resolve();
23263
23846
  }
23847
+ this._syncFilesToShellVfs();
23264
23848
  const fullUrl = this._previewUrl();
23265
23849
  this.previewState.loading = true;
23266
23850
  this.previewState.error = null;
23267
23851
 
23268
- if (this._previewSwReady) {
23852
+ if (this.options && this.options.useServiceWorkerForIframe === true && this._previewSwReady) {
23269
23853
  try {
23270
23854
  const u = new URL(fullUrl);
23271
23855
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
@@ -23277,8 +23861,8 @@ declare module 'bun:sqlite' {
23277
23861
  }
23278
23862
  }
23279
23863
 
23280
- // Fallback (no Service Worker): dispatch via the virtual port table and
23281
- // inline the response with an injected <base> for relative asset URLs.
23864
+ // Direct virtual dispatch + srcdoc injection guarantees zero Service Worker
23865
+ // race conditions and 100% deterministic loading inside sandboxed iframes.
23282
23866
  return this._dispatchPreviewRequest({ port, url: fullUrl, method: 'GET' })
23283
23867
  .then((res) => {
23284
23868
  let body = res.body || '';
@@ -23664,7 +24248,7 @@ declare module 'bun:sqlite' {
23664
24248
  this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
23665
24249
  }
23666
24250
  }
23667
- if (this.drawerTab === 'preview' && this.previewState && this.previewState.port) {
24251
+ if ((this.drawerTab === 'preview' || (this.previewState && this.previewState.dockMode === 'split')) && this.previewState && this.previewState.port) {
23668
24252
  if (this._previewReloadTimer) {
23669
24253
  clearTimeout(this._previewReloadTimer);
23670
24254
  }
@@ -23840,6 +24424,16 @@ declare module 'bun:sqlite' {
23840
24424
  };
23841
24425
  if (typeof document !== 'undefined') {
23842
24426
  document.addEventListener('keydown', this._escHandler);
24427
+ this._beforeUnloadHandler = () => {
24428
+ if (document.visibilityState === 'hidden') {
24429
+ try {
24430
+ this._saveState();
24431
+ } catch (err) {
24432
+ void err;
24433
+ }
24434
+ }
24435
+ };
24436
+ document.addEventListener('visibilitychange', this._beforeUnloadHandler);
23843
24437
  }
23844
24438
 
23845
24439
  this.container.addEventListener('keydown', e => {
@@ -24286,15 +24880,29 @@ declare module 'bun:sqlite' {
24286
24880
  this._previewSetFrameMode(actionBtn.dataset.mode);
24287
24881
  } else if (action === 'preview-popout') {
24288
24882
  this._popoutPreview();
24883
+ } else if (action === 'preview-dock-toggle') {
24884
+ this._togglePreviewDock();
24885
+ } else if (action === 'preview-maximize') {
24886
+ this._togglePreviewMaximize();
24887
+ } else if (action === 'preview-console-toggle') {
24888
+ this._togglePreviewConsole();
24889
+ } else if (action === 'preview-console-clear') {
24890
+ this._clearPreviewConsole();
24289
24891
  } else if (action === 'open-port-client') {
24290
- const port = actionBtn.dataset.port;
24892
+ const port = actionBtn.dataset.port || actionBtn.dataset.clPort;
24291
24893
  if (port) {
24292
24894
  this.httpClientUrl = `http://localhost:${port}/`;
24895
+ if (this.httpClientState) {
24896
+ this.httpClientState.url = `http://localhost:${port}/`;
24897
+ }
24293
24898
  this._renderDrawerBody();
24294
24899
  }
24295
24900
  } else if (action === 'stop-port') {
24296
- const port = Number(actionBtn.dataset.port);
24901
+ const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
24297
24902
  if (port) {
24903
+ if (this.portTable && typeof this.portTable.closeServer === 'function') {
24904
+ this.portTable.closeServer(port);
24905
+ }
24298
24906
  if (this.shell && this.shell.portTable && typeof this.shell.portTable.unregister === 'function') {
24299
24907
  this.shell.portTable.unregister(port);
24300
24908
  }
@@ -24304,18 +24912,32 @@ declare module 'bun:sqlite' {
24304
24912
  } else if (action === 'http-send') {
24305
24913
  this._sendHttpClientRequest();
24306
24914
  } else if (action === 'http-tab') {
24307
- this.httpActiveTab = actionBtn.dataset.httpTab || 'headers';
24915
+ const nextTab = actionBtn.dataset.tab || actionBtn.dataset.clHttpTab || actionBtn.dataset.httpTab || 'preview';
24916
+ this.httpActiveTab = nextTab;
24917
+ if (this.httpClientState) {
24918
+ this.httpClientState.activeResponseTab = nextTab;
24919
+ }
24308
24920
  this._renderDrawerBody();
24309
24921
  } else if (action === 'clear-net-traces') {
24310
24922
  this.lastHttpTrace = [];
24311
24923
  this.selectedNetTraceIdx = null;
24924
+ if (this.networkFilter) {
24925
+ this.networkFilter.selectedTraceId = null;
24926
+ }
24312
24927
  this._renderDrawerBody();
24313
24928
  } else if (action === 'select-net-trace') {
24929
+ const traceId = actionBtn.dataset.traceId || actionBtn.dataset.clTraceId || null;
24314
24930
  const idx = Number(actionBtn.dataset.traceIdx);
24315
24931
  this.selectedNetTraceIdx = Number.isNaN(idx) ? null : idx;
24932
+ if (this.networkFilter) {
24933
+ this.networkFilter.selectedTraceId = traceId;
24934
+ }
24316
24935
  this._renderDrawerBody();
24317
24936
  } else if (action === 'close-net-detail') {
24318
24937
  this.selectedNetTraceIdx = null;
24938
+ if (this.networkFilter) {
24939
+ this.networkFilter.selectedTraceId = null;
24940
+ }
24319
24941
  this._renderDrawerBody();
24320
24942
  }
24321
24943
  return;
@@ -24815,6 +25437,46 @@ declare module 'bun:sqlite' {
24815
25437
  fSplitter.addEventListener('pointerup', onUp);
24816
25438
  });
24817
25439
  }
25440
+
25441
+ const pSplitter = this.container.querySelector('#cl-splitter-preview');
25442
+ if (pSplitter) {
25443
+ pSplitter.addEventListener('dblclick', () => {
25444
+ this.previewSplitWidth = 0;
25445
+ shell.style.removeProperty('--cl-preview-split-width');
25446
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25447
+ this._saveState();
25448
+ });
25449
+
25450
+ pSplitter.addEventListener('pointerdown', e => {
25451
+ e.preventDefault();
25452
+ pSplitter.classList.add('is-dragging');
25453
+ shell.classList.add('is-resizing');
25454
+ try { pSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
25455
+
25456
+ const onMove = ev => {
25457
+ const ws = this.container.querySelector('.codelab-workspace');
25458
+ const rect = (ws || shell).getBoundingClientRect();
25459
+ const minW = 240;
25460
+ const maxW = Math.max(minW, Math.floor(rect.width * 0.65));
25461
+ const nextW = Math.min(maxW, Math.max(minW, Math.round(rect.right - ev.clientX)));
25462
+ this.previewSplitWidth = nextW;
25463
+ shell.style.setProperty('--cl-preview-split-width', `${nextW}px`);
25464
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25465
+ };
25466
+
25467
+ const onUp = ev => {
25468
+ pSplitter.classList.remove('is-dragging');
25469
+ shell.classList.remove('is-resizing');
25470
+ try { pSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
25471
+ pSplitter.removeEventListener('pointermove', onMove);
25472
+ pSplitter.removeEventListener('pointerup', onUp);
25473
+ this._saveState();
25474
+ };
25475
+
25476
+ pSplitter.addEventListener('pointermove', onMove);
25477
+ pSplitter.addEventListener('pointerup', onUp);
25478
+ });
25479
+ }
24818
25480
  }
24819
25481
 
24820
25482
  selectStep(idx, shouldJump = true) {
@@ -25043,6 +25705,9 @@ declare module 'bun:sqlite' {
25043
25705
  if (this.savedState.customFiles) {
25044
25706
  delete this.savedState.customFiles[key];
25045
25707
  }
25708
+ if (this.savedState.hasSnapshot) {
25709
+ delete this.savedState.hasSnapshot[key];
25710
+ }
25046
25711
  this._saveState();
25047
25712
  this._syncAllModels();
25048
25713
  this._syncActiveFileToView();
@@ -26350,6 +27015,10 @@ declare module 'bun:sqlite' {
26350
27015
  if (this._escHandler && typeof document !== 'undefined') {
26351
27016
  document.removeEventListener('keydown', this._escHandler);
26352
27017
  }
27018
+ if (this._beforeUnloadHandler && typeof document !== 'undefined') {
27019
+ document.removeEventListener('visibilitychange', this._beforeUnloadHandler);
27020
+ }
27021
+ this._beforeUnloadHandler = null;
26353
27022
  if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
26354
27023
  window.removeEventListener('message', this._previewViolationHandler);
26355
27024
  }