@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/ARCHITECTURE.md +34 -16
- package/README.md +17 -7
- package/dist/code-lab.css +683 -0
- package/dist/code-lab.d.ts +271 -1
- package/dist/code-lab.esm.js +3326 -193
- package/dist/code-lab.js +3286 -191
- package/dist/csp.d.ts +86 -0
- package/dist/diagnostics.d.ts +43 -0
- package/dist/extensions/guided-lab.esm.js +63 -0
- package/dist/extensions/guided-lab.js +63 -0
- package/dist/html.d.ts +24 -0
- package/dist/index.d.ts +9 -1
- package/dist/logger.d.ts +60 -0
- package/dist/preview-sw.js +604 -46
- package/dist/runtime.esm.js +169 -31
- package/dist/runtime.js +169 -31
- package/dist/schemas.d.ts +357 -25
- package/dist/schemas.esm.js +70 -0
- package/dist/schemas.js +70 -0
- package/dist/scm.d.ts +77 -0
- package/dist/search.d.ts +75 -0
- package/dist/shell.esm.js +333 -48
- package/dist/shell.js +333 -48
- package/dist/storage.d.ts +57 -0
- package/dist/terminal.esm.js +122 -7
- package/dist/terminal.js +122 -7
- package/dist/zip.d.ts +42 -0
- package/package.json +3 -1
- package/src/code-lab.css +683 -0
- package/src/csp.ts +588 -0
- package/src/diagnostics.ts +116 -0
- package/src/html.ts +88 -0
- package/src/index.ts +39 -1
- package/src/logger.ts +139 -0
- package/src/preview-sw.js +84 -46
- package/src/runtime.ts +67 -30
- package/src/schemas.ts +91 -1
- package/src/scm.ts +268 -0
- package/src/search.ts +389 -0
- package/src/shell.ts +231 -47
- package/src/storage.ts +377 -0
- package/src/terminal.ts +20 -6
- package/src/workbench.ts +1061 -107
- package/src/zip.ts +326 -0
package/dist/preview-sw.js
CHANGED
|
@@ -1,3 +1,523 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ============================================================
|
|
3
|
+
* @innovatorved/code-lab v0.1.9 — 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 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);';
|
|
270
|
+
var header = document.createElement('div');
|
|
271
|
+
header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
|
|
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);
|
|
280
|
+
var pre = document.createElement('pre');
|
|
281
|
+
pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
|
|
282
|
+
pre.textContent = String(stack || msg || '');
|
|
283
|
+
existing.appendChild(topBar);
|
|
284
|
+
existing.appendChild(pre);
|
|
285
|
+
} catch (err) {
|
|
286
|
+
void err;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
window.addEventListener('error', function (event) {
|
|
290
|
+
var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
|
|
291
|
+
var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
|
|
292
|
+
showPreviewErrorOverlay(msg, stack);
|
|
293
|
+
try {
|
|
294
|
+
parent.postMessage({
|
|
295
|
+
type: 'codelab:preview-error',
|
|
296
|
+
message: msg,
|
|
297
|
+
file: (event && event.filename) || null,
|
|
298
|
+
line: (event && event.lineno) || null,
|
|
299
|
+
col: (event && event.colno) || null,
|
|
300
|
+
stack: stack || null
|
|
301
|
+
}, '*');
|
|
302
|
+
} catch (err) {
|
|
303
|
+
void err;
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
window.addEventListener('unhandledrejection', function (event) {
|
|
307
|
+
var reason = event ? event.reason : null;
|
|
308
|
+
var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
|
|
309
|
+
var stack = reason && reason.stack ? String(reason.stack) : '';
|
|
310
|
+
showPreviewErrorOverlay(msg, stack);
|
|
311
|
+
try {
|
|
312
|
+
parent.postMessage({
|
|
313
|
+
type: 'codelab:preview-error',
|
|
314
|
+
message: msg,
|
|
315
|
+
file: null,
|
|
316
|
+
line: null,
|
|
317
|
+
col: null,
|
|
318
|
+
stack: stack || null
|
|
319
|
+
}, '*');
|
|
320
|
+
} catch (err) {
|
|
321
|
+
void err;
|
|
322
|
+
}
|
|
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; }
|
|
507
|
+
})();
|
|
508
|
+
<\/script>`;
|
|
509
|
+
}
|
|
510
|
+
var csp_default = {
|
|
511
|
+
buildPreviewPolicy,
|
|
512
|
+
buildPreviewShims,
|
|
513
|
+
describePreviewNetwork,
|
|
514
|
+
normalizePreviewCspConfig,
|
|
515
|
+
normalizeOrigin,
|
|
516
|
+
PREVIEW_SHIM_MARKER
|
|
517
|
+
};
|
|
518
|
+
return __toCommonJS(csp_exports);
|
|
519
|
+
})();
|
|
520
|
+
|
|
1
521
|
/**
|
|
2
522
|
* @innovatorved/code-lab — Web Preview Virtual Loopback Service Worker (Milestone 3)
|
|
3
523
|
* ============================================================================
|
|
@@ -8,6 +528,10 @@
|
|
|
8
528
|
* This enables "pop out to tab" Web Preview for virtual HTTP / Bun servers that
|
|
9
529
|
* exist only inside the workbench's in-memory runtime (no real OS socket).
|
|
10
530
|
*
|
|
531
|
+
* The Content-Security-Policy, the storage shims and the violation reporter all
|
|
532
|
+
* come from `src/csp.ts`, which the build prepends to this file. The workbench
|
|
533
|
+
* embeds the same module, so the two can never drift.
|
|
534
|
+
*
|
|
11
535
|
* Zero dependencies. Plain Service Worker script (no module imports) so it can
|
|
12
536
|
* be registered directly from any host origin.
|
|
13
537
|
*/
|
|
@@ -16,49 +540,32 @@
|
|
|
16
540
|
|
|
17
541
|
const PREVIEW_PREFIX = '/__preview/';
|
|
18
542
|
const DISPATCH_TIMEOUT_MS = 15000;
|
|
543
|
+
const MAX_CONFIG_LENGTH = 8192;
|
|
19
544
|
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
|
|
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('; ');
|
|
545
|
+
// Policy configured by the workbench via postMessage. The worker cannot read the
|
|
546
|
+
// host's options, so the host pushes the resolved policy after registering.
|
|
547
|
+
let configuredCsp = null;
|
|
41
548
|
|
|
42
|
-
function
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
if (!/<base\b/i.test(html)) {
|
|
48
|
-
tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
|
|
49
|
-
}
|
|
50
|
-
if (tags.length === 0) return html;
|
|
549
|
+
function cspModule() {
|
|
550
|
+
// `CodeLabCsp` is declared by the prepended csp bundle (src/csp.ts).
|
|
551
|
+
return typeof CodeLabCsp !== 'undefined' ? CodeLabCsp : null;
|
|
552
|
+
}
|
|
51
553
|
|
|
52
|
-
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
554
|
+
function previewPolicy() {
|
|
555
|
+
if (configuredCsp) return configuredCsp;
|
|
556
|
+
const csp = cspModule();
|
|
557
|
+
if (!csp) return "default-src 'self'; object-src 'none'";
|
|
558
|
+
// The workbench pushes its resolved policy on registration, so this branch
|
|
559
|
+
// only runs in the brief window before that message arrives. Use the
|
|
560
|
+
// documented default (`balanced`) rather than a stricter one, otherwise the
|
|
561
|
+
// very first preview of a CDN-based app can be blocked by a race.
|
|
562
|
+
return csp.buildPreviewPolicy({ hostOrigin: self.location.origin, mode: 'balanced' });
|
|
60
563
|
}
|
|
61
564
|
|
|
565
|
+
function previewShims() {
|
|
566
|
+
const csp = cspModule();
|
|
567
|
+
return csp ? csp.buildPreviewShims() : '';
|
|
568
|
+
}
|
|
62
569
|
|
|
63
570
|
self.addEventListener('install', () => {
|
|
64
571
|
self.skipWaiting();
|
|
@@ -68,6 +575,25 @@ self.addEventListener('activate', (event) => {
|
|
|
68
575
|
event.waitUntil(self.clients.claim());
|
|
69
576
|
});
|
|
70
577
|
|
|
578
|
+
self.addEventListener('message', (event) => {
|
|
579
|
+
const data = event && event.data;
|
|
580
|
+
if (!data || data.type !== 'codelab:config') return;
|
|
581
|
+
const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
|
|
582
|
+
if (!csp || csp.length > MAX_CONFIG_LENGTH) return;
|
|
583
|
+
configuredCsp = csp;
|
|
584
|
+
// Acknowledge so the host can wait for confirmation before loading a frame.
|
|
585
|
+
try {
|
|
586
|
+
if (event.ports && event.ports[0]) {
|
|
587
|
+
event.ports[0].postMessage({ type: 'codelab:config-ready' });
|
|
588
|
+
} else if (event.source && typeof event.source.postMessage === 'function') {
|
|
589
|
+
event.source.postMessage({ type: 'codelab:config-ready' });
|
|
590
|
+
}
|
|
591
|
+
} catch (err) {
|
|
592
|
+
// The client may have navigated away between postMessage and reply.
|
|
593
|
+
console.warn('[code-lab] preview-sw: config acknowledgement failed', err);
|
|
594
|
+
}
|
|
595
|
+
});
|
|
596
|
+
|
|
71
597
|
function parsePreviewPath(pathname) {
|
|
72
598
|
const match = pathname.match(/^\/__preview\/(\d+)(\/.*)?$/);
|
|
73
599
|
if (!match) return null;
|
|
@@ -75,8 +601,9 @@ function parsePreviewPath(pathname) {
|
|
|
75
601
|
}
|
|
76
602
|
|
|
77
603
|
function previewErrorResponse(status, title, message) {
|
|
604
|
+
const csp = previewPolicy();
|
|
78
605
|
const body = `<!doctype html><meta charset="utf-8">` +
|
|
79
|
-
`<meta http-equiv="Content-Security-Policy" content="${
|
|
606
|
+
`<meta http-equiv="Content-Security-Policy" content="${csp}">` +
|
|
80
607
|
`<title>${title}</title>` +
|
|
81
608
|
`<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
|
|
82
609
|
`<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
|
|
@@ -84,12 +611,36 @@ function previewErrorResponse(status, title, message) {
|
|
|
84
611
|
status,
|
|
85
612
|
headers: {
|
|
86
613
|
'Content-Type': 'text/html; charset=utf-8',
|
|
87
|
-
'Content-Security-Policy':
|
|
614
|
+
'Content-Security-Policy': csp,
|
|
88
615
|
'X-Content-Type-Options': 'nosniff'
|
|
89
616
|
}
|
|
90
617
|
});
|
|
91
618
|
}
|
|
92
619
|
|
|
620
|
+
/** Inject the policy, a base URL and the sandbox shims into an HTML response. */
|
|
621
|
+
function injectPreviewHead(html, port) {
|
|
622
|
+
const csp = previewPolicy();
|
|
623
|
+
const shims = previewShims();
|
|
624
|
+
const tags = [];
|
|
625
|
+
const hasCsp = /<meta[^>]+http-equiv=["']?content-security-policy/i.test(html);
|
|
626
|
+
const hasBase = /<base\b/i.test(html);
|
|
627
|
+
const hasShims = html.indexOf('data-codelab-preview-shims') !== -1;
|
|
628
|
+
|
|
629
|
+
if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
|
|
630
|
+
if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
|
|
631
|
+
if (!hasShims && shims) tags.push(shims);
|
|
632
|
+
if (tags.length === 0) return html;
|
|
633
|
+
|
|
634
|
+
const injection = tags.join('');
|
|
635
|
+
if (/<head\b[^>]*>/i.test(html)) {
|
|
636
|
+
return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
|
|
637
|
+
}
|
|
638
|
+
if (/<html\b[^>]*>/i.test(html)) {
|
|
639
|
+
return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
|
|
640
|
+
}
|
|
641
|
+
return `<head>${injection}</head>${html}`;
|
|
642
|
+
}
|
|
643
|
+
|
|
93
644
|
async function proxyVirtualRequest(event, port, targetPath) {
|
|
94
645
|
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
|
95
646
|
if (!clients || !clients.length) {
|
|
@@ -110,13 +661,18 @@ async function proxyVirtualRequest(event, port, targetPath) {
|
|
|
110
661
|
for (const [key, value] of request.headers.entries()) {
|
|
111
662
|
headers[key.toLowerCase()] = value;
|
|
112
663
|
}
|
|
113
|
-
} catch (
|
|
664
|
+
} catch (err) {
|
|
665
|
+
// Opaque or unsupported header collection; forward without request headers.
|
|
666
|
+
console.warn('[code-lab] preview-sw: could not read request headers', err);
|
|
667
|
+
}
|
|
114
668
|
|
|
115
669
|
let body = null;
|
|
116
670
|
if (!['GET', 'HEAD'].includes(method)) {
|
|
117
671
|
try {
|
|
118
672
|
body = await request.arrayBuffer();
|
|
119
|
-
} catch (
|
|
673
|
+
} catch (err) {
|
|
674
|
+
console.warn('[code-lab] preview-sw: could not read request body', err);
|
|
675
|
+
}
|
|
120
676
|
}
|
|
121
677
|
|
|
122
678
|
const response = await new Promise((resolve) => {
|
|
@@ -151,11 +707,11 @@ async function proxyVirtualRequest(event, port, targetPath) {
|
|
|
151
707
|
const responseHeaders = new Headers((response && response.headers) || {});
|
|
152
708
|
const contentType = responseHeaders.get('content-type') || '';
|
|
153
709
|
|
|
154
|
-
// Inject
|
|
155
|
-
// under the `/__preview/:port/` namespace rather than the host
|
|
710
|
+
// Inject the policy and a <base> so relative asset URLs in HTML responses
|
|
711
|
+
// resolve under the `/__preview/:port/` namespace rather than the host root.
|
|
156
712
|
if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
|
|
157
713
|
responseBody = injectPreviewHead(responseBody, port);
|
|
158
|
-
responseHeaders.set('Content-Security-Policy',
|
|
714
|
+
responseHeaders.set('Content-Security-Policy', previewPolicy());
|
|
159
715
|
responseHeaders.set('X-Content-Type-Options', 'nosniff');
|
|
160
716
|
}
|
|
161
717
|
|
|
@@ -170,7 +726,9 @@ self.addEventListener('fetch', (event) => {
|
|
|
170
726
|
let url;
|
|
171
727
|
try {
|
|
172
728
|
url = new URL(event.request.url);
|
|
173
|
-
} catch (
|
|
729
|
+
} catch (err) {
|
|
730
|
+
// Non-standard request URL; let the network handle it.
|
|
731
|
+
console.warn('[code-lab] preview-sw: unparsable request URL', err);
|
|
174
732
|
return;
|
|
175
733
|
}
|
|
176
734
|
|