@innovatorved/code-lab 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/csp.ts CHANGED
@@ -334,13 +334,22 @@ export function buildPreviewShims(): string {
334
334
  document.body.appendChild(existing);
335
335
  }
336
336
  existing.textContent = '';
337
+ var topBar = document.createElement('div');
338
+ 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);';
337
339
  var header = document.createElement('div');
338
- header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
340
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
339
341
  header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
342
+ var closeBtn = document.createElement('button');
343
+ closeBtn.type = 'button';
344
+ closeBtn.textContent = 'Dismiss \u00d7';
345
+ 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;';
346
+ closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
347
+ topBar.appendChild(header);
348
+ topBar.appendChild(closeBtn);
340
349
  var pre = document.createElement('pre');
341
- pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
350
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
342
351
  pre.textContent = String(stack || msg || '');
343
- existing.appendChild(header);
352
+ existing.appendChild(topBar);
344
353
  existing.appendChild(pre);
345
354
  } catch (err) {
346
355
  void err;
@@ -381,6 +390,189 @@ export function buildPreviewShims(): string {
381
390
  void err;
382
391
  }
383
392
  });
393
+
394
+ // Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
395
+ var pendingFetches = new Map();
396
+ var fetchSeq = 0;
397
+ function parseLoopbackTarget(rawUrl) {
398
+ if (!rawUrl || typeof rawUrl !== 'string') return null;
399
+ var trimmed = rawUrl.trim();
400
+ if (!trimmed) return null;
401
+ var lower = trimmed.toLowerCase();
402
+ 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;
403
+ if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
404
+ try {
405
+ var u = new URL(trimmed);
406
+ if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
407
+ return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
408
+ }
409
+ if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
410
+ var rest = u.pathname.slice('/__preview/'.length);
411
+ var slashIdx = rest.indexOf('/');
412
+ var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
413
+ var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
414
+ var portNum = Number(portStr);
415
+ if (portNum > 0) {
416
+ return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
417
+ }
418
+ }
419
+ } catch (e) { void e; }
420
+ return null;
421
+ }
422
+ if (trimmed.indexOf('/__preview/') === 0) {
423
+ var restRel = trimmed.slice('/__preview/'.length);
424
+ var sIdx = restRel.indexOf('/');
425
+ var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
426
+ var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
427
+ var pNum = Number(pStr);
428
+ if (pNum > 0) {
429
+ return { port: pNum, path: sPath || '/' };
430
+ }
431
+ }
432
+ var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
433
+ var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
434
+ return { port: null, path: pathPart };
435
+ }
436
+
437
+ window.addEventListener('message', function (event) {
438
+ var data = event && event.data;
439
+ if (!data || typeof data !== 'object') return;
440
+ if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
441
+ var entry = pendingFetches.get(data.reqId);
442
+ if (!entry) return;
443
+ pendingFetches.delete(data.reqId);
444
+ entry.resolve(data);
445
+ }
446
+ });
447
+
448
+ if (typeof window.fetch === 'function') {
449
+ var origFetch = window.fetch.bind(window);
450
+ window.fetch = function (input, init) {
451
+ var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
452
+ var target = parseLoopbackTarget(urlStr);
453
+ // Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
454
+ var isOpaque = false;
455
+ try {
456
+ var lowerUrl = urlStr.toLowerCase();
457
+ var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
458
+ isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
459
+ } catch (e) { isOpaque = true; void e; }
460
+ if (!target || !isOpaque || window.parent === window) {
461
+ return origFetch(input, init);
462
+ }
463
+ return new Promise(function (resolve, reject) {
464
+ var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
465
+ var method = (init && init.method) || (input && input.method) || 'GET';
466
+ var headersObj = {};
467
+ try {
468
+ var rawH = (init && init.headers) || (input && input.headers);
469
+ if (rawH) {
470
+ if (typeof rawH.forEach === 'function') {
471
+ rawH.forEach(function (v, k) { headersObj[k] = v; });
472
+ } else if (Array.isArray(rawH)) {
473
+ rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
474
+ } else if (typeof rawH === 'object') {
475
+ Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
476
+ }
477
+ }
478
+ } catch (e) { void e; }
479
+ var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
480
+ var timer = setTimeout(function () {
481
+ if (pendingFetches.has(reqId)) {
482
+ pendingFetches.delete(reqId);
483
+ origFetch(input, init).then(resolve, reject);
484
+ }
485
+ }, 5000);
486
+ pendingFetches.set(reqId, {
487
+ resolve: function (payload) {
488
+ clearTimeout(timer);
489
+ if (payload && payload.error) {
490
+ reject(new TypeError(String(payload.error)));
491
+ return;
492
+ }
493
+ var status = Number(payload && payload.status) || 200;
494
+ var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
495
+ var body = payload && payload.body !== undefined ? String(payload.body) : '';
496
+ try {
497
+ resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
498
+ } catch (err) {
499
+ void err;
500
+ resolve({
501
+ ok: status >= 200 && status < 300,
502
+ status: status,
503
+ headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
504
+ text: function () { return Promise.resolve(body); },
505
+ json: function () { return Promise.resolve(JSON.parse(body)); }
506
+ });
507
+ }
508
+ }
509
+ });
510
+ try {
511
+ parent.postMessage({
512
+ type: 'codelab:preview-fetch',
513
+ reqId: reqId,
514
+ port: target.port,
515
+ path: target.path,
516
+ method: String(method).toUpperCase(),
517
+ headers: headersObj,
518
+ body: bodyStr
519
+ }, '*');
520
+ } catch (err) {
521
+ clearTimeout(timer);
522
+ pendingFetches.delete(reqId);
523
+ origFetch(input, init).then(resolve, reject);
524
+ }
525
+ });
526
+ };
527
+ }
528
+
529
+ // Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
530
+ document.addEventListener('click', function (event) {
531
+ if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
532
+ var el = event.target;
533
+ while (el && el.tagName !== 'A') el = el.parentElement;
534
+ if (!el || !el.getAttribute) return;
535
+ var href = el.getAttribute('href');
536
+ var targetAttr = el.getAttribute('target');
537
+ if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
538
+ var lowerHref = href.toLowerCase();
539
+ 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;
540
+ var parsed = parseLoopbackTarget(href);
541
+ if (!parsed) return;
542
+ event.preventDefault();
543
+ try {
544
+ parent.postMessage({
545
+ type: 'codelab:preview-navigate',
546
+ port: parsed.port,
547
+ path: parsed.path
548
+ }, '*');
549
+ } catch (e) { void e; }
550
+ });
551
+
552
+ // Sync SPA history.pushState / replaceState with the preview omni-address bar
553
+ try {
554
+ ['pushState', 'replaceState'].forEach(function (method) {
555
+ var orig = history[method];
556
+ if (typeof orig !== 'function') return;
557
+ history[method] = function (state, title, url) {
558
+ var ret;
559
+ try { ret = orig.apply(history, arguments); } catch (e) { void e; }
560
+ if (url !== undefined && url !== null) {
561
+ var parsed = parseLoopbackTarget(String(url));
562
+ if (parsed) {
563
+ try {
564
+ parent.postMessage({
565
+ type: 'codelab:preview-url-change',
566
+ path: parsed.path,
567
+ replace: method === 'replaceState'
568
+ }, '*');
569
+ } catch (e) { void e; }
570
+ }
571
+ }
572
+ return ret;
573
+ };
574
+ });
575
+ } catch (e) { void e; }
384
576
  })();
