@innovatorved/code-lab 0.1.8 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +1 -1
- package/README.md +1 -1
- package/dist/code-lab.css +710 -9
- package/dist/code-lab.d.ts +1 -1
- package/dist/code-lab.esm.js +704 -35
- package/dist/code-lab.js +703 -34
- package/dist/index.d.ts +1 -1
- package/dist/preview-sw.js +197 -5
- package/dist/runtime.esm.js +1 -1
- package/dist/runtime.js +1 -1
- package/dist/schemas.d.ts +1 -1
- package/dist/shell.esm.js +151 -14
- package/dist/shell.js +151 -14
- package/dist/terminal.esm.js +1 -1
- package/dist/terminal.js +1 -1
- package/package.json +1 -1
- package/src/code-lab.css +710 -9
- package/src/csp.ts +201 -4
- package/src/index.ts +1 -1
- package/src/schemas.ts +1 -1
- package/src/shell.ts +150 -13
- package/src/workbench.ts +356 -16
package/dist/index.d.ts
CHANGED
package/dist/preview-sw.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab v0.1.
|
|
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
|
|
@@ -144,7 +144,7 @@ var CodeLabCsp = (() => {
|
|
|
144
144
|
const host = normalizeOrigin(options.hostOrigin);
|
|
145
145
|
const self = host || "'self'";
|
|
146
146
|
const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
|
|
147
|
-
const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
|
|
147
|
+
const script = () => [self, "data:", "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
|
|
148
148
|
const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
|
|
149
149
|
const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
|
|
150
150
|
return [
|
|
@@ -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:
|
|
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(
|
|
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
|
}
|
package/dist/runtime.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab v0.1.
|
|
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
|
package/dist/runtime.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab v0.1.
|
|
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
|
package/dist/schemas.d.ts
CHANGED
package/dist/shell.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab v0.1.
|
|
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
|
|
@@ -3143,10 +3143,40 @@ var CodeLabLogger = (() => {
|
|
|
3143
3143
|
return imports;
|
|
3144
3144
|
}
|
|
3145
3145
|
|
|
3146
|
-
|
|
3147
|
-
|
|
3146
|
+
// Some templates pin a CDN URL in the source instead of importing a bare
|
|
3147
|
+
// specifier, e.g. `import React from "https://cdn.jsdelivr.net/npm/react@19.3.1/+esm"`.
|
|
3148
|
+
// Those URL specifiers are resolved by the browser directly, so they bypass the
|
|
3149
|
+
// generated import map (and with it the project's declared version and the
|
|
3150
|
+
// multi-CDN fallback). Import maps can remap URL specifiers, so alias each
|
|
3151
|
+
// literal URL found in the project to the resolved bare-specifier URL.
|
|
3152
|
+
// The pinned version is kept when the project has no dependency to resolve.
|
|
3153
|
+
const PINNED_CDN_URL_RE = /https?:\/\/(?:cdn\.jsdelivr\.net\/npm|esm\.sh)\/((?:@[^\/'"`@\s]+\/)?[^\/'"`@\s]+)@([^\s'"`),;]+)/g;
|
|
3154
|
+
|
|
3155
|
+
function aliasPinnedCdnUrls(vfs, rootDir, text, importMap) {
|
|
3156
|
+
if (!text || typeof text !== 'string') return;
|
|
3157
|
+
const re = new RegExp(PINNED_CDN_URL_RE.source, 'g');
|
|
3158
|
+
let match;
|
|
3159
|
+
while ((match = re.exec(text)) !== null) {
|
|
3160
|
+
const url = match[0];
|
|
3161
|
+
const pkgName = decodeURIComponent(match[1]);
|
|
3162
|
+
const rest = match[2];
|
|
3163
|
+
const pinnedVersion = rest.split(/[\/?]/)[0];
|
|
3164
|
+
const tail = rest.slice(pinnedVersion.length);
|
|
3165
|
+
const rawSubpath = tail.startsWith('/') && tail !== '/+esm' ? tail.slice(1).split(/[?#]/)[0] : '';
|
|
3166
|
+
const subpath = rawSubpath.replace(/^\/+|\/+$/g, '');
|
|
3167
|
+
const bare = subpath ? `${pkgName}/${subpath}` : pkgName;
|
|
3168
|
+
|
|
3169
|
+
const declared = resolveBareVersion(vfs, rootDir, pkgName);
|
|
3170
|
+
const version = declared && declared !== 'latest' ? declared : decodeURIComponent(pinnedVersion);
|
|
3171
|
+
const target = importMap[bare] || cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
3172
|
+
if (target && target !== url) importMap[url] = target;
|
|
3173
|
+
}
|
|
3174
|
+
}
|
|
3175
|
+
|
|
3176
|
+
function collectPreviewScriptFiles(vfs, rootDir, maxFiles = 200) {
|
|
3177
|
+
const files = [];
|
|
3148
3178
|
const walk = (dir, depth) => {
|
|
3149
|
-
if (depth > 8 ||
|
|
3179
|
+
if (depth > 8 || files.length >= maxFiles) return;
|
|
3150
3180
|
let entries = [];
|
|
3151
3181
|
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
3152
3182
|
for (const name of entries) {
|
|
@@ -3157,13 +3187,23 @@ var CodeLabLogger = (() => {
|
|
|
3157
3187
|
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
3158
3188
|
if (dirFlag) {
|
|
3159
3189
|
walk(full, depth + 1);
|
|
3160
|
-
} else if (isPreviewScriptPath(name) &&
|
|
3161
|
-
try {
|
|
3190
|
+
} else if (isPreviewScriptPath(name) && files.length < maxFiles) {
|
|
3191
|
+
try {
|
|
3192
|
+
const content = vfs.readFileSync(full, 'utf8');
|
|
3193
|
+
const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
|
|
3194
|
+
files.push({ full, rel, content });
|
|
3195
|
+
} catch (err) {
|
|
3196
|
+
_shellLogger.debug('Preview script read skipped.', full, err);
|
|
3197
|
+
}
|
|
3162
3198
|
}
|
|
3163
3199
|
}
|
|
3164
3200
|
};
|
|
3165
3201
|
walk(rootDir, 0);
|
|
3166
|
-
return
|
|
3202
|
+
return files;
|
|
3203
|
+
}
|
|
3204
|
+
|
|
3205
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
3206
|
+
return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
|
|
3167
3207
|
}
|
|
3168
3208
|
|
|
3169
3209
|
function injectPreviewExtras(html, importMap) {
|
|
@@ -3188,12 +3228,6 @@ var CodeLabLogger = (() => {
|
|
|
3188
3228
|
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
3189
3229
|
while (taken.has(port)) port++;
|
|
3190
3230
|
|
|
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
3231
|
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
3198
3232
|
const isDir = (p) => {
|
|
3199
3233
|
try {
|
|
@@ -3201,8 +3235,111 @@ var CodeLabLogger = (() => {
|
|
|
3201
3235
|
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
3202
3236
|
} catch (_) { return false; }
|
|
3203
3237
|
};
|
|
3238
|
+
const isFile = (p) => exists(p) && !isDir(p);
|
|
3204
3239
|
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
3205
3240
|
|
|
3241
|
+
const resolveLocalTarget = (baseDir, rawSpec) => {
|
|
3242
|
+
if (!rawSpec || typeof rawSpec !== 'string') return null;
|
|
3243
|
+
const clean = rawSpec.split(/[?#]/)[0].trim();
|
|
3244
|
+
if (!clean || /^(?:https?:|data:|blob:|\/\/)/i.test(clean)) return null;
|
|
3245
|
+
const candidateBase = clean.startsWith('/')
|
|
3246
|
+
? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
|
|
3247
|
+
: PosixPath.join(baseDir, clean);
|
|
3248
|
+
if (isFile(candidateBase)) return candidateBase;
|
|
3249
|
+
const cands = [
|
|
3250
|
+
candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
|
|
3251
|
+
candidateBase + '.mjs', candidateBase + '.cjs',
|
|
3252
|
+
PosixPath.join(candidateBase, 'index.tsx'), PosixPath.join(candidateBase, 'index.ts'),
|
|
3253
|
+
PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
|
|
3254
|
+
];
|
|
3255
|
+
for (const c of cands) {
|
|
3256
|
+
if (isFile(c)) return c;
|
|
3257
|
+
}
|
|
3258
|
+
return null;
|
|
3259
|
+
};
|
|
3260
|
+
|
|
3261
|
+
const toLocalImportKey = (fullPath) => {
|
|
3262
|
+
const rel = fullPath.startsWith(rootDir + '/') ? fullPath.slice(rootDir.length + 1) : fullPath.replace(/^\/+/, '');
|
|
3263
|
+
return `@codelab-local/${rel}`;
|
|
3264
|
+
};
|
|
3265
|
+
|
|
3266
|
+
const transpileAndRewriteLocalImports = (code, sourcePath) => {
|
|
3267
|
+
let out = code;
|
|
3268
|
+
try {
|
|
3269
|
+
const rm = getRuntimeModule();
|
|
3270
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
3271
|
+
out = rm.transpileForBrowser(out, sourcePath);
|
|
3272
|
+
}
|
|
3273
|
+
} catch (err) {
|
|
3274
|
+
_shellLogger.warn(`Preview script transpilation failed for ${sourcePath}.`, err);
|
|
3275
|
+
}
|
|
3276
|
+
const fromDir = PosixPath.dirname(sourcePath);
|
|
3277
|
+
const rewriteSpec = (spec) => {
|
|
3278
|
+
if (!spec || (!spec.startsWith('.') && !spec.startsWith('/'))) return spec;
|
|
3279
|
+
const resolved = resolveLocalTarget(fromDir, spec);
|
|
3280
|
+
return resolved ? toLocalImportKey(resolved) : spec;
|
|
3281
|
+
};
|
|
3282
|
+
out = out.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
|
|
3283
|
+
out = out.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g, (_, pre, spec, post) => `${pre}${rewriteSpec(spec)}${post}`);
|
|
3284
|
+
return out;
|
|
3285
|
+
};
|
|
3286
|
+
|
|
3287
|
+
const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
|
|
3288
|
+
const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
|
|
3289
|
+
const specifiers = new Set();
|
|
3290
|
+
for (const f of scriptFiles) {
|
|
3291
|
+
for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
|
|
3292
|
+
}
|
|
3293
|
+
// Also scan inline module scripts in HTML for bare specifiers
|
|
3294
|
+
const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
|
|
3295
|
+
let inlineMatch;
|
|
3296
|
+
while ((inlineMatch = inlineScriptRe.exec(htmlBody)) !== null) {
|
|
3297
|
+
if (inlineMatch[1]) {
|
|
3298
|
+
for (const s of extractBareSpecifiers(inlineMatch[1])) specifiers.add(s);
|
|
3299
|
+
}
|
|
3300
|
+
}
|
|
3301
|
+
|
|
3302
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
3303
|
+
for (const f of scriptFiles) aliasPinnedCdnUrls(ctx.vfs, rootDir, f.content, importMap);
|
|
3304
|
+
aliasPinnedCdnUrls(ctx.vfs, rootDir, htmlBody, importMap);
|
|
3305
|
+
for (const f of scriptFiles) {
|
|
3306
|
+
const compiled = transpileAndRewriteLocalImports(f.content, f.full);
|
|
3307
|
+
const key = toLocalImportKey(f.full);
|
|
3308
|
+
importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
|
|
3309
|
+
}
|
|
3310
|
+
|
|
3311
|
+
const htmlDir = PosixPath.dirname(htmlTargetPath);
|
|
3312
|
+
let transformedHtml = htmlBody;
|
|
3313
|
+
|
|
3314
|
+
// Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
|
|
3315
|
+
transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
|
|
3316
|
+
if (!/\brel\s*=\s*["']stylesheet["']/i.test(attrs)) return fullTag;
|
|
3317
|
+
const hrefMatch = /\bhref\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
3318
|
+
if (!hrefMatch) return fullTag;
|
|
3319
|
+
const cssTarget = resolveLocalTarget(htmlDir, hrefMatch[1]);
|
|
3320
|
+
if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
|
|
3321
|
+
const cssContent = readText(cssTarget);
|
|
3322
|
+
if (cssContent === null) return fullTag;
|
|
3323
|
+
return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '"')}">\n${cssContent}\n</style>`;
|
|
3324
|
+
});
|
|
3325
|
+
|
|
3326
|
+
// Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
|
|
3327
|
+
transformedHtml = transformedHtml.replace(/<script\b([^>]*?)>\s*<\/script>/gi, (fullTag, attrs) => {
|
|
3328
|
+
const srcMatch = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(attrs);
|
|
3329
|
+
if (!srcMatch) return fullTag;
|
|
3330
|
+
const scriptTarget = resolveLocalTarget(htmlDir, srcMatch[1]);
|
|
3331
|
+
if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
|
|
3332
|
+
const rawScript = readText(scriptTarget);
|
|
3333
|
+
if (rawScript === null) return fullTag;
|
|
3334
|
+
const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
|
|
3335
|
+
const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
|
|
3336
|
+
const typeAttr = isMod ? ' type="module"' : '';
|
|
3337
|
+
return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '"')}">\n${compiled}\n</script>`;
|
|
3338
|
+
});
|
|
3339
|
+
|
|
3340
|
+
return injectPreviewExtras(transformedHtml, importMap);
|
|
3341
|
+
};
|
|
3342
|
+
|
|
3206
3343
|
const handler = async (request) => {
|
|
3207
3344
|
let pathname = '/';
|
|
3208
3345
|
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
|
|
@@ -3237,7 +3374,7 @@ var CodeLabLogger = (() => {
|
|
|
3237
3374
|
let body = readText(target);
|
|
3238
3375
|
if (body === null) body = '';
|
|
3239
3376
|
if (/\.html?$/i.test(target)) {
|
|
3240
|
-
body =
|
|
3377
|
+
body = buildHtmlPreviewResponse(body, target);
|
|
3241
3378
|
} else if (isPreviewScriptPath(target)) {
|
|
3242
3379
|
try {
|
|
3243
3380
|
const rm = getRuntimeModule();
|