@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.
@@ -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
@@ -146,7 +146,7 @@ var CodeLabCsp = (() => {
146
146
  const host = normalizeOrigin(options.hostOrigin);
147
147
  const self = host || "'self'";
148
148
  const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
149
- const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
149
+ const script = () => [self, "data:", "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
150
150
  const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
151
151
  const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
152
152
  return [
@@ -267,13 +267,22 @@ var CodeLabCsp = (() => {
267
267
  document.body.appendChild(existing);
268
268
  }
269
269
  existing.textContent = '';
270
+ var topBar = document.createElement('div');
271
+ 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);';
270
272
  var header = document.createElement('div');
271
- header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
273
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
272
274
  header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
275
+ var closeBtn = document.createElement('button');
276
+ closeBtn.type = 'button';
277
+ closeBtn.textContent = 'Dismiss \xD7';
278
+ 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;';
279
+ closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
280
+ topBar.appendChild(header);
281
+ topBar.appendChild(closeBtn);
273
282
  var pre = document.createElement('pre');
274
- pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
283
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
275
284
  pre.textContent = String(stack || msg || '');
276
- existing.appendChild(header);
285
+ existing.appendChild(topBar);
277
286
  existing.appendChild(pre);
278
287
  } catch (err) {
279
288
  void err;
@@ -314,6 +323,189 @@ var CodeLabCsp = (() => {
314
323
  void err;
315
324
  }
316
325
  });
326
+
327
+ // Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
328
+ var pendingFetches = new Map();
329
+ var fetchSeq = 0;
330
+ function parseLoopbackTarget(rawUrl) {
331
+ if (!rawUrl || typeof rawUrl !== 'string') return null;
332
+ var trimmed = rawUrl.trim();
333
+ if (!trimmed) return null;
334
+ var lower = trimmed.toLowerCase();
335
+ 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;
336
+ if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
337
+ try {
338
+ var u = new URL(trimmed);
339
+ if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
340
+ return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
341
+ }
342
+ if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
343
+ var rest = u.pathname.slice('/__preview/'.length);
344
+ var slashIdx = rest.indexOf('/');
345
+ var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
346
+ var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
347
+ var portNum = Number(portStr);
348
+ if (portNum > 0) {
349
+ return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
350
+ }
351
+ }
352
+ } catch (e) { void e; }
353
+ return null;
354
+ }
355
+ if (trimmed.indexOf('/__preview/') === 0) {
356
+ var restRel = trimmed.slice('/__preview/'.length);
357
+ var sIdx = restRel.indexOf('/');
358
+ var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
359
+ var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
360
+ var pNum = Number(pStr);
361
+ if (pNum > 0) {
362
+ return { port: pNum, path: sPath || '/' };
363
+ }
364
+ }
365
+ var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
366
+ var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
367
+ return { port: null, path: pathPart };
368
+ }
369
+
370
+ window.addEventListener('message', function (event) {
371
+ var data = event && event.data;
372
+ if (!data || typeof data !== 'object') return;
373
+ if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
374
+ var entry = pendingFetches.get(data.reqId);
375
+ if (!entry) return;
376
+ pendingFetches.delete(data.reqId);
377
+ entry.resolve(data);
378
+ }
379
+ });
380
+
381
+ if (typeof window.fetch === 'function') {
382
+ var origFetch = window.fetch.bind(window);
383
+ window.fetch = function (input, init) {
384
+ var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
385
+ var target = parseLoopbackTarget(urlStr);
386
+ // Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
387
+ var isOpaque = false;
388
+ try {
389
+ var lowerUrl = urlStr.toLowerCase();
390
+ var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
391
+ isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
392
+ } catch (e) { isOpaque = true; void e; }
393
+ if (!target || !isOpaque || window.parent === window) {
394
+ return origFetch(input, init);
395
+ }
396
+ return new Promise(function (resolve, reject) {
397
+ var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
398
+ var method = (init && init.method) || (input && input.method) || 'GET';
399
+ var headersObj = {};
400
+ try {
401
+ var rawH = (init && init.headers) || (input && input.headers);
402
+ if (rawH) {
403
+ if (typeof rawH.forEach === 'function') {
404
+ rawH.forEach(function (v, k) { headersObj[k] = v; });
405
+ } else if (Array.isArray(rawH)) {
406
+ rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
407
+ } else if (typeof rawH === 'object') {
408
+ Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
409
+ }
410
+ }
411
+ } catch (e) { void e; }
412
+ var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
413
+ var timer = setTimeout(function () {
414
+ if (pendingFetches.has(reqId)) {
415
+ pendingFetches.delete(reqId);
416
+ origFetch(input, init).then(resolve, reject);
417
+ }
418
+ }, 5000);
419
+ pendingFetches.set(reqId, {
420
+ resolve: function (payload) {
421
+ clearTimeout(timer);
422
+ if (payload && payload.error) {
423
+ reject(new TypeError(String(payload.error)));
424
+ return;
425
+ }
426
+ var status = Number(payload && payload.status) || 200;
427
+ var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
428
+ var body = payload && payload.body !== undefined ? String(payload.body) : '';
429
+ try {
430
+ resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
431
+ } catch (err) {
432
+ void err;
433
+ resolve({
434
+ ok: status >= 200 && status < 300,
435
+ status: status,
436
+ headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
437
+ text: function () { return Promise.resolve(body); },
438
+ json: function () { return Promise.resolve(JSON.parse(body)); }
439
+ });
440
+ }
441
+ }
442
+ });
443
+ try {
444
+ parent.postMessage({
445
+ type: 'codelab:preview-fetch',
446
+ reqId: reqId,
447
+ port: target.port,
448
+ path: target.path,
449
+ method: String(method).toUpperCase(),
450
+ headers: headersObj,
451
+ body: bodyStr
452
+ }, '*');
453
+ } catch (err) {
454
+ clearTimeout(timer);
455
+ pendingFetches.delete(reqId);
456
+ origFetch(input, init).then(resolve, reject);
457
+ }
458
+ });
459
+ };
460
+ }
461
+
462
+ // Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
463
+ document.addEventListener('click', function (event) {
464
+ if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
465
+ var el = event.target;
466
+ while (el && el.tagName !== 'A') el = el.parentElement;
467
+ if (!el || !el.getAttribute) return;
468
+ var href = el.getAttribute('href');
469
+ var targetAttr = el.getAttribute('target');
470
+ if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
471
+ var lowerHref = href.toLowerCase();
472
+ 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;
473
+ var parsed = parseLoopbackTarget(href);
474
+ if (!parsed) return;
475
+ event.preventDefault();
476
+ try {
477
+ parent.postMessage({
478
+ type: 'codelab:preview-navigate',
479
+ port: parsed.port,
480
+ path: parsed.path
481
+ }, '*');
482
+ } catch (e) { void e; }
483
+ });
484
+
485
+ // Sync SPA history.pushState / replaceState with the preview omni-address bar
486
+ try {
487
+ ['pushState', 'replaceState'].forEach(function (method) {
488
+ var orig = history[method];
489
+ if (typeof orig !== 'function') return;
490
+ history[method] = function (state, title, url) {
491
+ var ret;
492
+ try { ret = orig.apply(history, arguments); } catch (e) { void e; }
493
+ if (url !== undefined && url !== null) {
494
+ var parsed = parseLoopbackTarget(String(url));
495
+ if (parsed) {
496
+ try {
497
+ parent.postMessage({
498
+ type: 'codelab:preview-url-change',
499
+ path: parsed.path,
500
+ replace: method === 'replaceState'
501
+ }, '*');
502
+ } catch (e) { void e; }
503
+ }
504
+ }
505
+ return ret;
506
+ };
507
+ });
508
+ } catch (e) { void e; }
317
509
  })();
