@innovatorved/code-lab 0.1.7 → 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 ADDED
@@ -0,0 +1,588 @@
1
+ /**
2
+ * @innovatorved/code-lab — Web Preview Content-Security-Policy builder
3
+ * ============================================================================
4
+ * One place that knows how a preview policy is assembled. Before this module
5
+ * existed the policy was copy-pasted into `preview-sw.js` and `workbench.ts`
6
+ * under a "keep both copies in sync" comment — the classic drift bug.
7
+ *
8
+ * Why the host origin appears literally instead of `'self'`:
9
+ * previews are served in a sandboxed iframe (`allow-scripts`, deliberately
10
+ * *without* `allow-same-origin`). A sandboxed document has an opaque origin, so
11
+ * `'self'` matches no URL at all and the app's own `/__preview/<port>/app.js`
12
+ * would be blocked. Naming the host origin keeps the app's assets loadable
13
+ * while the sandbox keeps it away from host DOM and storage.
14
+ *
15
+ * Bundled as a classic script (`globalName: CodeLabCsp`) so the Service Worker
16
+ * and the workbench can both consume it without a module loader.
17
+ */
18
+
19
+ export type PreviewCspMode = 'strict' | 'balanced' | 'custom';
20
+
21
+ /** Per-directive network allowlist. Values are origins or CSP source keywords. */
22
+ export interface PreviewCspSources {
23
+ scriptSrc?: string[];
24
+ styleSrc?: string[];
25
+ imgSrc?: string[];
26
+ fontSrc?: string[];
27
+ connectSrc?: string[];
28
+ mediaSrc?: string[];
29
+ workerSrc?: string[];
30
+ frameSrc?: string[];
31
+ }
32
+
33
+ export interface PreviewCspConfig extends PreviewCspSources {
34
+ mode?: PreviewCspMode | string;
35
+ }
36
+
37
+ export interface PreviewCspOptions extends PreviewCspConfig {
38
+ /** Origin that serves `/__preview/*` (the host page). Falls back to `'self'`. */
39
+ hostOrigin?: string;
40
+ /** Value for `frame-ancestors`; defaults to `'self'`. */
41
+ frameAncestors?: string;
42
+ }
43
+
44
+ export interface NormalizedPreviewCsp {
45
+ mode: PreviewCspMode;
46
+ allow: PreviewCspSources;
47
+ }
48
+
49
+ /** CDNs the built-in preview server itself resolves bare imports to. */
50
+ const IMPORT_MAP_CDNS = ['https://cdn.jsdelivr.net', 'https://esm.sh'];
51
+
52
+ /** Fonts commonly referenced by CDN-hosted CSS. */
53
+ const FONT_CDNS = ['https://cdn.jsdelivr.net', 'https://fonts.gstatic.com'];
54
+
55
+ const PRESETS: Record<'strict' | 'balanced', PreviewCspSources> = {
56
+ strict: {},
57
+ balanced: {
58
+ scriptSrc: IMPORT_MAP_CDNS.slice(),
59
+ styleSrc: ['https://cdn.jsdelivr.net', 'https://fonts.googleapis.com'],
60
+ fontSrc: FONT_CDNS.slice(),
61
+ connectSrc: IMPORT_MAP_CDNS.slice(),
62
+ imgSrc: ['https://cdn.jsdelivr.net']
63
+ }
64
+ };
65
+
66
+ const SOURCE_KEYS: Array<keyof PreviewCspSources> = [
67
+ 'scriptSrc',
68
+ 'styleSrc',
69
+ 'imgSrc',
70
+ 'fontSrc',
71
+ 'connectSrc',
72
+ 'mediaSrc',
73
+ 'workerSrc',
74
+ 'frameSrc'
75
+ ];
76
+
77
+ const MAX_SOURCES = 64;
78
+ const MAX_SOURCE_LENGTH = 512;
79
+
80
+ /** HTML marker so the shim block is injected exactly once. */
81
+ export const PREVIEW_SHIM_MARKER = 'data-codelab-preview-shims';
82
+
83
+ /** Accepts `"https://a.example"` and returns its origin; `null` otherwise. */
84
+ export function normalizeOrigin(raw: unknown): string | null {
85
+ if (raw === null || raw === undefined || raw === '') return null;
86
+ try {
87
+ const parsed = new URL(String(raw));
88
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
89
+ return parsed.origin;
90
+ } catch (_) {
91
+ // Not an absolute URL (e.g. "preview.example.com" or a relative path).
92
+ return null;
93
+ }
94
+ }
95
+
96
+ function normalizeMode(raw: unknown): PreviewCspMode {
97
+ if (raw === 'strict' || raw === 'custom') return raw;
98
+ return 'balanced';
99
+ }
100
+
101
+ /**
102
+ * CSP source keywords an author may name explicitly. Everything else has to be
103
+ * a concrete http(s) URL, `data:` or `blob:`.
104
+ */
105
+ const ALLOWED_KEYWORDS: ReadonlyArray<string> = [
106
+ "'self'",
107
+ "'none'",
108
+ "'unsafe-inline'",
109
+ "'unsafe-eval'",
110
+ "'wasm-unsafe-eval'",
111
+ "'strict-dynamic'",
112
+ "'unsafe-hashes'"
113
+ ];
114
+
115
+ /**
116
+ * `*`, `https:` and friends would silently disable the allowlist, and a `;`
117
+ * would inject an extra directive. Only concrete sources survive.
118
+ */
119
+ const SOURCE_PATTERN = /^(?:https?:\/\/[A-Za-z0-9._~%-]+(?::\d{1,5})?(?:\/[^\s;,'"]*)?|data:|blob:|filesystem:)$/;
120
+
121
+ function isSafeSource(source: string): boolean {
122
+ return ALLOWED_KEYWORDS.indexOf(source) !== -1 || SOURCE_PATTERN.test(source);
123
+ }
124
+
125
+ function cleanSources(raw: unknown): string[] {
126
+ if (!Array.isArray(raw)) return [];
127
+ const out: string[] = [];
128
+ for (const value of raw.slice(0, MAX_SOURCES)) {
129
+ if (typeof value !== 'string') continue;
130
+ const source = value.trim();
131
+ if (!source || source.length > MAX_SOURCE_LENGTH) continue;
132
+ if (!isSafeSource(source)) continue;
133
+ if (out.indexOf(source) === -1) out.push(source);
134
+ }
135
+ return out;
136
+ }
137
+
138
+ function unique(...lists: Array<string[] | undefined>): string[] {
139
+ const out: string[] = [];
140
+ for (const list of lists) {
141
+ if (!list) continue;
142
+ for (const value of list) {
143
+ if (value && out.indexOf(value) === -1) out.push(value);
144
+ }
145
+ }
146
+ return out;
147
+ }
148
+
149
+ /**
150
+ * Validate an author-supplied `previewCsp` option. Unknown modes fall back to
151
+ * `balanced`; invalid source entries are dropped rather than shipped.
152
+ */
153
+ export function normalizePreviewCspConfig(raw: unknown): NormalizedPreviewCsp {
154
+ if (typeof raw === 'string') return { mode: normalizeMode(raw), allow: {} };
155
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
156
+ return { mode: 'balanced', allow: {} };
157
+ }
158
+ const input = raw as PreviewCspConfig;
159
+ // Accept both the author-facing shape (`{ mode, scriptSrc }`) and the
160
+ // normalized shape (`{ mode, allow: { scriptSrc } }`) so callers can pass a
161
+ // stored `previewCsp` value straight back in.
162
+ const nested = (input as { allow?: unknown }).allow;
163
+ const sources = (nested && typeof nested === 'object' && !Array.isArray(nested))
164
+ ? nested as PreviewCspSources
165
+ : input;
166
+ const allow: PreviewCspSources = {};
167
+ for (const key of SOURCE_KEYS) {
168
+ const list = cleanSources(sources[key]);
169
+ if (list.length) allow[key] = list;
170
+ }
171
+ return { mode: normalizeMode(input.mode), allow };
172
+ }
173
+
174
+ function sourcesFor(mode: PreviewCspMode, allow: PreviewCspSources, key: keyof PreviewCspSources): string[] {
175
+ const preset = mode === 'custom' ? {} : PRESETS[mode];
176
+ // Clean here too: buildPreviewPolicy is public and must not splice unvalidated
177
+ // strings into the policy even when the caller skipped normalization.
178
+ return unique(preset[key], cleanSources(allow[key]));
179
+ }
180
+
181
+ /**
182
+ * Build the policy string for one preview document.
183
+ *
184
+ * `unsafe-inline`/`unsafe-eval` stay enabled on purpose: previews are arbitrary
185
+ * user code and inline import maps are part of how they run. Isolation comes
186
+ * from the iframe sandbox (opaque origin), not from the CSP.
187
+ */
188
+ export function buildPreviewPolicy(options: PreviewCspOptions = {}): string {
189
+ const mode = normalizeMode(options.mode);
190
+ const allow = options as PreviewCspSources;
191
+ const host = normalizeOrigin(options.hostOrigin);
192
+ // A `file://` preview has no usable origin; `'self'` is the least surprising
193
+ // fallback and simply blocks remote assets.
194
+ const self = host || "'self'";
195
+
196
+ const directive = (name: string, parts: string[]): string => `${name} ${unique(parts).join(' ')}`;
197
+
198
+ const script = (): string[] => [self, 'blob:', "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, 'scriptSrc'));
199
+ const style = (): string[] => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, 'styleSrc'));
200
+ const withData = (key: keyof PreviewCspSources): string[] => [self, 'data:', 'blob:'].concat(sourcesFor(mode, allow, key));
201
+
202
+ return [
203
+ directive('default-src', [self, 'data:', 'blob:']),
204
+ directive('base-uri', [self]),
205
+ "object-src 'none'",
206
+ directive('script-src', script()),
207
+ directive('style-src', style()),
208
+ directive('img-src', withData('imgSrc')),
209
+ directive('font-src', [self, 'data:'].concat(sourcesFor(mode, allow, 'fontSrc'))),
210
+ directive('connect-src', withData('connectSrc')),
211
+ directive('media-src', withData('mediaSrc')),
212
+ directive('worker-src', [self, 'blob:'].concat(sourcesFor(mode, allow, 'workerSrc'))),
213
+ directive('frame-src', withData('frameSrc')),
214
+ directive('form-action', [self]),
215
+ directive('frame-ancestors', [options.frameAncestors || "'self'"])
216
+ ].join('; ');
217
+ }
218
+
219
+ /**
220
+ * Network hosts a preview may reach, for display in the Web Preview toolbar.
221
+ * Returns remote origins only — the host origin and CSP keywords are omitted.
222
+ */
223
+ export function describePreviewNetwork(config: unknown): string[] {
224
+ const normalized = normalizePreviewCspConfig(config);
225
+ if (normalized.mode === 'strict') return [];
226
+ const preset = normalized.mode === 'custom' ? {} : PRESETS[normalized.mode];
227
+ const hosts: string[] = [];
228
+ for (const key of ['scriptSrc', 'connectSrc', 'imgSrc', 'styleSrc', 'fontSrc'] as Array<keyof PreviewCspSources>) {
229
+ for (const source of unique(preset[key], normalized.allow[key])) {
230
+ if (!/^https?:\/\//i.test(source)) continue;
231
+ let host: string;
232
+ try {
233
+ host = new URL(source).host;
234
+ } catch (_) {
235
+ continue;
236
+ }
237
+ if (hosts.indexOf(host) === -1) hosts.push(host);
238
+ }
239
+ }
240
+ return hosts;
241
+ }
242
+
243
+ /**
244
+ * Scripts injected into every preview document:
245
+ *
246
+ * 1. In-memory `localStorage`/`sessionStorage` — a sandboxed (opaque origin)
247
+ * document throws `SecurityError` on access, which breaks any preview that
248
+ * touches storage at module top level. In-memory equivalents keep the app
249
+ * running; sub-resource loading is unaffected.
250
+ * 2. A `securitypolicyviolation` reporter that forwards to the host via
251
+ * `postMessage`. The host validates `event.source` (the document origin is
252
+ * opaque, so `event.origin` is the string `"null"` and is not usable).
253
+ */
254
+ export function buildPreviewShims(): string {
255
+ return `<script ${PREVIEW_SHIM_MARKER}>
256
+ (function () {
257
+ 'use strict';
258
+ function memoryStorage() {
259
+ var data = new Map();
260
+ return {
261
+ getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
262
+ setItem: function (k, v) { data.set(String(k), String(v)); },
263
+ removeItem: function (k) { data.delete(String(k)); },
264
+ clear: function () { data.clear(); },
265
+ key: function (i) { return Array.from(data.keys())[i] || null; },
266
+ get length() { return data.size; }
267
+ };
268
+ }
269
+ function shim(name) {
270
+ var blocked = false;
271
+ try {
272
+ var existing = window[name];
273
+ if (existing) { existing.getItem('__codelab_probe__'); return; }
274
+ } catch (err) {
275
+ // Expected on an opaque origin: the accessor itself throws.
276
+ blocked = Boolean(err);
277
+ }
278
+ void blocked;
279
+ try {
280
+ Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
281
+ } catch (err) {
282
+ console.warn('[code-lab] preview: unable to shim ' + name, err);
283
+ }
284
+ }
285
+ shim('localStorage');
286
+ shim('sessionStorage');
287
+ document.addEventListener('securitypolicyviolation', function (event) {
288
+ try {
289
+ parent.postMessage({
290
+ type: 'codelab:preview-violation',
291
+ directive: event.effectiveDirective || event.violatedDirective || '',
292
+ blockedURI: event.blockedURI || '',
293
+ sourceFile: event.sourceFile || '',
294
+ line: event.lineNumber || 0
295
+ }, '*');
296
+ } catch (err) {
297
+ console.warn('[code-lab] preview: could not report CSP violation', err);
298
+ }
299
+ });
300
+ function serializeArg(arg) {
301
+ if (typeof arg !== 'object' || arg === null) return String(arg);
302
+ try {
303
+ return JSON.stringify(arg);
304
+ } catch (err) {
305
+ void err;
306
+ return '[Circular/Unserializable]';
307
+ }
308
+ }
309
+ ['log', 'warn', 'error', 'info'].forEach(function (level) {
310
+ var orig = console[level];
311
+ if (typeof orig !== 'function') return;
312
+ console[level] = function () {
313
+ var args = Array.prototype.slice.call(arguments);
314
+ try {
315
+ parent.postMessage({
316
+ type: 'codelab:preview-console',
317
+ level: level,
318
+ args: args.map(serializeArg)
319
+ }, '*');
320
+ } catch (err) {
321
+ void err;
322
+ }
323
+ return orig.apply(console, args);
324
+ };
325
+ });
326
+ function showPreviewErrorOverlay(msg, stack) {
327
+ try {
328
+ if (!document || !document.body) return;
329
+ var existing = document.getElementById('codelab-preview-error-overlay');
330
+ if (!existing) {
331
+ existing = document.createElement('div');
332
+ existing.id = 'codelab-preview-error-overlay';
333
+ existing.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:rgba(15,23,42,0.94);color:#f8fafc;font-family:ui-monospace,monospace;padding:24px;overflow:auto;';
334
+ document.body.appendChild(existing);
335
+ }
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);';
339
+ var header = document.createElement('div');
340
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
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);
349
+ var pre = document.createElement('pre');
350
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
351
+ pre.textContent = String(stack || msg || '');
352
+ existing.appendChild(topBar);
353
+ existing.appendChild(pre);
354
+ } catch (err) {
355
+ void err;
356
+ }
357
+ }
358
+ window.addEventListener('error', function (event) {
359
+ var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
360
+ var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
361
+ showPreviewErrorOverlay(msg, stack);
362
+ try {
363
+ parent.postMessage({
364
+ type: 'codelab:preview-error',
365
+ message: msg,
366
+ file: (event && event.filename) || null,
367
+ line: (event && event.lineno) || null,
368
+ col: (event && event.colno) || null,
369
+ stack: stack || null
370
+ }, '*');
371
+ } catch (err) {
372
+ void err;
373
+ }
374
+ });
375
+ window.addEventListener('unhandledrejection', function (event) {
376
+ var reason = event ? event.reason : null;
377
+ var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
378
+ var stack = reason && reason.stack ? String(reason.stack) : '';
379
+ showPreviewErrorOverlay(msg, stack);
380
+ try {
381
+ parent.postMessage({
382
+ type: 'codelab:preview-error',
383
+ message: msg,
384
+ file: null,
385
+ line: null,
386
+ col: null,
387
+ stack: stack || null
388
+ }, '*');
389
+ } catch (err) {
390
+ void err;
391
+ }
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; }
576
+ })();
577
+ </script>`;
578
+ }
579
+
580
+ /** Default export keeps the IIFE global (`CodeLabCsp`) shaped like the sources. */
581
+ export default {
582
+ buildPreviewPolicy,
583
+ buildPreviewShims,
584
+ describePreviewNetwork,
585
+ normalizePreviewCspConfig,
586
+ normalizeOrigin,
587
+ PREVIEW_SHIM_MARKER
588
+ };