385
577
  </script>`;
386
578
  }
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @innovatorved/code-lab v0.1.8
2
+ * @innovatorved/code-lab v0.1.9
3
3
  * Browser-native IDE, POSIX Shell, Web Worker Node.js/Bun Runtime, and Git Engine.
4
4
  */
5
5
 
package/src/schemas.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  /**
4
- * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.8
4
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.9
5
5
  */
6
6
 
7
7
  // ── 1. Guided Step ──────────────────────────────────────────────────────────
package/src/shell.ts CHANGED
@@ -3024,10 +3024,10 @@
3024
3024
  return imports;
3025
3025
  }
3026
3026
 
3027
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3028
- const scripts = [];
3027
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
3028
+ const files = [];
3029
3029
  const walk = (dir, depth) => {
3030
- if (depth > 8 || scripts.length >= maxFiles) return;
3030
+ if (depth > 8 || files.length >= maxFiles) return;
3031
3031
  let entries = [];
3032
3032
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
3033
3033
  for (const name of entries) {
@@ -3038,13 +3038,23 @@
3038
3038
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
3039
3039
  if (dirFlag) {
3040
3040
  walk(full, depth + 1);
3041
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
3042
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
3041
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
3042
+ try {
3043
+ const content = vfs.readFileSync(full, 'utf8');
3044
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
3045
+ files.push({ full, rel, content });
3046
+ } catch (err) {
3047
+ _shellLogger.debug('Preview script read skipped.', full, err);
3048
+ }
3043
3049
  }
3044
3050
  }
3045
3051
  };
3046
3052
  walk(rootDir, 0);
3047
- return scripts;
3053
+ return files;
3054
+ }
3055
+
3056
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3057
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
3048
3058
  }
3049
3059
 
3050
3060
  function injectPreviewExtras(html, importMap) {
@@ -3069,12 +3079,6 @@
3069
3079
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
3070
3080
  while (taken.has(port)) port++;
3071
3081
 
3072
- const specifiers = new Set();
3073
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
3074
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
3075
- }
3076
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3077
-
3078
3082
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
3079
3083
  const isDir = (p) => {
3080
3084
  try {
@@ -3082,8 +3086,109 @@
3082
3086
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
3083
3087
  } catch (_) { return false; }
3084
3088
  };
3089
+ const isFile = (p) => exists(p) && !isDir(p);
3085
3090
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3086
3091
 
3092
+ const resolveLocalTarget = (baseDir, rawSpec) => {
3093
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
3094
+ const clean = rawSpec.split(/[?#]/)[0].trim();
3095
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
3096
+ const candidateBase = clean.startsWith('/')
3097
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3098
+ : PosixPath.join(baseDir, clean);
3099
+ if (isFile(candidateBase)) return candidateBase;
3100
+ const cands = [
3101
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
3102
+ candidateBase + '.mjs', candidateBase + '.cjs',
3103
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
3104
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3105
+ ];
3106
+ for (const c of cands) {
3107
+ if (isFile(c)) return c;
3108
+ }
3109
+ return null;
3110
+ };
3111
+
3112
+ const toLocalImportKey = (fullPath) => {
3113
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
3114
+ return `@codelab-local/${rel}`;
3115
+ };
3116
+
3117
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
3118
+ let out = code;
3119
+ try {
3120
+ const rm = getRuntimeModule();
3121
+ if (rm && typeof rm.transpileForBrowser === 'function') {
3122
+ out = rm.transpileForBrowser(out, sourcePath);
3123
+ }
3124
+ } catch (err) {
3125
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
3126
+ }
3127
+ const fromDir = PosixPath.dirname(sourcePath);
3128
+ const rewriteSpec = (spec) => {
3129
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
3130
+ const resolved = resolveLocalTarget(fromDir, spec);
3131
+ return resolved ? toLocalImportKey(resolved) : spec;
3132
+ };
3133
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3134
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3135
+ return out;
3136
+ };
3137
+
3138
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
3139
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
3140
+ const specifiers = new Set();
3141
+ for (const f of scriptFiles) {
3142
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
3143
+ }
3144
+ // Also scan inline module scripts in HTML for bare specifiers
3145
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
3146
+ let inlineMatch;
3147
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
3148
+ if (inlineMatch[1]) {
3149
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
3150
+ }
3151
+ }
3152
+
3153
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3154
+ for (const f of scriptFiles) {
3155
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
3156
+ const key = toLocalImportKey(f.full);
3157
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
3158
+ }
3159
+
3160
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
3161
+ let transformedHtml = htmlBody;
3162
+
3163
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
3164
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
3165
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
3166
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
3167
+ if (!hrefMatch) return fullTag;
3168
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
3169
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
3170
+ const cssContent = readText(cssTarget);
3171
+ if (cssContent === null) return fullTag;
3172
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
3173
+ });
3174
+
3175
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
3176
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
3177
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
3178
+ if (!srcMatch) return fullTag;
3179
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
3180
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3181
+ const rawScript = readText(scriptTarget);
3182
+ if (rawScript === null) return fullTag;
3183
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3184
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
3185
+ const typeAttr = isMod ? ' type="module"' : '';
3186
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
3187
+ });
3188
+
3189
+ return injectPreviewExtras(transformedHtml, importMap);
3190
+ };
3191
+
3087
3192
  const handler = async (request) => {
3088
3193
  let pathname = '/';
3089
3194
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
@@ -3118,7 +3223,7 @@
3118
3223
  let body = readText(target);
3119
3224
  if (body === null) body = '';
3120
3225
  if (/\.html?$/i.test(target)) {
3121
- body = injectPreviewExtras(body, importMap);
3226
+ body = buildHtmlPreviewResponse(body, target);
3122
3227
  } else if (isPreviewScriptPath(target)) {
3123
3228
  try {
3124
3229
  const rm = getRuntimeModule();