318
510
  <\/script>`;
319
511
  }
@@ -12989,10 +13181,40 @@ if (typeof module !== 'undefined' && module.exports) {
12989
13181
  return imports;
12990
13182
  }
12991
13183
 
12992
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
12993
- const scripts = [];
13184
+ // Some templates pin a CDN URL in the source instead of importing a bare
13185
+ // specifier, e.g. `import React from "https://cdn.jsdelivr.net/npm/react@19.3.1/+esm"`.
13186
+ // Those URL specifiers are resolved by the browser directly, so they bypass the
13187
+ // generated import map (and with it the project's declared version and the
13188
+ // multi-CDN fallback). Import maps can remap URL specifiers, so alias each
13189
+ // literal URL found in the project to the resolved bare-specifier URL.
13190
+ // The pinned version is kept when the project has no dependency to resolve.
13191
+ const PINNED_CDN_URL_RE = /https?:\/\/(?:cdn\.jsdelivr\.net\/npm|esm\.sh)\/((?:@[^\/'"`@\s]+\/)?[^\/'"`@\s]+)@([^\s'"`),;]+)/g;
13192
+
13193
+ function aliasPinnedCdnUrls(vfs, rootDir, text, importMap) {
13194
+ if (!text || typeof text !== 'string') return;
13195
+ const re = new RegExp(PINNED_CDN_URL_RE.source, 'g');
13196
+ let match;
13197
+ while ((match = re.exec(text)) !== null) {
13198
+ const url = match[0];
13199
+ const pkgName = decodeURIComponent(match[1]);
13200
+ const rest = match[2];
13201
+ const pinnedVersion = rest.split(/[\/?]/)[0];
13202
+ const tail = rest.slice(pinnedVersion.length);
13203
+ const rawSubpath = tail.startsWith('/') && tail !== '/+esm' ? tail.slice(1).split(/[?#]/)[0] : '';
13204
+ const subpath = rawSubpath.replace(/^\/+|\/+$/g, '');
13205
+ const bare = subpath ? `${pkgName}/${subpath}` : pkgName;
13206
+
13207
+ const declared = resolveBareVersion(vfs, rootDir, pkgName);
13208
+ const version = declared && declared !== 'latest' ? declared : decodeURIComponent(pinnedVersion);
13209
+ const target = importMap[bare] || cdnEsmUrl(pkgName, version, subpath || undefined);
13210
+ if (target && target !== url) importMap[url] = target;
13211
+ }
13212
+ }
13213
+
13214
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
13215
+ const files = [];
12994
13216
  const walk = (dir, depth) => {
12995
- if (depth > 8 || scripts.length >= maxFiles) return;
13217
+ if (depth > 8 || files.length >= maxFiles) return;
12996
13218
  let entries = [];
12997
13219
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
12998
13220
  for (const name of entries) {
@@ -13003,13 +13225,23 @@ if (typeof module !== 'undefined' && module.exports) {
13003
13225
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
13004
13226
  if (dirFlag) {
13005
13227
  walk(full, depth + 1);
13006
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
13007
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
13228
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
13229
+ try {
13230
+ const content = vfs.readFileSync(full, 'utf8');
13231
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
13232
+ files.push({ full, rel, content });
13233
+ } catch (err) {
13234
+ _shellLogger.debug('Preview script read skipped.', full, err);
13235
+ }
13008
13236
  }
13009
13237
  }
13010
13238
  };
13011
13239
  walk(rootDir, 0);
13012
- return scripts;
13240
+ return files;
13241
+ }
13242
+
13243
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
13244
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
13013
13245
  }
13014
13246
 
13015
13247
  function injectPreviewExtras(html, importMap) {
@@ -13034,12 +13266,6 @@ if (typeof module !== 'undefined' && module.exports) {
13034
13266
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
13035
13267
  while (taken.has(port)) port++;
13036
13268
 
13037
- const specifiers = new Set();
13038
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
13039
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
13040
- }
13041
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
13042
-
13043
13269
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
13044
13270
  const isDir = (p) => {
13045
13271
  try {
@@ -13047,8 +13273,111 @@ if (typeof module !== 'undefined' && module.exports) {
13047
13273
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
13048
13274
  } catch (_) { return false; }
13049
13275
  };
13276
+ const isFile = (p) => exists(p) && !isDir(p);
13050
13277
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
13051
13278
 
13279
+ const resolveLocalTarget = (baseDir, rawSpec) => {
13280
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
13281
+ const clean = rawSpec.split(/[?#]/)[0].trim();
13282
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
13283
+ const candidateBase = clean.startsWith('/')
13284
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
13285
+ : PosixPath.join(baseDir, clean);
13286
+ if (isFile(candidateBase)) return candidateBase;
13287
+ const cands = [
13288
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
13289
+ candidateBase + '.mjs', candidateBase + '.cjs',
13290
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
13291
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
13292
+ ];
13293
+ for (const c of cands) {
13294
+ if (isFile(c)) return c;
13295
+ }
13296
+ return null;
13297
+ };
13298
+
13299
+ const toLocalImportKey = (fullPath) => {
13300
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
13301
+ return `@codelab-local/${rel}`;
13302
+ };
13303
+
13304
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
13305
+ let out = code;
13306
+ try {
13307
+ const rm = getRuntimeModule();
13308
+ if (rm && typeof rm.transpileForBrowser === 'function') {
13309
+ out = rm.transpileForBrowser(out, sourcePath);
13310
+ }
13311
+ } catch (err) {
13312
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
13313
+ }
13314
+ const fromDir = PosixPath.dirname(sourcePath);
13315
+ const rewriteSpec = (spec) => {
13316
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
13317
+ const resolved = resolveLocalTarget(fromDir, spec);
13318
+ return resolved ? toLocalImportKey(resolved) : spec;
13319
+ };
13320
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13321
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
13322
+ return out;
13323
+ };
13324
+
13325
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
13326
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
13327
+ const specifiers = new Set();
13328
+ for (const f of scriptFiles) {
13329
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
13330
+ }
13331
+ // Also scan inline module scripts in HTML for bare specifiers
13332
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
13333
+ let inlineMatch;
13334
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
13335
+ if (inlineMatch[1]) {
13336
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
13337
+ }
13338
+ }
13339
+
13340
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
13341
+ for (const f of scriptFiles) aliasPinnedCdnUrls(ctx.vfs, rootDir, f.content, importMap);
13342
+ aliasPinnedCdnUrls(ctx.vfs, rootDir, htmlBody, importMap);
13343
+ for (const f of scriptFiles) {
13344
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
13345
+ const key = toLocalImportKey(f.full);
13346
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
13347
+ }
13348
+
13349
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
13350
+ let transformedHtml = htmlBody;
13351
+
13352
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
13353
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
13354
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
13355
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
13356
+ if (!hrefMatch) return fullTag;
13357
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
13358
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
13359
+ const cssContent = readText(cssTarget);
13360
+ if (cssContent === null) return fullTag;
13361
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
13362
+ });
13363
+
13364
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
13365
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
13366
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
13367
+ if (!srcMatch) return fullTag;
13368
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
13369
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
13370
+ const rawScript = readText(scriptTarget);
13371
+ if (rawScript === null) return fullTag;
13372
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
13373
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
13374
+ const typeAttr = isMod ? ' type="module"' : '';
13375
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
13376
+ });
13377
+
13378
+ return injectPreviewExtras(transformedHtml, importMap);
13379
+ };
13380
+
13052
13381
  const handler = async (request) => {
13053
13382
  let pathname = '/';
13054
13383
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
@@ -13083,7 +13412,7 @@ if (typeof module !== 'undefined' && module.exports) {
13083
13412
  let body = readText(target);
13084
13413
  if (body === null) body = '';
13085
13414
  if (/\.html?$/i.test(target)) {
13086
- body = injectPreviewExtras(body, importMap);
13415
+ body = buildHtmlPreviewResponse(body, target);
13087
13416
  } else if (isPreviewScriptPath(target)) {
13088
13417
  try {
13089
13418
  const rm = getRuntimeModule();
@@ -18449,7 +18778,7 @@ if (typeof module !== 'undefined' && module.exports) {
18449
18778
 
18450
18779
  // The bundler rewrites this literal from package.json at build time. Keeping
18451
18780
  // the fallback in sync lets tests require src/workbench.js directly.
18452
- const CODELAB_VERSION = '0.1.8';
18781
+ const CODELAB_VERSION = '0.1.10';
18453
18782
 
18454
18783
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
18455
18784
  const NODE_AMBIENT_DTS = `
@@ -19756,6 +20085,11 @@ declare module 'bun:sqlite' {
19756
20085
  this.explorerWidth = (typeof this.savedState?.explorerWidth === 'number' && this.savedState.explorerWidth >= 120)
19757
20086
  ? this.savedState.explorerWidth
19758
20087
  : 196;
20088
+ // 0 = use the default 44% track; otherwise a pixel width chosen by dragging
20089
+ // the preview splitter.
20090
+ this.previewSplitWidth = (typeof this.savedState?.previewSplitWidth === 'number' && this.savedState.previewSplitWidth >= 200)
20091
+ ? this.savedState.previewSplitWidth
20092
+ : 0;
19759
20093
  this.folderSwitcherOpen = false;
19760
20094
  this.creatingItem = null; // { type: 'file' | 'folder', parentFolder: string } | null
19761
20095
  this.renamingItem = null;
@@ -19768,6 +20102,10 @@ declare module 'bun:sqlite' {
19768
20102
  path: '/',
19769
20103
  url: '',
19770
20104
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
20105
+ dockMode: (options && options.previewDock === 'split') ? 'split' : 'bottom', // 'bottom' | 'split'
20106
+ maximized: false,
20107
+ consoleOpen: false,
20108
+ consoleLogs: [],
19771
20109
  loading: false,
19772
20110
  error: null,
19773
20111
  srcdoc: '',
@@ -19779,6 +20117,7 @@ declare module 'bun:sqlite' {
19779
20117
  this._previewSwRegistration = null;
19780
20118
  this._previewViolationHandler = null;
19781
20119
  this._swMessageHandler = null;
20120
+ this._beforeUnloadHandler = null;
19782
20121
  this._portToasts = new Map();
19783
20122
  this.isFullscreen = false;
19784
20123
  this.isRunning = false;
@@ -20125,6 +20464,11 @@ declare module 'bun:sqlite' {
20125
20464
  const key = `${this.mode}:${this.lang}`;
20126
20465
  const customFiles = (this.savedState && this.savedState.customFiles) || {};
20127
20466
  customFiles[key] = { ...this.files };
20467
+ const hasSnapshot = Object.assign(
20468
+ {},
20469
+ (this.savedState && this.savedState.hasSnapshot) || {},
20470
+ { [key]: true }
20471
+ );
20128
20472
  const completedArr = Array.from(this.completedSteps);
20129
20473
  const state = {
20130
20474
  mode: this.mode,
@@ -20132,12 +20476,14 @@ declare module 'bun:sqlite' {
20132
20476
  activeStepIndex: this.activeStepIndex,
20133
20477
  completedSteps: completedArr,
20134
20478
  customFiles,
20479
+ hasSnapshot,
20135
20480
  openTabs: Array.isArray(this.openTabs) ? [...this.openTabs] : undefined,
20136
20481
  activeFile: this.activeFile,
20137
20482
  folders: Array.from(this.folders || []),
20138
20483
  collapsedFolders: Array.from(this.collapsedFolders || []),
20139
20484
  explorerFolder: this.explorerFolder || '',
20140
- explorerWidth: typeof this.explorerWidth === 'number' ? this.explorerWidth : undefined
20485
+ explorerWidth: typeof this.explorerWidth === 'number' ? this.explorerWidth : undefined,
20486
+ previewSplitWidth: this.previewSplitWidth || undefined
20141
20487
  };
20142
20488
  this.savedState = state;
20143
20489
  if (this.options && this.options.persistState === false) {
@@ -20156,6 +20502,20 @@ declare module 'bun:sqlite' {
20156
20502
  safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
20157
20503
  safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
20158
20504
  ];
20505
+ if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
20506
+ try {
20507
+ if (!this._idbStorage) {
20508
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
20509
+ }
20510
+ if (this._idbStorage && typeof this._idbStorage.save === 'function') {
20511
+ Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
20512
+ this.logger.debug('Async WorkspaceStorage save skipped.', err);
20513
+ });
20514
+ }
20515
+ } catch (err) {
20516
+ this.logger.debug('WorkspaceStorage initialization skipped.', err);
20517
+ }
20518
+ }
20159
20519
  if (persisted.includes(false)) {
20160
20520
  this._reportPersistenceFailure(safeStorageSet._lastError);
20161
20521
  } else {
@@ -20308,6 +20668,9 @@ declare module 'bun:sqlite' {
20308
20668
  const key = `${this.mode}:${this.lang}`;
20309
20669
  const saved = this.savedState.customFiles?.[key];
20310
20670
  const base = this._getBaseFilesForModeAndLang(this.mode, this.lang);
20671
+ if (this.savedState && this.savedState.hasSnapshot && this.savedState.hasSnapshot[key] && saved && typeof saved === 'object') {
20672
+ return { ...saved };
20673
+ }
20311
20674
  if (saved && Object.keys(saved).length > 0) {
20312
20675
  return { ...base, ...saved };
20313
20676
  }
@@ -20382,7 +20745,9 @@ declare module 'bun:sqlite' {
20382
20745
  const themeAttr = this.themeOption !== 'auto' ? `data-theme="${escapeHtml(this.themeOption)}"` : '';
20383
20746
  const brandLabel = (this.title && this.title !== 'custom-lab' && this.title !== this.labId) ? this.title : 'code-lab';
20384
20747
  const isGuideCollapsed = !this.hasGuidedLab || this.mode === 'sandbox' || !this.steps.length;
20385
- const explorerStyle = `style="--cl-explorer-width:${Math.round(this.explorerWidth || 196)}px"`;
20748
+ const shellVars = [`--cl-explorer-width:${Math.round(this.explorerWidth || 196)}px`];
20749
+ if (this.previewSplitWidth) shellVars.push(`--cl-preview-split-width:${Math.round(this.previewSplitWidth)}px`);
20750
+ const explorerStyle = `style="${shellVars.join(';')}"`;
20386
20751
  this.container.innerHTML = `
20387
20752
  <div class="codelab codelab-workbench ${isGuideCollapsed ? 'guide-collapsed' : ''}" id="codelab-${escapeHtml(this.labId)}" ${themeAttr} ${explorerStyle}>
20388
20753
  <!-- Top Bar -->
@@ -20520,6 +20885,10 @@ declare module 'bun:sqlite' {
20520
20885
  <div class="codelab-empty-editor" id="cl-empty-editor" style="display:none"></div>
20521
20886
  </div>
20522
20887
  </div>
20888
+
20889
+ <!-- Right-Hand Split Web Preview Pane -->
20890
+ <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>
20891
+ <div class="codelab-preview-split" id="cl-preview-split" aria-label="In-Browser Web Preview" style="display:none"></div>
20523
20892
  </div>
20524
20893
 
20525
20894
  <!-- Interactive Horizontal Splitter -->
@@ -21773,6 +22142,7 @@ declare module 'bun:sqlite' {
21773
22142
  }
21774
22143
 
21775
22144
  if (this.drawerTab === 'preview') {
22145
+ bodyEl.scrollTop = 0;
21776
22146
  this._renderWebPreview(bodyEl);
21777
22147
  return;
21778
22148
  }
@@ -22901,6 +23271,10 @@ declare module 'bun:sqlite' {
22901
23271
  type: level === 'error' ? 'stderr' : 'stdout',
22902
23272
  text: `[Preview ${level.toUpperCase()}] ${text}`
22903
23273
  });
23274
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23275
+ this.previewState.consoleLogs.push({ level, text, timestamp: new Date().toLocaleTimeString() });
23276
+ if (this.previewState.consoleLogs.length > 200) this.previewState.consoleLogs.shift();
23277
+ this._updatePreviewConsoleUI();
22904
23278
  this._emitEvent('preview-console', { level, text, args });
22905
23279
  } else if (data.type === 'codelab:preview-error') {
22906
23280
  const msg = String(data.message || 'Uncaught runtime error');
@@ -22915,9 +23289,66 @@ declare module 'bun:sqlite' {
22915
23289
  type: 'stderr',
22916
23290
  text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
22917
23291
  });
23292
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
23293
+ this.previewState.consoleLogs.push({
23294
+ level: 'error',
23295
+ text: `${msg}${data.stack ? '\n' + String(data.stack) : ''}`,
23296
+ timestamp: new Date().toLocaleTimeString()
23297
+ });
23298
+ this._updatePreviewConsoleUI();
22918
23299
  this._emitEvent('preview-error', this.previewState.runtimeError);
22919
23300
  } else if (data.type === 'codelab:preview-error-clear') {
22920
23301
  this.previewState.runtimeError = null;
23302
+ } else if (data.type === 'codelab:preview-fetch') {
23303
+ const reqId = data.reqId || data.id;
23304
+ const targetPort = Number(data.port) || this.previewState.port || this._firstListeningPort() || 3000;
23305
+ const reqPath = data.path ? (String(data.path).startsWith('/') ? String(data.path) : '/' + String(data.path)) : '/';
23306
+ const targetUrl = String(data.url || `http://127.0.0.1:${targetPort}${reqPath}`);
23307
+ this._dispatchPreviewRequest({
23308
+ port: targetPort,
23309
+ url: targetUrl,
23310
+ method: data.method || 'GET',
23311
+ headers: data.headers || {},
23312
+ body: data.body !== undefined ? data.body : null
23313
+ })
23314
+ .then((res) => {
23315
+ const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
23316
+ if (netPill) netPill.textContent = `${(this.lastHttpTrace || []).length} reqs`;
23317
+ if (this.drawerTab === 'network') this._renderDrawerBody();
23318
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23319
+ iframe.contentWindow.postMessage({
23320
+ type: 'codelab:preview-fetch-res',
23321
+ reqId,
23322
+ id: reqId,
23323
+ status: res.status || 200,
23324
+ statusText: res.statusText || 'OK',
23325
+ headers: res.headers || {},
23326
+ body: res.body || ''
23327
+ }, '*');
23328
+ }
23329
+ })
23330
+ .catch((err) => {
23331
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
23332
+ iframe.contentWindow.postMessage({
23333
+ type: 'codelab:preview-fetch-res',
23334
+ reqId,
23335
+ id: reqId,
23336
+ error: String((err && err.message) || err)
23337
+ }, '*');
23338
+ }
23339
+ });
23340
+ } else if (data.type === 'codelab:preview-navigate') {
23341
+ const navHref = data.href || (data.path ? (data.port ? `http://127.0.0.1:${data.port}${data.path}` : String(data.path)) : '');
23342
+ if (navHref) {
23343
+ this._previewGo(String(navHref));
23344
+ }
23345
+ } else if (data.type === 'codelab:preview-url-change') {
23346
+ if (data.path && typeof data.path === 'string') {
23347
+ this.previewState.path = data.path.startsWith('/') ? data.path : '/' + data.path;
23348
+ this.previewState.url = this._previewUrl();
23349
+ const input = this.container ? this.container.querySelector('#cl-preview-url-input') : null;
23350
+ if (input) input.value = this.previewState.url;
23351
+ }
22921
23352
  }
22922
23353
  };
