@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/dist/index.d.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
  export * from './schemas';
@@ -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.9 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -265,13 +265,22 @@ var CodeLabCsp = (() => {
265
265
  document.body.appendChild(existing);
266
266
  }
267
267
  existing.textContent = '';
268
+ var topBar = document.createElement('div');
269
+ 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);';
268
270
  var header = document.createElement('div');
269
- header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
271
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
270
272
  header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
273
+ var closeBtn = document.createElement('button');
274
+ closeBtn.type = 'button';
275
+ closeBtn.textContent = 'Dismiss \xD7';
276
+ 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;';
277
+ closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
278
+ topBar.appendChild(header);
279
+ topBar.appendChild(closeBtn);
271
280
  var pre = document.createElement('pre');
272
- pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
281
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
273
282
  pre.textContent = String(stack || msg || '');
274
- existing.appendChild(header);
283
+ existing.appendChild(topBar);
275
284
  existing.appendChild(pre);
276
285
  } catch (err) {
277
286
  void err;
@@ -312,6 +321,189 @@ var CodeLabCsp = (() => {
312
321
  void err;
313
322
  }
314
323
  });
324
+
325
+ // Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
326
+ var pendingFetches = new Map();
327
+ var fetchSeq = 0;
328
+ function parseLoopbackTarget(rawUrl) {
329
+ if (!rawUrl || typeof rawUrl !== 'string') return null;
330
+ var trimmed = rawUrl.trim();
331
+ if (!trimmed) return null;
332
+ var lower = trimmed.toLowerCase();
333
+ 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;
334
+ if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
335
+ try {
336
+ var u = new URL(trimmed);
337
+ if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
338
+ return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
339
+ }
340
+ if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
341
+ var rest = u.pathname.slice('/__preview/'.length);
342
+ var slashIdx = rest.indexOf('/');
343
+ var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
344
+ var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
345
+ var portNum = Number(portStr);
346
+ if (portNum > 0) {
347
+ return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
348
+ }
349
+ }
350
+ } catch (e) { void e; }
351
+ return null;
352
+ }
353
+ if (trimmed.indexOf('/__preview/') === 0) {
354
+ var restRel = trimmed.slice('/__preview/'.length);
355
+ var sIdx = restRel.indexOf('/');
356
+ var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
357
+ var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
358
+ var pNum = Number(pStr);
359
+ if (pNum > 0) {
360
+ return { port: pNum, path: sPath || '/' };
361
+ }
362
+ }
363
+ var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
364
+ var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
365
+ return { port: null, path: pathPart };
366
+ }
367
+
368
+ window.addEventListener('message', function (event) {
369
+ var data = event && event.data;
370
+ if (!data || typeof data !== 'object') return;
371
+ if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
372
+ var entry = pendingFetches.get(data.reqId);
373
+ if (!entry) return;
374
+ pendingFetches.delete(data.reqId);
375
+ entry.resolve(data);
376
+ }
377
+ });
378
+
379
+ if (typeof window.fetch === 'function') {
380
+ var origFetch = window.fetch.bind(window);
381
+ window.fetch = function (input, init) {
382
+ var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
383
+ var target = parseLoopbackTarget(urlStr);
384
+ // Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
385
+ var isOpaque = false;
386
+ try {
387
+ var lowerUrl = urlStr.toLowerCase();
388
+ var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
389
+ isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
390
+ } catch (e) { isOpaque = true; void e; }
391
+ if (!target || !isOpaque || window.parent === window) {
392
+ return origFetch(input, init);
393
+ }
394
+ return new Promise(function (resolve, reject) {
395
+ var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
396
+ var method = (init && init.method) || (input && input.method) || 'GET';
397
+ var headersObj = {};
398
+ try {
399
+ var rawH = (init && init.headers) || (input && input.headers);
400
+ if (rawH) {
401
+ if (typeof rawH.forEach === 'function') {
402
+ rawH.forEach(function (v, k) { headersObj[k] = v; });
403
+ } else if (Array.isArray(rawH)) {
404
+ rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
405
+ } else if (typeof rawH === 'object') {
406
+ Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
407
+ }
408
+ }
409
+ } catch (e) { void e; }
410
+ var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
411
+ var timer = setTimeout(function () {
412
+ if (pendingFetches.has(reqId)) {
413
+ pendingFetches.delete(reqId);
414
+ origFetch(input, init).then(resolve, reject);
415
+ }
416
+ }, 5000);
417
+ pendingFetches.set(reqId, {
418
+ resolve: function (payload) {
419
+ clearTimeout(timer);
420
+ if (payload && payload.error) {
421
+ reject(new TypeError(String(payload.error)));
422
+ return;
423
+ }
424
+ var status = Number(payload && payload.status) || 200;
425
+ var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
426
+ var body = payload && payload.body !== undefined ? String(payload.body) : '';
427
+ try {
428
+ resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
429
+ } catch (err) {
430
+ void err;
431
+ resolve({
432
+ ok: status >= 200 && status < 300,
433
+ status: status,
434
+ headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
435
+ text: function () { return Promise.resolve(body); },
436
+ json: function () { return Promise.resolve(JSON.parse(body)); }
437
+ });
438
+ }
439
+ }
440
+ });
441
+ try {
442
+ parent.postMessage({
443
+ type: 'codelab:preview-fetch',
444
+ reqId: reqId,
445
+ port: target.port,
446
+ path: target.path,
447
+ method: String(method).toUpperCase(),
448
+ headers: headersObj,
449
+ body: bodyStr
450
+ }, '*');
451
+ } catch (err) {
452
+ clearTimeout(timer);
453
+ pendingFetches.delete(reqId);
454
+ origFetch(input, init).then(resolve, reject);
455
+ }
456
+ });
457
+ };
458
+ }
459
+
460
+ // Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
461
+ document.addEventListener('click', function (event) {
462
+ if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
463
+ var el = event.target;
464
+ while (el && el.tagName !== 'A') el = el.parentElement;
465
+ if (!el || !el.getAttribute) return;
466
+ var href = el.getAttribute('href');
467
+ var targetAttr = el.getAttribute('target');
468
+ if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
469
+ var lowerHref = href.toLowerCase();
470
+ 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;
471
+ var parsed = parseLoopbackTarget(href);
472
+ if (!parsed) return;
473
+ event.preventDefault();
474
+ try {
475
+ parent.postMessage({
476
+ type: 'codelab:preview-navigate',
477
+ port: parsed.port,
478
+ path: parsed.path
479
+ }, '*');
480
+ } catch (e) { void e; }
481
+ });
482
+
483
+ // Sync SPA history.pushState / replaceState with the preview omni-address bar
484
+ try {
485
+ ['pushState', 'replaceState'].forEach(function (method) {
486
+ var orig = history[method];
487
+ if (typeof orig !== 'function') return;
488
+ history[method] = function (state, title, url) {
489
+ var ret;
490
+ try { ret = orig.apply(history, arguments); } catch (e) { void e; }
491
+ if (url !== undefined && url !== null) {
492
+ var parsed = parseLoopbackTarget(String(url));
493
+ if (parsed) {
494
+ try {
495
+ parent.postMessage({
496
+ type: 'codelab:preview-url-change',
497
+ path: parsed.path,
498
+ replace: method === 'replaceState'
499
+ }, '*');
500
+ } catch (e) { void e; }
501
+ }
502
+ }
503
+ return ret;
504
+ };
505
+ });
506
+ } catch (e) { void e; }
315
507
  })();
