@innovatorved/code-lab 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,331 @@
1
+ /**
2
+ * ============================================================
3
+ * @innovatorved/code-lab v0.1.8 — Standalone Browser Code IDE & Virtual Runtime
4
+ * ============================================================
5
+ * Features:
6
+ * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
+ * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
+ * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
+ * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
+ * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
+ * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
12
+ * - Modular Opt-In Guided Lab Extension (stepper, hints, solution diff, JS/TS switcher)
13
+ * - Zero-Auth Public GitHub Repository Cloning (git clone, workbench.cloneRepo, <code-lab repo="...">)
14
+ * - Third-Party Imperative SDK (getFiles, setFiles, getFile, setFile, cloneRepo, on, off, use, exportWorkspace)
15
+ * ============================================================
16
+ */
17
+
18
+ var CodeLabCsp = (() => {
19
+ var __defProp = Object.defineProperty;
20
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
21
+ var __getOwnPropNames = Object.getOwnPropertyNames;
22
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
23
+ var __export = (target, all) => {
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+
37
+ // src/csp.ts
38
+ var csp_exports = {};
39
+ __export(csp_exports, {
40
+ PREVIEW_SHIM_MARKER: () => PREVIEW_SHIM_MARKER,
41
+ buildPreviewPolicy: () => buildPreviewPolicy,
42
+ buildPreviewShims: () => buildPreviewShims,
43
+ default: () => csp_default,
44
+ describePreviewNetwork: () => describePreviewNetwork,
45
+ normalizeOrigin: () => normalizeOrigin,
46
+ normalizePreviewCspConfig: () => normalizePreviewCspConfig
47
+ });
48
+ var IMPORT_MAP_CDNS = ["https://cdn.jsdelivr.net", "https://esm.sh"];
49
+ var FONT_CDNS = ["https://cdn.jsdelivr.net", "https://fonts.gstatic.com"];
50
+ var PRESETS = {
51
+ strict: {},
52
+ balanced: {
53
+ scriptSrc: IMPORT_MAP_CDNS.slice(),
54
+ styleSrc: ["https://cdn.jsdelivr.net", "https://fonts.googleapis.com"],
55
+ fontSrc: FONT_CDNS.slice(),
56
+ connectSrc: IMPORT_MAP_CDNS.slice(),
57
+ imgSrc: ["https://cdn.jsdelivr.net"]
58
+ }
59
+ };
60
+ var SOURCE_KEYS = [
61
+ "scriptSrc",
62
+ "styleSrc",
63
+ "imgSrc",
64
+ "fontSrc",
65
+ "connectSrc",
66
+ "mediaSrc",
67
+ "workerSrc",
68
+ "frameSrc"
69
+ ];
70
+ var MAX_SOURCES = 64;
71
+ var MAX_SOURCE_LENGTH = 512;
72
+ var PREVIEW_SHIM_MARKER = "data-codelab-preview-shims";
73
+ function normalizeOrigin(raw) {
74
+ if (raw === null || raw === void 0 || raw === "") return null;
75
+ try {
76
+ const parsed = new URL(String(raw));
77
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
78
+ return parsed.origin;
79
+ } catch (_) {
80
+ return null;
81
+ }
82
+ }
83
+ function normalizeMode(raw) {
84
+ if (raw === "strict" || raw === "custom") return raw;
85
+ return "balanced";
86
+ }
87
+ var ALLOWED_KEYWORDS = [
88
+ "'self'",
89
+ "'none'",
90
+ "'unsafe-inline'",
91
+ "'unsafe-eval'",
92
+ "'wasm-unsafe-eval'",
93
+ "'strict-dynamic'",
94
+ "'unsafe-hashes'"
95
+ ];
96
+ var SOURCE_PATTERN = /^(?:https?:\/\/[A-Za-z0-9._~%-]+(?::\d{1,5})?(?:\/[^\s;,'"]*)?|data:|blob:|filesystem:)$/;
97
+ function isSafeSource(source) {
98
+ return ALLOWED_KEYWORDS.indexOf(source) !== -1 || SOURCE_PATTERN.test(source);
99
+ }
100
+ function cleanSources(raw) {
101
+ if (!Array.isArray(raw)) return [];
102
+ const out = [];
103
+ for (const value of raw.slice(0, MAX_SOURCES)) {
104
+ if (typeof value !== "string") continue;
105
+ const source = value.trim();
106
+ if (!source || source.length > MAX_SOURCE_LENGTH) continue;
107
+ if (!isSafeSource(source)) continue;
108
+ if (out.indexOf(source) === -1) out.push(source);
109
+ }
110
+ return out;
111
+ }
112
+ function unique(...lists) {
113
+ const out = [];
114
+ for (const list of lists) {
115
+ if (!list) continue;
116
+ for (const value of list) {
117
+ if (value && out.indexOf(value) === -1) out.push(value);
118
+ }
119
+ }
120
+ return out;
121
+ }
122
+ function normalizePreviewCspConfig(raw) {
123
+ if (typeof raw === "string") return { mode: normalizeMode(raw), allow: {} };
124
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
125
+ return { mode: "balanced", allow: {} };
126
+ }
127
+ const input = raw;
128
+ const nested = input.allow;
129
+ const sources = nested && typeof nested === "object" && !Array.isArray(nested) ? nested : input;
130
+ const allow = {};
131
+ for (const key of SOURCE_KEYS) {
132
+ const list = cleanSources(sources[key]);
133
+ if (list.length) allow[key] = list;
134
+ }
135
+ return { mode: normalizeMode(input.mode), allow };
136
+ }
137
+ function sourcesFor(mode, allow, key) {
138
+ const preset = mode === "custom" ? {} : PRESETS[mode];
139
+ return unique(preset[key], cleanSources(allow[key]));
140
+ }
141
+ function buildPreviewPolicy(options = {}) {
142
+ const mode = normalizeMode(options.mode);
143
+ const allow = options;
144
+ const host = normalizeOrigin(options.hostOrigin);
145
+ const self = host || "'self'";
146
+ const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
147
+ const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
148
+ const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
149
+ const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
150
+ return [
151
+ directive("default-src", [self, "data:", "blob:"]),
152
+ directive("base-uri", [self]),
153
+ "object-src 'none'",
154
+ directive("script-src", script()),
155
+ directive("style-src", style()),
156
+ directive("img-src", withData("imgSrc")),
157
+ directive("font-src", [self, "data:"].concat(sourcesFor(mode, allow, "fontSrc"))),
158
+ directive("connect-src", withData("connectSrc")),
159
+ directive("media-src", withData("mediaSrc")),
160
+ directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
161
+ directive("frame-src", withData("frameSrc")),
162
+ directive("form-action", [self]),
163
+ directive("frame-ancestors", [options.frameAncestors || "'self'"])
164
+ ].join("; ");
165
+ }
166
+ function describePreviewNetwork(config) {
167
+ const normalized = normalizePreviewCspConfig(config);
168
+ if (normalized.mode === "strict") return [];
169
+ const preset = normalized.mode === "custom" ? {} : PRESETS[normalized.mode];
170
+ const hosts = [];
171
+ for (const key of ["scriptSrc", "connectSrc", "imgSrc", "styleSrc", "fontSrc"]) {
172
+ for (const source of unique(preset[key], normalized.allow[key])) {
173
+ if (!/^https?:\/\//i.test(source)) continue;
174
+ let host;
175
+ try {
176
+ host = new URL(source).host;
177
+ } catch (_) {
178
+ continue;
179
+ }
180
+ if (hosts.indexOf(host) === -1) hosts.push(host);
181
+ }
182
+ }
183
+ return hosts;
184
+ }
185
+ function buildPreviewShims() {
186
+ return `<script ${PREVIEW_SHIM_MARKER}>
187
+ (function () {
188
+ 'use strict';
189
+ function memoryStorage() {
190
+ var data = new Map();
191
+ return {
192
+ getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
193
+ setItem: function (k, v) { data.set(String(k), String(v)); },
194
+ removeItem: function (k) { data.delete(String(k)); },
195
+ clear: function () { data.clear(); },
196
+ key: function (i) { return Array.from(data.keys())[i] || null; },
197
+ get length() { return data.size; }
198
+ };
199
+ }
200
+ function shim(name) {
201
+ var blocked = false;
202
+ try {
203
+ var existing = window[name];
204
+ if (existing) { existing.getItem('__codelab_probe__'); return; }
205
+ } catch (err) {
206
+ // Expected on an opaque origin: the accessor itself throws.
207
+ blocked = Boolean(err);
208
+ }
209
+ void blocked;
210
+ try {
211
+ Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
212
+ } catch (err) {
213
+ console.warn('[code-lab] preview: unable to shim ' + name, err);
214
+ }
215
+ }
216
+ shim('localStorage');
217
+ shim('sessionStorage');
218
+ document.addEventListener('securitypolicyviolation', function (event) {
219
+ try {
220
+ parent.postMessage({
221
+ type: 'codelab:preview-violation',
222
+ directive: event.effectiveDirective || event.violatedDirective || '',
223
+ blockedURI: event.blockedURI || '',
224
+ sourceFile: event.sourceFile || '',
225
+ line: event.lineNumber || 0
226
+ }, '*');
227
+ } catch (err) {
228
+ console.warn('[code-lab] preview: could not report CSP violation', err);
229
+ }
230
+ });
231
+ function serializeArg(arg) {
232
+ if (typeof arg !== 'object' || arg === null) return String(arg);
233
+ try {
234
+ return JSON.stringify(arg);
235
+ } catch (err) {
236
+ void err;
237
+ return '[Circular/Unserializable]';
238
+ }
239
+ }
240
+ ['log', 'warn', 'error', 'info'].forEach(function (level) {
241
+ var orig = console[level];
242
+ if (typeof orig !== 'function') return;
243
+ console[level] = function () {
244
+ var args = Array.prototype.slice.call(arguments);
245
+ try {
246
+ parent.postMessage({
247
+ type: 'codelab:preview-console',
248
+ level: level,
249
+ args: args.map(serializeArg)
250
+ }, '*');
251
+ } catch (err) {
252
+ void err;
253
+ }
254
+ return orig.apply(console, args);
255
+ };
256
+ });
257
+ function showPreviewErrorOverlay(msg, stack) {
258
+ try {
259
+ if (!document || !document.body) return;
260
+ var existing = document.getElementById('codelab-preview-error-overlay');
261
+ if (!existing) {
262
+ existing = document.createElement('div');
263
+ existing.id = 'codelab-preview-error-overlay';
264
+ 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;';
265
+ document.body.appendChild(existing);
266
+ }
267
+ existing.textContent = '';
268
+ var header = document.createElement('div');
269
+ header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
270
+ header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
271
+ var pre = document.createElement('pre');
272
+ pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
273
+ pre.textContent = String(stack || msg || '');
274
+ existing.appendChild(header);
275
+ existing.appendChild(pre);
276
+ } catch (err) {
277
+ void err;
278
+ }
279
+ }
280
+ window.addEventListener('error', function (event) {
281
+ var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
282
+ var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
283
+ showPreviewErrorOverlay(msg, stack);
284
+ try {
285
+ parent.postMessage({
286
+ type: 'codelab:preview-error',
287
+ message: msg,
288
+ file: (event && event.filename) || null,
289
+ line: (event && event.lineno) || null,
290
+ col: (event && event.colno) || null,
291
+ stack: stack || null
292
+ }, '*');
293
+ } catch (err) {
294
+ void err;
295
+ }
296
+ });
297
+ window.addEventListener('unhandledrejection', function (event) {
298
+ var reason = event ? event.reason : null;
299
+ var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
300
+ var stack = reason && reason.stack ? String(reason.stack) : '';
301
+ showPreviewErrorOverlay(msg, stack);
302
+ try {
303
+ parent.postMessage({
304
+ type: 'codelab:preview-error',
305
+ message: msg,
306
+ file: null,
307
+ line: null,
308
+ col: null,
309
+ stack: stack || null
310
+ }, '*');
311
+ } catch (err) {
312
+ void err;
313
+ }
314
+ });
315
+ })();
316
+ <\/script>`;
317
+ }
318
+ var csp_default = {
319
+ buildPreviewPolicy,
320
+ buildPreviewShims,
321
+ describePreviewNetwork,
322
+ normalizePreviewCspConfig,
323
+ normalizeOrigin,
324
+ PREVIEW_SHIM_MARKER
325
+ };
326
+ return __toCommonJS(csp_exports);
327
+ })();
328
+
1
329
  /**
2
330
  * @innovatorved/code-lab — Web Preview Virtual Loopback Service Worker (Milestone 3)
3
331
  * ============================================================================
@@ -8,6 +336,10 @@
8
336
  * This enables "pop out to tab" Web Preview for virtual HTTP / Bun servers that
9
337
  * exist only inside the workbench's in-memory runtime (no real OS socket).
10
338
  *
339
+ * The Content-Security-Policy, the storage shims and the violation reporter all
340
+ * come from `src/csp.ts`, which the build prepends to this file. The workbench
341
+ * embeds the same module, so the two can never drift.
342
+ *
11
343
  * Zero dependencies. Plain Service Worker script (no module imports) so it can
12
344
  * be registered directly from any host origin.
13
345
  */
@@ -16,49 +348,32 @@
16
348
 
17
349
  const PREVIEW_PREFIX = '/__preview/';
18
350
  const DISPATCH_TIMEOUT_MS = 15000;
351
+ const MAX_CONFIG_LENGTH = 8192;
19
352
 
20
- // Content-Security-Policy applied to every HTML preview response.
21
- //
22
- // The preview is untrusted user code. Inline/eval are allowed because previews
23
- // are built from arbitrary user source, but network access is restricted to
24
- // the preview origin plus data:/blob: so a preview cannot exfiltrate host data
25
- // to a third party. Keep this string in sync with PREVIEW_CSP in workbench.js.
26
- const PREVIEW_CSP = [
27
- "default-src 'self' data: blob:",
28
- "base-uri 'self'",
29
- "object-src 'none'",
30
- "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
31
- "style-src 'self' 'unsafe-inline'",
32
- "img-src 'self' data: blob:",
33
- "font-src 'self' data:",
34
- "connect-src 'self' data: blob:",
35
- "media-src 'self' data: blob:",
36
- "worker-src 'self' blob:",
37
- "frame-src 'self' data: blob:",
38
- "form-action 'self'",
39
- "frame-ancestors 'self'"
40
- ].join('; ');
353
+ // Policy configured by the workbench via postMessage. The worker cannot read the
354
+ // host's options, so the host pushes the resolved policy after registering.
355
+ let configuredCsp = null;
41
356
 
42
- function injectPreviewHead(html, port) {
43
- const tags = [];
44
- if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
45
- tags.push(`<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">`);
46
- }
47
- if (!/<base\b/i.test(html)) {
48
- tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
49
- }
50
- if (tags.length === 0) return html;
357
+ function cspModule() {
358
+ // `CodeLabCsp` is declared by the prepended csp bundle (src/csp.ts).
359
+ return typeof CodeLabCsp !== 'undefined' ? CodeLabCsp : null;
360
+ }
51
361
 
52
- const injection = tags.join('');
53
- if (/<head\b[^>]*>/i.test(html)) {
54
- return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
55
- }
56
- if (/<html\b[^>]*>/i.test(html)) {
57
- return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
58
- }
59
- return `<head>${injection}</head>${html}`;
362
+ function previewPolicy() {
363
+ if (configuredCsp) return configuredCsp;
364
+ const csp = cspModule();
365
+ if (!csp) return "default-src 'self'; object-src 'none'";
366
+ // The workbench pushes its resolved policy on registration, so this branch
367
+ // only runs in the brief window before that message arrives. Use the
368
+ // documented default (`balanced`) rather than a stricter one, otherwise the
369
+ // very first preview of a CDN-based app can be blocked by a race.
370
+ return csp.buildPreviewPolicy({ hostOrigin: self.location.origin, mode: 'balanced' });
60
371
  }
61
372
 
373
+ function previewShims() {
374
+ const csp = cspModule();
375
+ return csp ? csp.buildPreviewShims() : '';
376
+ }
62
377
 
63
378
  self.addEventListener('install', () => {
64
379
  self.skipWaiting();
@@ -68,6 +383,25 @@ self.addEventListener('activate', (event) => {
68
383
  event.waitUntil(self.clients.claim());
69
384
  });
70
385
 
386
+ self.addEventListener('message', (event) => {
387
+ const data = event && event.data;
388
+ if (!data || data.type !== 'codelab:config') return;
389
+ const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
390
+ if (!csp || csp.length > MAX_CONFIG_LENGTH) return;
391
+ configuredCsp = csp;
392
+ // Acknowledge so the host can wait for confirmation before loading a frame.
393
+ try {
394
+ if (event.ports && event.ports[0]) {
395
+ event.ports[0].postMessage({ type: 'codelab:config-ready' });
396
+ } else if (event.source && typeof event.source.postMessage === 'function') {
397
+ event.source.postMessage({ type: 'codelab:config-ready' });
398
+ }
399
+ } catch (err) {
400
+ // The client may have navigated away between postMessage and reply.
401
+ console.warn('[code-lab] preview-sw: config acknowledgement failed', err);
402
+ }
403
+ });
404
+
71
405
  function parsePreviewPath(pathname) {
72
406
  const match = pathname.match(/^\/__preview\/(\d+)(\/.*)?$/);
73
407
  if (!match) return null;
@@ -75,8 +409,9 @@ function parsePreviewPath(pathname) {
75
409
  }
76
410
 
77
411
  function previewErrorResponse(status, title, message) {
412
+ const csp = previewPolicy();
78
413
  const body = `<!doctype html><meta charset="utf-8">` +
79
- `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
414
+ `<meta http-equiv="Content-Security-Policy" content="${csp}">` +
80
415
  `<title>${title}</title>` +
81
416
  `<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
82
417
  `<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
@@ -84,12 +419,36 @@ function previewErrorResponse(status, title, message) {
84
419
  status,
85
420
  headers: {
86
421
  'Content-Type': 'text/html; charset=utf-8',
87
- 'Content-Security-Policy': PREVIEW_CSP,
422
+ 'Content-Security-Policy': csp,
88
423
  'X-Content-Type-Options': 'nosniff'
89
424
  }
90
425
  });
91
426
  }
92
427
 
428
+ /** Inject the policy, a base URL and the sandbox shims into an HTML response. */
429
+ function injectPreviewHead(html, port) {
430
+ const csp = previewPolicy();
431
+ const shims = previewShims();
432
+ const tags = [];
433
+ const hasCsp = /<meta[^>]+http-equiv=["']?content-security-policy/i.test(html);
434
+ const hasBase = /<base\b/i.test(html);
435
+ const hasShims = html.indexOf('data-codelab-preview-shims') !== -1;
436
+
437
+ if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
438
+ if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
439
+ if (!hasShims && shims) tags.push(shims);
440
+ if (tags.length === 0) return html;
441
+
442
+ const injection = tags.join('');
443
+ if (/<head\b[^>]*>/i.test(html)) {
444
+ return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
445
+ }
446
+ if (/<html\b[^>]*>/i.test(html)) {
447
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
448
+ }
449
+ return `<head>${injection}</head>${html}`;
450
+ }
451
+
93
452
  async function proxyVirtualRequest(event, port, targetPath) {
94
453
  const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
95
454
  if (!clients || !clients.length) {
@@ -110,13 +469,18 @@ async function proxyVirtualRequest(event, port, targetPath) {
110
469
  for (const [key, value] of request.headers.entries()) {
111
470
  headers[key.toLowerCase()] = value;
112
471
  }
113
- } catch (_) {}
472
+ } catch (err) {
473
+ // Opaque or unsupported header collection; forward without request headers.
474
+ console.warn('[code-lab] preview-sw: could not read request headers', err);
475
+ }
114
476
 
115
477
  let body = null;
116
478
  if (!['GET', 'HEAD'].includes(method)) {
117
479
  try {
118
480
  body = await request.arrayBuffer();
119
- } catch (_) {}
481
+ } catch (err) {
482
+ console.warn('[code-lab] preview-sw: could not read request body', err);
483
+ }
120
484
  }
121
485
 
122
486
  const response = await new Promise((resolve) => {
@@ -151,11 +515,11 @@ async function proxyVirtualRequest(event, port, targetPath) {
151
515
  const responseHeaders = new Headers((response && response.headers) || {});
152
516
  const contentType = responseHeaders.get('content-type') || '';
153
517
 
154
- // Inject a CSP and a <base> so relative asset URLs in HTML responses resolve
155
- // under the `/__preview/:port/` namespace rather than the host document root.
518
+ // Inject the policy and a <base> so relative asset URLs in HTML responses
519
+ // resolve under the `/__preview/:port/` namespace rather than the host root.
156
520
  if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
157
521
  responseBody = injectPreviewHead(responseBody, port);
158
- responseHeaders.set('Content-Security-Policy', PREVIEW_CSP);
522
+ responseHeaders.set('Content-Security-Policy', previewPolicy());
159
523
  responseHeaders.set('X-Content-Type-Options', 'nosniff');
160
524
  }
161
525
 
@@ -170,7 +534,9 @@ self.addEventListener('fetch', (event) => {
170
534
  let url;
171
535
  try {
172
536
  url = new URL(event.request.url);
173
- } catch (_) {
537
+ } catch (err) {
538
+ // Non-standard request URL; let the network handle it.
539
+ console.warn('[code-lab] preview-sw: unparsable request URL', err);
174
540
  return;
175
541
  }
176
542