22923
23354
  window.addEventListener('message', this._previewViolationHandler);
@@ -22981,7 +23412,12 @@ declare module 'bun:sqlite' {
22981
23412
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
22982
23413
  this.previewHistory.push(this.previewState.url);
22983
23414
  this.previewHistoryIdx = this.previewHistory.length - 1;
22984
- this.switchDrawerTab('preview');
23415
+ if (this.previewState.dockMode === 'split') {
23416
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23417
+ if (splitHost) this._renderWebPreview(splitHost);
23418
+ } else {
23419
+ this.switchDrawerTab('preview');
23420
+ }
22985
23421
  return this._previewLoadPromise || Promise.resolve();
22986
23422
  }
22987
23423
 
@@ -23100,7 +23536,12 @@ declare module 'bun:sqlite' {
23100
23536
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
23101
23537
  this.previewHistory.push(url);
23102
23538
  this.previewHistoryIdx = this.previewHistory.length - 1;
23103
- this.switchDrawerTab('preview');
23539
+ if (this.previewState.dockMode === 'split') {
23540
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23541
+ if (splitHost) this._renderWebPreview(splitHost);
23542
+ } else {
23543
+ this.switchDrawerTab('preview');
23544
+ }
23104
23545
  return this._previewLoadPromise || Promise.resolve();
23105
23546
  }