316
508
  <\/script>`;
317
509
  }
@@ -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.9 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
package/dist/runtime.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.9 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
package/dist/schemas.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  /**
3
- * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.8
3
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.9
4
4
  */
5
5
  export declare const GuidedStepSchema: z.ZodObject<{
6
6
  id: z.ZodString;
package/dist/shell.esm.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.9 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -3143,10 +3143,10 @@ var CodeLabLogger = (() => {
3143
3143
  return imports;
3144
3144
  }
3145
3145
 
3146
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3147
- const scripts = [];
3146
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
3147
+ const files = [];
3148
3148
  const walk = (dir, depth) => {
3149
- if (depth > 8 || scripts.length >= maxFiles) return;
3149
+ if (depth > 8 || files.length >= maxFiles) return;
3150
3150
  let entries = [];
3151
3151
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
3152
3152
  for (const name of entries) {
@@ -3157,13 +3157,23 @@ var CodeLabLogger = (() => {
3157
3157
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
3158
3158
  if (dirFlag) {
3159
3159
  walk(full, depth + 1);
3160
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
3161
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
3160
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
3161
+ try {
3162
+ const content = vfs.readFileSync(full, 'utf8');
3163
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
3164
+ files.push({ full, rel, content });
3165
+ } catch (err) {
3166
+ _shellLogger.debug('Preview script read skipped.', full, err);
3167
+ }
3162
3168
  }
3163
3169
  }
3164
3170
  };
3165
3171
  walk(rootDir, 0);
3166
- return scripts;
3172
+ return files;
3173
+ }
3174
+
3175
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3176
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
3167
3177
  }
3168
3178
 
3169
3179
  function injectPreviewExtras(html, importMap) {
@@ -3188,12 +3198,6 @@ var CodeLabLogger = (() => {
3188
3198
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
3189
3199
  while (taken.has(port)) port++;
3190
3200
 
3191
- const specifiers = new Set();
3192
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
3193
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
3194
- }
3195
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3196
-
3197
3201
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
3198
3202
  const isDir = (p) => {
3199
3203
  try {
@@ -3201,8 +3205,109 @@ var CodeLabLogger = (() => {
3201
3205
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
3202
3206
  } catch (_) { return false; }
3203
3207
  };
3208
+ const isFile = (p) => exists(p) && !isDir(p);
3204
3209
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3205
3210
 
3211
+ const resolveLocalTarget = (baseDir, rawSpec) => {
3212
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
3213
+ const clean = rawSpec.split(/[?#]/)[0].trim();
3214
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
3215
+ const candidateBase = clean.startsWith('/')
3216
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3217
+ : PosixPath.join(baseDir, clean);
3218
+ if (isFile(candidateBase)) return candidateBase;
3219
+ const cands = [
3220
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
3221
+ candidateBase + '.mjs', candidateBase + '.cjs',
3222
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
3223
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3224
+ ];
3225
+ for (const c of cands) {
3226
+ if (isFile(c)) return c;
3227
+ }
3228
+ return null;
3229
+ };
3230
+
3231
+ const toLocalImportKey = (fullPath) => {
3232
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
3233
+ return `@codelab-local/${rel}`;
3234
+ };
3235
+
3236
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
3237
+ let out = code;
3238
+ try {
3239
+ const rm = getRuntimeModule();
3240
+ if (rm && typeof rm.transpileForBrowser === 'function') {
3241
+ out = rm.transpileForBrowser(out, sourcePath);
3242
+ }
3243
+ } catch (err) {
3244
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
3245
+ }
3246
+ const fromDir = PosixPath.dirname(sourcePath);
3247
+ const rewriteSpec = (spec) => {
3248
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
3249
+ const resolved = resolveLocalTarget(fromDir, spec);
3250
+ return resolved ? toLocalImportKey(resolved) : spec;
3251
+ };
3252
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3253
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3254
+ return out;
3255
+ };
3256
+
3257
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
3258
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
3259
+ const specifiers = new Set();
3260
+ for (const f of scriptFiles) {
3261
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
3262
+ }
3263
+ // Also scan inline module scripts in HTML for bare specifiers
3264
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
3265
+ let inlineMatch;
3266
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
3267
+ if (inlineMatch[1]) {
3268
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
3269
+ }
3270
+ }
3271
+
3272
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3273
+ for (const f of scriptFiles) {
3274
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
3275
+ const key = toLocalImportKey(f.full);
3276
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
3277
+ }
3278
+
3279
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
3280
+ let transformedHtml = htmlBody;
3281
+
3282
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
3283
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
3284
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
3285
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
3286
+ if (!hrefMatch) return fullTag;
3287
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
3288
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
3289
+ const cssContent = readText(cssTarget);
3290
+ if (cssContent === null) return fullTag;
3291
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
3292
+ });
3293
+
3294
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
3295
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
3296
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
3297
+ if (!srcMatch) return fullTag;
3298
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
3299
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3300
+ const rawScript = readText(scriptTarget);
3301
+ if (rawScript === null) return fullTag;
3302
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3303
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
3304
+ const typeAttr = isMod ? ' type="module"' : '';
3305
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
3306
+ });
3307
+
3308
+ return injectPreviewExtras(transformedHtml, importMap);
3309
+ };
3310
+
3206
3311
  const handler = async (request) => {
3207
3312
  let pathname = '/';
3208
3313
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
@@ -3237,7 +3342,7 @@ var CodeLabLogger = (() => {
3237
3342
  let body = readText(target);
3238
3343
  if (body === null) body = '';
3239
3344
  if (/\.html?$/i.test(target)) {
3240
- body = injectPreviewExtras(body, importMap);
3345
+ body = buildHtmlPreviewResponse(body, target);
3241
3346
  } else if (isPreviewScriptPath(target)) {
3242
3347
  try {
3243
3348
  const rm = getRuntimeModule();
package/dist/shell.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.9 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -3144,10 +3144,10 @@ var CodeLabLogger = (() => {
3144
3144
  return imports;
3145
3145
  }
3146
3146
 
3147
- function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3148
- const scripts = [];
3147
+ function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
3148
+ const files = [];
3149
3149
  const walk = (dir, depth) => {
3150
- if (depth > 8 || scripts.length >= maxFiles) return;
3150
+ if (depth > 8 || files.length >= maxFiles) return;
3151
3151
  let entries = [];
3152
3152
  try { entries = vfs.readdirSync(dir); } catch (_) { return; }
3153
3153
  for (const name of entries) {
@@ -3158,13 +3158,23 @@ var CodeLabLogger = (() => {
3158
3158
  const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
3159
3159
  if (dirFlag) {
3160
3160
  walk(full, depth + 1);
3161
- } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
3162
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
3161
+ } else if (isPreviewScriptPath(name) && files.length < maxFiles) {
3162
+ try {
3163
+ const content = vfs.readFileSync(full, 'utf8');
3164
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
3165
+ files.push({ full, rel, content });
3166
+ } catch (err) {
3167
+ _shellLogger.debug('Preview script read skipped.', full, err);
3168
+ }
3163
3169
  }
3164
3170
  }
3165
3171
  };
3166
3172
  walk(rootDir, 0);
3167
- return scripts;
3173
+ return files;
3174
+ }
3175
+
3176
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3177
+ return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
3168
3178
  }
3169
3179
 
3170
3180
  function injectPreviewExtras(html, importMap) {
@@ -3189,12 +3199,6 @@ var CodeLabLogger = (() => {
3189
3199
  const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
3190
3200
  while (taken.has(port)) port++;
3191
3201
 
3192
- const specifiers = new Set();
3193
- for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
3194
- for (const s of extractBareSpecifiers(content)) specifiers.add(s);
3195
- }
3196
- const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3197
-
3198
3202
  const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
3199
3203
  const isDir = (p) => {
3200
3204
  try {
@@ -3202,8 +3206,109 @@ var CodeLabLogger = (() => {
3202
3206
  return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
3203
3207
  } catch (_) { return false; }
3204
3208
  };
3209
+ const isFile = (p) => exists(p) && !isDir(p);
3205
3210
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3206
3211
 
3212
+ const resolveLocalTarget = (baseDir, rawSpec) => {
3213
+ if (!rawSpec || typeof rawSpec !== 'string') return null;
3214
+ const clean = rawSpec.split(/[?#]/)[0].trim();
3215
+ if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
3216
+ const candidateBase = clean.startsWith('/')
3217
+ ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3218
+ : PosixPath.join(baseDir, clean);
3219
+ if (isFile(candidateBase)) return candidateBase;
3220
+ const cands = [
3221
+ candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
3222
+ candidateBase + '.mjs', candidateBase + '.cjs',
3223
+ PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
3224
+ PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3225
+ ];
3226
+ for (const c of cands) {
3227
+ if (isFile(c)) return c;
3228
+ }
3229
+ return null;
3230
+ };
3231
+
3232
+ const toLocalImportKey = (fullPath) => {
3233
+ const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
3234
+ return `@codelab-local/${rel}`;
3235
+ };
3236
+
3237
+ const transpileAndRewriteLocalImports = (code, sourcePath) => {
3238
+ let out = code;
3239
+ try {
3240
+ const rm = getRuntimeModule();
3241
+ if (rm && typeof rm.transpileForBrowser === 'function') {
3242
+ out = rm.transpileForBrowser(out, sourcePath);
3243
+ }
3244
+ } catch (err) {
3245
+ _shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
3246
+ }
3247
+ const fromDir = PosixPath.dirname(sourcePath);
3248
+ const rewriteSpec = (spec) => {
3249
+ if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
3250
+ const resolved = resolveLocalTarget(fromDir, spec);
3251
+ return resolved ? toLocalImportKey(resolved) : spec;
3252
+ };
3253
+ out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3254
+ out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
3255
+ return out;
3256
+ };
3257
+
3258
+ const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
3259
+ const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
3260
+ const specifiers = new Set();
3261
+ for (const f of scriptFiles) {
3262
+ for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
3263
+ }
3264
+ // Also scan inline module scripts in HTML for bare specifiers
3265
+ const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
3266
+ let inlineMatch;
3267
+ while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
3268
+ if (inlineMatch[1]) {
3269
+ for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
3270
+ }
3271
+ }
3272
+
3273
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3274
+ for (const f of scriptFiles) {
3275
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
3276
+ const key = toLocalImportKey(f.full);
3277
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
3278
+ }
3279
+
3280
+ const htmlDir = PosixPath.dirname(htmlTargetPath);
3281
+ let transformedHtml = htmlBody;
3282
+
3283
+ // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
3284
+ transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
3285
+ if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
3286
+ const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
3287
+ if (!hrefMatch) return fullTag;
3288
+ const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
3289
+ if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
3290
+ const cssContent = readText(cssTarget);
3291
+ if (cssContent === null) return fullTag;
3292
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
3293
+ });
3294
+
3295
+ // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
3296
+ transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
3297
+ const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
3298
+ if (!srcMatch) return fullTag;
3299
+ const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
3300
+ if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3301
+ const rawScript = readText(scriptTarget);
3302
+ if (rawScript === null) return fullTag;
3303
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3304
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
3305
+ const typeAttr = isMod ? ' type="module"' : '';
3306
+ return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
3307
+ });
3308
+
3309
+ return injectPreviewExtras(transformedHtml, importMap);
3310
+ };
3311
+
3207
3312
  const handler = async (request) => {
3208
3313
  let pathname = '/';
3209
3314
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
@@ -3238,7 +3343,7 @@ var CodeLabLogger = (() => {
3238
3343
  let body = readText(target);
3239
3344
  if (body === null) body = '';
3240
3345
  if (/\.html?$/i.test(target)) {
3241
- body = injectPreviewExtras(body, importMap);
3346
+ body = buildHtmlPreviewResponse(body, target);
3242
3347
  } else if (isPreviewScriptPath(target)) {
3243
3348
  try {
3244
3349
  const rm = getRuntimeModule();
@@ -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.9 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
package/dist/terminal.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.9 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@innovatorved/code-lab",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "Standalone browser-native IDE Workbench, POSIX Shell & Coreutils, PTY Terminal, and Web Worker Node.js/Bun Virtual Runtime.",
5
5
  "main": "./dist/code-lab.js",
6
6
  "module": "./dist/code-lab.esm.js",