@innovatorved/code-lab 0.1.6 → 0.1.7

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/preview-sw.js CHANGED
@@ -17,6 +17,49 @@
17
17
  const PREVIEW_PREFIX = '/__preview/';
18
18
  const DISPATCH_TIMEOUT_MS = 15000;
19
19
 
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('; ');
41
+
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;
51
+
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}`;
60
+ }
61
+
62
+
20
63
  self.addEventListener('install', () => {
21
64
  self.skipWaiting();
22
65
  });
@@ -32,12 +75,18 @@ function parsePreviewPath(pathname) {
32
75
  }
33
76
 
34
77
  function previewErrorResponse(status, title, message) {
35
- const body = `<!doctype html><meta charset="utf-8"><title>${title}</title>` +
78
+ const body = `<!doctype html><meta charset="utf-8">` +
79
+ `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
80
+ `<title>${title}</title>` +
36
81
  `<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
37
82
  `<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
38
83
  return new Response(body, {
39
84
  status,
40
- headers: { 'Content-Type': 'text/html; charset=utf-8' }
85
+ headers: {
86
+ 'Content-Type': 'text/html; charset=utf-8',
87
+ 'Content-Security-Policy': PREVIEW_CSP,
88
+ 'X-Content-Type-Options': 'nosniff'
89
+ }
41
90
  });
42
91
  }
43
92
 
@@ -102,13 +151,12 @@ async function proxyVirtualRequest(event, port, targetPath) {
102
151
  const responseHeaders = new Headers((response && response.headers) || {});
103
152
  const contentType = responseHeaders.get('content-type') || '';
104
153
 
105
- // Inject a <base> so relative asset URLs in HTML responses resolve under the
106
- // `/__preview/:port/` namespace rather than the host document root.
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.
107
156
  if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
108
- const baseTag = `<base href="${PREVIEW_PREFIX}${port}/">`;
109
- if (!/<base\b/i.test(responseBody) && /<head\b/i.test(responseBody)) {
110
- responseBody = responseBody.replace(/<head\b[^>]*>/i, (match) => match + baseTag);
111
- }
157
+ responseBody = injectPreviewHead(responseBody, port);
158
+ responseHeaders.set('Content-Security-Policy', PREVIEW_CSP);
159
+ responseHeaders.set('X-Content-Type-Options', 'nosniff');
112
160
  }
113
161
 