23106
23547
 
@@ -23141,6 +23582,97 @@ declare module 'bun:sqlite' {
23141
23582
  if (!['desktop', 'tablet', 'mobile'].includes(mode)) return;
23142
23583
  this.previewState.frameMode = mode;
23143
23584
  this._renderDrawerBody();
23585
+ if (this.previewState.dockMode === 'split') {
23586
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23587
+ if (splitHost) this._renderWebPreview(splitHost);
23588
+ }
23589
+ }
23590
+
23591
+ _togglePreviewDock() {
23592
+ this.previewState.dockMode = this.previewState.dockMode === 'split' ? 'bottom' : 'split';
23593
+ this._previewRenderKey = null;
23594
+ const ws = this.container ? this.container.querySelector('.codelab-workspace') : null;
23595
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23596
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23597
+ if (this.previewState.dockMode === 'split') {
23598
+ if (ws) ws.classList.add('has-preview-split');
23599
+ if (splitBar) splitBar.style.display = 'block';
23600
+ if (splitHost) {
23601
+ splitHost.style.display = 'flex';
23602
+ this._renderWebPreview(splitHost);
23603
+ }
23604
+ if (this.drawerTab === 'preview') {
23605
+ this.switchDrawerTab('terminal');
23606
+ } else {
23607
+ this._renderDrawerBody();
23608
+ }
23609
+ } else {
23610
+ if (ws) ws.classList.remove('has-preview-split');
23611
+ if (splitBar) splitBar.style.display = 'none';
23612
+ if (splitHost) {
23613
+ splitHost.style.display = 'none';
23614
+ splitHost.innerHTML = '';
23615
+ }
23616
+ this.switchDrawerTab('preview');
23617
+ }
23618
+ if (this.editor && typeof this.editor.layout === 'function') {
23619
+ setTimeout(() => {
23620
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
23621
+ }, 30);
23622
+ }
23623
+ }
23624
+
23625
+ _togglePreviewMaximize() {
23626
+ this.previewState.maximized = !this.previewState.maximized;
23627
+ const previewEl = this.container ? this.container.querySelector('.codelab-preview') : null;
23628
+ if (previewEl) {
23629
+ previewEl.classList.toggle('is-maximized', Boolean(this.previewState.maximized));
23630
+ }
23631
+ const maxBtn = this.container ? this.container.querySelector('[data-cl-action="preview-maximize"]') : null;
23632
+ if (maxBtn) {
23633
+ maxBtn.classList.toggle('active', Boolean(this.previewState.maximized));
23634
+ }
23635
+ }
23636
+
23637
+ _togglePreviewConsole() {
23638
+ this.previewState.consoleOpen = !this.previewState.consoleOpen;
23639
+ this._updatePreviewConsoleUI();
23640
+ }
23641
+
23642
+ _clearPreviewConsole() {
23643
+ this.previewState.consoleLogs = [];
23644
+ this._updatePreviewConsoleUI();
23645
+ }
23646
+
23647
+ _updatePreviewConsoleUI() {
23648
+ if (!this.container) return;
23649
+ const consoleDrawer = this.container.querySelector('#cl-preview-console');
23650
+ const consoleBody = this.container.querySelector('#cl-preview-console-body');
23651
+ const consolePill = this.container.querySelector('#cl-preview-console-pill');
23652
+ const consoleBtn = this.container.querySelector('[data-cl-action="preview-console-toggle"]');
23653
+ const logs = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs : [];
23654
+ if (consolePill) {
23655
+ consolePill.textContent = String(logs.length);
23656
+ }
23657
+ if (consoleBtn) {
23658
+ consoleBtn.classList.toggle('active', Boolean(this.previewState.consoleOpen));
23659
+ }
23660
+ if (consoleDrawer) {
23661
+ consoleDrawer.style.display = this.previewState.consoleOpen ? 'flex' : 'none';
23662
+ }
23663
+ if (consoleBody) {
23664
+ if (logs.length === 0) {
23665
+ consoleBody.innerHTML = `<div class="codelab-preview-console__empty">No console output from preview frame yet.</div>`;
23666
+ } else {
23667
+ consoleBody.innerHTML = logs.map((entry) => `
23668
+ <div class="codelab-preview-console__row codelab-preview-console__row--${escapeHtml(entry.level || 'log')}">
23669
+ <span class="codelab-preview-console__time">${escapeHtml(entry.timestamp || '')}</span>
23670
+ <span class="codelab-preview-console__text">${escapeHtml(entry.text || '')}</span>
23671
+ </div>
23672
+ `).join('');
23673
+ consoleBody.scrollTop = consoleBody.scrollHeight;
23674
+ }
23675
+ }
23144
23676
  }
23145
23677
 
23146
23678
  _renderWebPreviewControls() {
@@ -23152,6 +23684,7 @@ declare module 'bun:sqlite' {
23152
23684
  if (backBtn) backBtn.disabled = this.previewHistoryIdx <= 0;
23153
23685
  const fwdBtn = this.container.querySelector('[data-cl-action="preview-forward"]');
23154
23686
  if (fwdBtn) fwdBtn.disabled = this.previewHistoryIdx >= this.previewHistory.length - 1;
23687
+ this._updatePreviewConsoleUI();
23155
23688
  }
23156
23689
 
23157
23690
  _popoutPreview() {
@@ -23172,8 +23705,35 @@ declare module 'bun:sqlite' {
23172
23705
  _renderWebPreview(bodyEl) {
23173
23706
  if (!bodyEl) return;
23174
23707
  this._warnPreviewIsolation();
23175
- const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
23176
- if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
23708
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
23709
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
23710
+ const ws = this.container ? this.container.querySelector('.codelab-workspace') : null;
23711
+
23712
+ let targetHost = bodyEl;
23713
+ if (this.previewState.dockMode === 'split' && splitHost) {
23714
+ if (ws) ws.classList.add('has-preview-split');
23715
+ if (splitBar) splitBar.style.display = 'block';
23716
+ splitHost.style.display = 'flex';
23717
+ if (bodyEl !== splitHost) {
23718
+ bodyEl.innerHTML = `
23719
+ <div class="codelab-preview-split-notice">
23720
+ <span>Web Preview is docked to the right split pane.</span>
23721
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-dock-toggle">Dock to Bottom Drawer</button>
23722
+ </div>
23723
+ `;
23724
+ }
23725
+ targetHost = splitHost;
23726
+ } else {
23727
+ if (ws) ws.classList.remove('has-preview-split');
23728
+ if (splitBar) splitBar.style.display = 'none';
23729
+ if (splitHost && bodyEl !== splitHost) {
23730
+ splitHost.style.display = 'none';
23731
+ splitHost.innerHTML = '';
23732
+ }
23733
+ }
23734
+
23735
+ const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this.previewState.dockMode}|${this._previewSwReady}`;
23736
+ if (targetHost.querySelector && targetHost.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
23177
23737
  this._renderWebPreviewControls();
23178
23738
  return;
23179
23739
  }
@@ -23204,8 +23764,11 @@ declare module 'bun:sqlite' {
23204
23764
  ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
23205
23765
  : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
23206
23766
 
23207
- bodyEl.innerHTML = `
23208
- <div class="codelab-preview">
23767
+ const logsCount = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs.length : 0;
23768
+ const isSplit = this.previewState.dockMode === 'split';
23769
+
23770
+ targetHost.innerHTML = `
23771
+ <div class="codelab-preview ${this.previewState.maximized ? 'is-maximized' : ''}">
23209
23772
  <div class="codelab-preview-chrome">
23210
23773
  <div class="codelab-preview-nav">
23211
23774
  <button type="button" class="codelab-preview-btn" data-cl-action="preview-back" title="Back" ${this.previewHistoryIdx <= 0 ? 'disabled' : ''}>${CL_ICONS.arrowLeft || '←'}</button>
@@ -23221,11 +23784,30 @@ declare module 'bun:sqlite' {
23221
23784
  </div>
23222
23785
  <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
23223
23786
  <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
23787
+ <button type="button" class="codelab-preview-btn ${this.previewState.consoleOpen ? 'active' : ''}" data-cl-action="preview-console-toggle" title="Toggle Preview Console">
23788
+ ${CL_ICONS.terminal || '>_'} <span class="codelab-preview-console-pill" id="cl-preview-console-pill">${logsCount}</span>
23789
+ </button>
23790
+ <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'}">
23791
+ ${CL_ICONS.layout || '◫'}
23792
+ </button>
23793
+ <button type="button" class="codelab-preview-btn ${this.previewState.maximized ? 'active' : ''}" data-cl-action="preview-maximize" title="Maximize / Restore Preview">
23794
+ ${CL_ICONS.maximize || '⛶'}
23795
+ </button>
23224
23796
  <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>
23225
23797
  </div>
23226
23798
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
23227
23799
  <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>
23228
23800
  </div>
23801
+ <div class="codelab-preview-console" id="cl-preview-console" style="display:${this.previewState.consoleOpen ? 'flex' : 'none'}">
23802
+ <div class="codelab-preview-console__bar">
23803
+ <span>Preview Console</span>
23804
+ <div style="display:flex;align-items:center;gap:6px;">
23805
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-clear">Clear</button>
23806
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-toggle">Close</button>
23807
+ </div>
23808
+ </div>
23809
+ <div class="codelab-preview-console__body" id="cl-preview-console-body"></div>
23810
+ </div>
23229
23811
  ${servers.length
23230
23812
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
23231
23813
  : `<div class="codelab-preview-empty">
@@ -23238,6 +23820,7 @@ declare module 'bun:sqlite' {
23238
23820
  </div>
23239
23821
  `;
23240
23822
  this._updatePreviewCspStatus();
23823
+ this._updatePreviewConsoleUI();
23241
23824
  this._loadPreviewFrame();
23242
23825
  }
23243
23826
 
@@ -23254,11 +23837,12 @@ declare module 'bun:sqlite' {
23254
23837
  this.previewState.error = 'No port selected';
23255
23838
  return Promise.resolve();
23256
23839
  }
23840
+ this._syncFilesToShellVfs();
23257
23841
  const fullUrl = this._previewUrl();
23258
23842
  this.previewState.loading = true;
23259
23843
  this.previewState.error = null;
23260
23844
 
23261
- if (this._previewSwReady) {
23845
+ if (this.options && this.options.useServiceWorkerForIframe === true && this._previewSwReady) {
23262
23846
  try {
23263
23847
  const u = new URL(fullUrl);
23264
23848
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
@@ -23270,8 +23854,8 @@ declare module 'bun:sqlite' {
23270
23854
  }
23271
23855
  }
23272
23856
 
23273
- // Fallback (no Service Worker): dispatch via the virtual port table and
23274
- // inline the response with an injected <base> for relative asset URLs.
23857
+ // Direct virtual dispatch + srcdoc injection guarantees zero Service Worker
23858
+ // race conditions and 100% deterministic loading inside sandboxed iframes.
23275
23859
  return this._dispatchPreviewRequest({ port, url: fullUrl, method: 'GET' })
23276
23860
  .then((res) => {
23277
23861
  let body = res.body || '';
@@ -23657,7 +24241,7 @@ declare module 'bun:sqlite' {
23657
24241
  this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
23658
24242
  }
23659
24243
  }
23660
- if (this.drawerTab === 'preview' && this.previewState && this.previewState.port) {
24244
+ if ((this.drawerTab === 'preview' || (this.previewState && this.previewState.dockMode === 'split')) && this.previewState && this.previewState.port) {
23661
24245
  if (this._previewReloadTimer) {
23662
24246
  clearTimeout(this._previewReloadTimer);
23663
24247
  }
@@ -23833,6 +24417,16 @@ declare module 'bun:sqlite' {
23833
24417
  };
23834
24418
  if (typeof document !== 'undefined') {
23835
24419
  document.addEventListener('keydown', this._escHandler);
24420
+ this._beforeUnloadHandler = () => {
24421
+ if (document.visibilityState === 'hidden') {
24422
+ try {
24423
+ this._saveState();
24424
+ } catch (err) {
24425
+ void err;
24426
+ }
24427
+ }
24428
+ };
24429
+ document.addEventListener('visibilitychange', this._beforeUnloadHandler);
23836
24430
  }
23837
24431
 
23838
24432
  this.container.addEventListener('keydown', e => {
@@ -24279,15 +24873,29 @@ declare module 'bun:sqlite' {
24279
24873
  this._previewSetFrameMode(actionBtn.dataset.mode);
24280
24874
  } else if (action === 'preview-popout') {
24281
24875
  this._popoutPreview();
24876
+ } else if (action === 'preview-dock-toggle') {
24877
+ this._togglePreviewDock();
24878
+ } else if (action === 'preview-maximize') {
24879
+ this._togglePreviewMaximize();
24880
+ } else if (action === 'preview-console-toggle') {
24881
+ this._togglePreviewConsole();
24882
+ } else if (action === 'preview-console-clear') {
24883
+ this._clearPreviewConsole();
24282
24884
  } else if (action === 'open-port-client') {
24283
- const port = actionBtn.dataset.port;
24885
+ const port = actionBtn.dataset.port || actionBtn.dataset.clPort;
24284
24886
  if (port) {
24285
24887
  this.httpClientUrl = `http://localhost:${port}/`;
24888
+ if (this.httpClientState) {
24889
+ this.httpClientState.url = `http://localhost:${port}/`;
24890
+ }
24286
24891
  this._renderDrawerBody();
24287
24892
  }
24288
24893
  } else if (action === 'stop-port') {
24289
- const port = Number(actionBtn.dataset.port);
24894
+ const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
24290
24895
  if (port) {
24896
+ if (this.portTable && typeof this.portTable.closeServer === 'function') {
24897
+ this.portTable.closeServer(port);
24898
+ }
24291
24899
  if (this.shell && this.shell.portTable && typeof this.shell.portTable.unregister === 'function') {
24292
24900
  this.shell.portTable.unregister(port);
24293
24901
  }
@@ -24297,18 +24905,32 @@ declare module 'bun:sqlite' {
24297
24905
  } else if (action === 'http-send') {
24298
24906
  this._sendHttpClientRequest();
24299
24907
  } else if (action === 'http-tab') {
24300
- this.httpActiveTab = actionBtn.dataset.httpTab || 'headers';
24908
+ const nextTab = actionBtn.dataset.tab || actionBtn.dataset.clHttpTab || actionBtn.dataset.httpTab || 'preview';
24909
+ this.httpActiveTab = nextTab;
24910
+ if (this.httpClientState) {
24911
+ this.httpClientState.activeResponseTab = nextTab;
24912
+ }
24301
24913
  this._renderDrawerBody();
24302
24914
  } else if (action === 'clear-net-traces') {
24303
24915
  this.lastHttpTrace = [];
24304
24916
  this.selectedNetTraceIdx = null;
24917
+ if (this.networkFilter) {
24918
+ this.networkFilter.selectedTraceId = null;
24919
+ }
24305
24920
  this._renderDrawerBody();
24306
24921
  } else if (action === 'select-net-trace') {
24922
+ const traceId = actionBtn.dataset.traceId || actionBtn.dataset.clTraceId || null;
24307
24923
  const idx = Number(actionBtn.dataset.traceIdx);
24308
24924
  this.selectedNetTraceIdx = Number.isNaN(idx) ? null : idx;
24925
+ if (this.networkFilter) {
24926
+ this.networkFilter.selectedTraceId = traceId;
24927
+ }
24309
24928
  this._renderDrawerBody();
24310
24929
  } else if (action === 'close-net-detail') {
24311
24930
  this.selectedNetTraceIdx = null;
24931
+ if (this.networkFilter) {
24932
+ this.networkFilter.selectedTraceId = null;
24933
+ }
24312
24934
  this._renderDrawerBody();
24313
24935
  }
24314
24936
  return;
@@ -24808,6 +25430,46 @@ declare module 'bun:sqlite' {
24808
25430
  fSplitter.addEventListener('pointerup', onUp);
24809
25431
  });
24810
25432
  }
25433
+
25434
+ const pSplitter = this.container.querySelector('#cl-splitter-preview');
25435
+ if (pSplitter) {
25436
+ pSplitter.addEventListener('dblclick', () => {
25437
+ this.previewSplitWidth = 0;
25438
+ shell.style.removeProperty('--cl-preview-split-width');
25439
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25440
+ this._saveState();
25441
+ });
25442
+
25443
+ pSplitter.addEventListener('pointerdown', e => {
25444
+ e.preventDefault();
25445
+ pSplitter.classList.add('is-dragging');
25446
+ shell.classList.add('is-resizing');
25447
+ try { pSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
25448
+
25449
+ const onMove = ev => {
25450
+ const ws = this.container.querySelector('.codelab-workspace');
25451
+ const rect = (ws || shell).getBoundingClientRect();
25452
+ const minW = 240;
25453
+ const maxW = Math.max(minW, Math.floor(rect.width * 0.65));
25454
+ const nextW = Math.min(maxW, Math.max(minW, Math.round(rect.right - ev.clientX)));
25455
+ this.previewSplitWidth = nextW;
25456
+ shell.style.setProperty('--cl-preview-split-width', `${nextW}px`);
25457
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
25458
+ };
25459
+
25460
+ const onUp = ev => {
25461
+ pSplitter.classList.remove('is-dragging');
25462
+ shell.classList.remove('is-resizing');
25463
+ try { pSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
25464
+ pSplitter.removeEventListener('pointermove', onMove);
25465
+ pSplitter.removeEventListener('pointerup', onUp);
25466
+ this._saveState();
25467
+ };
25468
+
25469
+ pSplitter.addEventListener('pointermove', onMove);
25470
+ pSplitter.addEventListener('pointerup', onUp);
25471
+ });
25472
+ }
24811
25473
  }
24812
25474
 
24813
25475
  selectStep(idx, shouldJump = true) {
@@ -25036,6 +25698,9 @@ declare module 'bun:sqlite' {
25036
25698
  if (this.savedState.customFiles) {
25037
25699
  delete this.savedState.customFiles[key];
25038
25700
  }
25701
+ if (this.savedState.hasSnapshot) {
25702
+ delete this.savedState.hasSnapshot[key];
25703
+ }
25039
25704
  this._saveState();
25040
25705
  this._syncAllModels();
25041
25706
  this._syncActiveFileToView();
@@ -26343,6 +27008,10 @@ declare module 'bun:sqlite' {
26343
27008
  if (this._escHandler && typeof document !== 'undefined') {
26344
27009
  document.removeEventListener('keydown', this._escHandler);
26345
27010
  }
27011
+ if (this._beforeUnloadHandler && typeof document !== 'undefined') {
27012
+ document.removeEventListener('visibilitychange', this._beforeUnloadHandler);
27013
+ }
27014
+ this._beforeUnloadHandler = null;
26346
27015
  if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
26347
27016
  window.removeEventListener('message', this._previewViolationHandler);
26348
27017
  }
@@ -26612,7 +27281,7 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
26612
27281
  const mount = CodeLab ? CodeLab.mount : null;
26613
27282
  const create = CodeLab ? CodeLab.create : null;
26614
27283
  const unmount = CodeLab ? CodeLab.unmount : null;
26615
- const version = CodeLab ? CodeLab.version : '0.1.8';
27284
+ const version = CodeLab ? CodeLab.version : '0.1.10';
26616
27285
  const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
26617
27286
  const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
26618
27287
  const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;