114
162
  return new Response(responseBody, {
package/src/runtime.ts CHANGED
@@ -4898,8 +4898,8 @@ function __initVirtualRuntime(rootScope) {
4898
4898
 
4899
4899
  if ((hasESM || isTS) && !keepEsm) {
4900
4900
  // Convert ES module imports (including multi-line `{ ... }`)
4901
- code = code.replace(/\bimport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, 'const $1 = require($2);');
4902
- code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4901
+ code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
4902
+ code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4903
4903
  const cleaned = specifiers
4904
4904
  .split(',')
4905
4905
  .map((s) => s.trim())
@@ -4910,7 +4910,7 @@ function __initVirtualRuntime(rootScope) {
4910
4910
  return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
4911
4911
  (cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
4912
4912
  });
4913
- code = code.replace(/\bimport\s+\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, specifiers, mod) => {
4913
+ code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
4914
4914
  const cleaned = specifiers
4915
4915
  .split(',')
4916
4916
  .map((s) => s.trim())
@@ -4933,11 +4933,11 @@ function __initVirtualRuntime(rootScope) {
4933
4933
  let defaultExportName = null;
4934
4934
  let hasEsmExport = false;
4935
4935
 
4936
- code = code.replace(/\bexport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, (_, ns, mod) => {
4936
+ code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
4937
4937
  hasEsmExport = true;
4938
4938
  return `exports.${ns} = require(${mod.trim()});`;
4939
4939
  });
4940
- code = code.replace(/\bexport\s+\*\s+from\s+([^\n;]+);?/gm, (_, mod) => {
4940
+ code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
4941
4941
  hasEsmExport = true;
4942
4942
  return `Object.assign(exports, require(${mod.trim()}));`;
4943
4943
  });
@@ -4960,7 +4960,7 @@ function __initVirtualRuntime(rootScope) {
4960
4960
  exportedNames.push(name);
4961
4961
  return `${kw} ${name}`;
4962
4962
  });
4963
- code = code.replace(/\bexport\s+\{([^}]+)\}\s+from\s+([^\n;]+);?/gm, (_, list, mod) => {
4963
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
4964
4964
  hasEsmExport = true;
4965
4965
  const mTrim = mod.trim();
4966
4966
  return list.split(',').map((item) => {
@@ -4972,7 +4972,7 @@ function __initVirtualRuntime(rootScope) {
4972
4972
  return `exports.${exported} = require(${mTrim}).${local};`;
4973
4973
  }).join(' ');
4974
4974
  });
4975
- code = code.replace(/\bexport\s+\{([^}]+)\}\s*;?/gm, (_, list) => {
4975
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
4976
4976
  hasEsmExport = true;
4977
4977
  return list.split(',').map((item) => {
4978
4978
  const trimmed = item.trim();
@@ -5047,9 +5047,9 @@ function __initVirtualRuntime(rootScope) {
5047
5047
  // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
5048
5048
  // preloadNpmPackages(files, existingCache) // package-text cache (Map)
5049
5049
  // preloadNpmPackages(files, existingCache, onProgress)
5050
- const isCacheLike = (v: any) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
5051
- let onProgress: any = null;
5052
- let existingCache: any = _npmPackageCache;
5050
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
5051
+ let onProgress = null;
5052
+ let existingCache = _npmPackageCache;
5053
5053
  if (typeof secondArg === 'function') onProgress = secondArg;
5054
5054
  else if (isCacheLike(secondArg)) existingCache = secondArg;
5055
5055
  if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
@@ -5099,14 +5099,14 @@ function __initVirtualRuntime(rootScope) {
5099
5099
  if (typeof fetch === 'function') {
5100
5100
  let pass = 0;
5101
5101
  while (pass < 6) {
5102
- const pending: string[] = [];
5102
+ const pending = [];
5103
5103
  for (const pkg of specs) {
5104
- if (!_npmMetadataCache.has(pkg)) pending.push(pkg as string);
5104
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
5105
5105
  }
5106
5106
  if (pending.length === 0) break;
5107
5107
  pass++;
5108
5108
  await Promise.all(pending.map(async (pkg) => {
5109
- let deps: string[] = [];
5109
+ let deps = [];
5110
5110
  try {
5111
5111
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
5112
5112
  if (res && res.ok) {
@@ -7702,20 +7702,20 @@ function __initVirtualRuntime(rootScope) {
7702
7702
  }
7703
7703
  }
7704
7704
 
7705
- function raceWithAbort<T = any>(promise: Promise<T>): Promise<T | undefined> {
7706
- if (!promise || typeof (promise as any).then !== 'function') {
7707
- return Promise.resolve(promise as any);
7705
+ function raceWithAbort(promise) {
7706
+ if (!promise || typeof promise.then !== 'function') {
7707
+ return Promise.resolve(promise);
7708
7708
  }
7709
7709
  if (hasExited || isSigintAborted || Boolean(signal && signal.aborted)) {
7710
7710
  if (!hasExited) handleSigint();
7711
- return Promise.resolve(undefined);
7711
+ return Promise.resolve();
7712
7712
  }
7713
7713
 
7714
7714
  // Absorb late rejections after abort to avoid unhandled promise rejection warnings
7715
- (promise as any).catch(() => {});
7715
+ promise.catch(() => {});
7716
7716
 
7717
- return new Promise<T | undefined>((resolve, reject) => {
7718
- let timer: any = null;
7717
+ return new Promise((resolve, reject) => {
7718
+ let timer = null;
7719
7719
  let settled = false;
7720
7720
 
7721
7721
  const cleanup = () => {
@@ -7735,7 +7735,7 @@ function __initVirtualRuntime(rootScope) {
7735
7735
  const onAbort = () => {
7736
7736
  cleanup();
7737
7737
  handleSigint();
7738
- resolve(undefined);
7738
+ resolve();
7739
7739
  };
7740
7740
 
7741
7741
  if (signal) {
@@ -7750,7 +7750,7 @@ function __initVirtualRuntime(rootScope) {
7750
7750
  if (remainingMs > 0 && Number.isFinite(remainingMs)) {
7751
7751
  timer = setTimeout(() => {
7752
7752
  cleanup();
7753
- resolve(undefined);
7753
+ resolve();
7754
7754
  }, remainingMs);
7755
7755
  if (timer && typeof timer.unref === 'function') {
7756
7756
  timer.unref();
@@ -7758,11 +7758,11 @@ function __initVirtualRuntime(rootScope) {
7758
7758
  }
7759
7759
 
7760
7760
  promise.then(
7761
- (val: any) => {
7761
+ (val) => {
7762
7762
  cleanup();
7763
7763
  resolve(val);
7764
7764
  },
7765
- (err: any) => {
7765
+ (err) => {
7766
7766
  cleanup();
7767
7767
  reject(err);
7768
7768
  }
@@ -7995,11 +7995,12 @@ function __workerMessageLoop(workerScope) {
7995
7995
  };
7996
7996
  }
7997
7997
 
7998
- const _hostRuntime: any = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
7999
-
8000
- _hostRuntime.createWorkerRuntimeSource = function createWorkerRuntimeSource() {
7998
+ function createWorkerRuntimeSource() {
8001
7999
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
8002
- };
8000
+ }
8001
+
8002
+ const _hostRuntime = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
8003
+ _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
8003
8004
 
8004
8005
  let _cachedWorkerUrl = null;
8005
8006
  let _warmWorker = null;
@@ -8008,7 +8009,7 @@ const _activeWorkerJobs = new Map();
8008
8009
 
8009
8010
  function _ensureWorkerUrl() {
8010
8011
  if (!_cachedWorkerUrl) {
8011
- const blob = new Blob([_hostRuntime.createWorkerRuntimeSource()], { type: 'application/javascript' });
8012
+ const blob = new Blob([createWorkerRuntimeSource()], { type: 'application/javascript' });
8012
8013
  _cachedWorkerUrl = URL.createObjectURL(blob);
8013
8014
  }
8014
8015
  return _cachedWorkerUrl;
@@ -8228,54 +8229,43 @@ if (typeof module !== 'undefined' && module.exports) {
8228
8229
  }
8229
8230
 
8230
8231
 
8231
- export interface RuntimeExecutionResult {
8232
- ok: boolean;
8233
- exitCode: number;
8234
- durationMs: number;
8235
- stdout: string;
8236
- stderr: string;
8237
- testResults: any[];
8238
- fsSnapshot: any[];
8239
- httpTrace: any[];
8240
- error?: { message: string; stack?: string };
8241
- outputTruncated?: boolean;
8242
- replValue?: any;
8243
- cancelled?: boolean;
8244
- testSummary?: {
8245
- total: number;
8246
- passed: number;
8247
- failed: number;
8248
- };
8249
- }
8250
-
8251
- export const VirtualBuffer: any = _hostRuntime.VirtualBuffer;
8252
- export const VirtualCrypto: any = _hostRuntime.VirtualCrypto;
8253
- export const VirtualZlib: any = _hostRuntime.VirtualZlib;
8254
- export const VirtualPath: any = _hostRuntime.VirtualPath;
8255
- export const VirtualOs: any = _hostRuntime.VirtualOs;
8256
- export const VirtualAssert: any = _hostRuntime.VirtualAssert;
8257
- export const EventEmitter: any = _hostRuntime.EventEmitter;
8258
- export const VirtualUtil: any = _hostRuntime.VirtualUtil;
8259
- export const VirtualUrl: any = _hostRuntime.VirtualUrl;
8260
- export const VirtualQuerystring: any = _hostRuntime.VirtualQuerystring;
8261
- export const VirtualStream: any = _hostRuntime.VirtualStream;
8262
- export const VirtualStreamPromises: any = _hostRuntime.VirtualStreamPromises;
8263
- export const VirtualStringDecoder: any = _hostRuntime.VirtualStringDecoder;
8264
- export const VirtualDns: any = _hostRuntime.VirtualDns;
8265
- export const createVirtualFs: (options?: any) => any = _hostRuntime.createVirtualFs;
8266
- export const createVirtualHttp: (portTable?: any, vfs?: any) => any = _hostRuntime.createVirtualHttp;
8267
- export const createVirtualNet: (portTable?: any) => any = _hostRuntime.createVirtualNet;
8268
- export const transpileTS: (code: string, filename?: string) => string = _hostRuntime.transpileTS;
8269
- export const transpileForBrowser: (source: string, filename?: string) => string = _hostRuntime.transpileForBrowser;
8232
+ // ── TypeScript module surface (stripped from browser bundles) ──────────────
8233
+ // The implementation above is a UMD script that attaches itself to the global
8234
+ // object. These aliases give TypeScript consumers named exports without
8235
+ // duplicating the implementation. tools/bundle.js removes this footer before
8236
+ // concatenating the script into the browser bundle.
8237
+ const _runtimeApi: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabRuntime : undefined)
8238
+ || (typeof module !== 'undefined' && module.exports ? module.exports : {});
8239
+
8240
+ export const VirtualBuffer: any = _runtimeApi.VirtualBuffer;
8241
+ export const VirtualCrypto: any = _runtimeApi.VirtualCrypto;
8242
+ export const VirtualZlib: any = _runtimeApi.VirtualZlib;
8243
+ export const VirtualPath: any = _runtimeApi.VirtualPath;
8244
+ export const VirtualOs: any = _runtimeApi.VirtualOs;
8245
+ export const VirtualAssert: any = _runtimeApi.VirtualAssert;
8246
+ export const EventEmitter: any = _runtimeApi.EventEmitter;
8247
+ export const VirtualUtil: any = _runtimeApi.VirtualUtil;
8248
+ export const VirtualUrl: any = _runtimeApi.VirtualUrl;
8249
+ export const VirtualQuerystring: any = _runtimeApi.VirtualQuerystring;
8250
+ export const VirtualStream: any = _runtimeApi.VirtualStream;
8251
+ export const VirtualStreamPromises: any = _runtimeApi.VirtualStreamPromises;
8252
+ export const VirtualStringDecoder: any = _runtimeApi.VirtualStringDecoder;
8253
+ export const VirtualDns: any = _runtimeApi.VirtualDns;
8254
+ export const createVirtualFs: (options?: any) => any = _runtimeApi.createVirtualFs;
8255
+ export const createVirtualHttp: (portTable?: any, vfs?: any) => any = _runtimeApi.createVirtualHttp;
8256
+ export const createVirtualNet: (portTable?: any) => any = _runtimeApi.createVirtualNet;
8257
+ export const transpileTS: (code: string, filename?: string) => string = _runtimeApi.transpileTS;
8258
+ export const transpileForBrowser: (source: string, filename?: string) => string = _runtimeApi.transpileForBrowser;
8270
8259
  export const preloadNpmPackages: (
8271
8260
  files?: Record<string, any>,
8272
8261
  onProgressOrCache?: ((pkg: string) => void) | Map<string, string>,
8273
8262
  onProgress?: (pkg: string) => void
8274
- ) => Promise<Record<string, string>> = _hostRuntime.preloadNpmPackages;
8275
- export const createVirtualPortTable: () => any = _hostRuntime.createVirtualPortTable;
8276
- export const executeInVirtualRuntime: (options?: any) => Promise<RuntimeExecutionResult> = _hostRuntime.executeInVirtualRuntime;
8277
- export const createWorkerRuntimeSource: () => string = _hostRuntime.createWorkerRuntimeSource;
8278
- export const cancelWorkerExecution: (reason?: string, instanceId?: string) => boolean = _hostRuntime.cancelWorkerExecution;
8279
- export const executeInWorker: (options?: any) => Promise<RuntimeExecutionResult> = _hostRuntime.executeInWorker;
8280
-
8281
- export default _hostRuntime;
8263
+ ) => Promise<Record<string, string>> = _runtimeApi.preloadNpmPackages;
8264
+ export const createVirtualPortTable: () => any = _runtimeApi.createVirtualPortTable;
8265
+ export const executeInVirtualRuntime: (options?: any) => Promise<any> = _runtimeApi.executeInVirtualRuntime;
8266
+ const createWorkerRuntimeSourceExport: () => string = _runtimeApi.createWorkerRuntimeSource;
8267
+ export { createWorkerRuntimeSourceExport as createWorkerRuntimeSource };
8268
+ export const cancelWorkerExecution: (reason?: string, instanceId?: string) => boolean = _runtimeApi.cancelWorkerExecution;
8269
+ export const executeInWorker: (options?: any) => Promise<any> = _runtimeApi.executeInWorker;
8270
+
8271
+ export default _runtimeApi;
package/src/schemas.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  /**
4
- * Zod Schemas and Inferred TypeScript Types for code-lab v2.0.0
4
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.7
5
5
  */
6
6
 
7
7
  // ── 1. Guided Step ──────────────────────────────────────────────────────────
@@ -152,6 +152,9 @@ export const WorkbenchOptionsSchema = z.object({
152
152
  testFile: z.string().optional(),
153
153
  backLabel: z.string().default('Back'),
154
154
  monacoUrl: z.string().optional(),
155
+ previewOrigin: z.string().optional(),
156
+ logger: z.any().optional(),
157
+ debug: z.boolean().optional(),
155
158
  onClose: z.function().returns(z.void()).optional(),
156
159
  onRun: z.function().args(z.any()).returns(z.void()).optional(),
157
160
  onTestResult: z.function().args(z.any()).returns(z.void()).optional(),