@innovatorved/code-lab 0.7.0 → 0.7.2

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.
Files changed (159) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +6 -6
  4. package/dist/code-lab-sql.esm.js +19 -19
  5. package/dist/code-lab-sql.umd.js +20 -20
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +1183 -1909
  9. package/dist/code-lab.js +1182 -1906
  10. package/dist/extensions/cpp.esm.js +132 -8760
  11. package/dist/extensions/cpp.js +124 -8770
  12. package/dist/extensions/guided-lab.esm.js +33 -6836
  13. package/dist/extensions/guided-lab.js +33 -6854
  14. package/dist/extensions/javascript.esm.js +1 -36
  15. package/dist/extensions/javascript.js +1 -58
  16. package/dist/extensions/python.esm.js +113 -8122
  17. package/dist/extensions/python.js +113 -8140
  18. package/dist/extensions/typescript.esm.js +1 -55
  19. package/dist/extensions/typescript.js +1 -77
  20. package/dist/index.d.ts +1 -1
  21. package/dist/logger.d.ts +4 -20
  22. package/dist/modular-kernel.d.ts +0 -5
  23. package/dist/packages/core/src/errors.d.ts +5 -1
  24. package/dist/packages/fs/src/backends.d.ts +0 -27
  25. package/dist/packages/fs/src/index.d.ts +1 -1
  26. package/dist/packages/ui/src/html.d.ts +1 -0
  27. package/dist/packages/ui/src/index.d.ts +1 -0
  28. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -11
  29. package/dist/packages/ui/src/observability.d.ts +1 -1
  30. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  31. package/dist/preview-sw.js +1 -1
  32. package/dist/runtime.d.ts +3 -0
  33. package/dist/runtime.esm.js +78 -78
  34. package/dist/runtime.js +78 -78
  35. package/dist/schemas.d.ts +10 -1
  36. package/dist/schemas.esm.js +33 -6815
  37. package/dist/schemas.js +33 -6831
  38. package/dist/shell.esm.js +277 -285
  39. package/dist/shell.js +277 -285
  40. package/dist/terminal.esm.js +9 -7
  41. package/dist/terminal.js +7 -7
  42. package/dist/workbench/command-palette.d.ts +0 -4
  43. package/dist/workbench/editor.d.ts +0 -4
  44. package/dist/workbench/index.d.ts +0 -22
  45. package/dist/workbench/intellisense.d.ts +1 -8
  46. package/dist/workbench/xterm-adapter.d.ts +0 -1
  47. package/package.json +4 -13
  48. package/dist/code-lab.umd.js +0 -6117
  49. package/dist/packages/editor/src/index.d.ts +0 -118
  50. package/dist/packages/preview/src/index.d.ts +0 -34
  51. package/dist/packages/runtime/src/index.d.ts +0 -47
  52. package/dist/packages/terminal/src/index.d.ts +0 -54
  53. package/dist/workbench/drawer.d.ts +0 -18
  54. package/dist/workbench/file-tree.d.ts +0 -11
  55. package/dist/workbench/guided-pane.d.ts +0 -11
  56. package/dist/workbench/styles.d.ts +0 -4
  57. package/dist/workbench/toolbar.d.ts +0 -17
  58. package/packages/commands/README.md +0 -7
  59. package/packages/commands/package.json +0 -16
  60. package/packages/commands/src/index.ts +0 -467
  61. package/packages/commands/tsconfig.json +0 -22
  62. package/packages/core/README.md +0 -12
  63. package/packages/core/package.json +0 -13
  64. package/packages/core/src/di.ts +0 -147
  65. package/packages/core/src/disposable.ts +0 -112
  66. package/packages/core/src/errors.ts +0 -205
  67. package/packages/core/src/events.ts +0 -157
  68. package/packages/core/src/index.ts +0 -49
  69. package/packages/core/src/path.ts +0 -118
  70. package/packages/core/src/registry.ts +0 -61
  71. package/packages/core/tsconfig.json +0 -19
  72. package/packages/editor/README.md +0 -9
  73. package/packages/editor/package.json +0 -18
  74. package/packages/editor/src/index.ts +0 -344
  75. package/packages/editor/tsconfig.json +0 -24
  76. package/packages/fs/README.md +0 -7
  77. package/packages/fs/package.json +0 -16
  78. package/packages/fs/src/backends.ts +0 -301
  79. package/packages/fs/src/index.ts +0 -18
  80. package/packages/fs/src/types.ts +0 -44
  81. package/packages/fs/src/vfs-service.ts +0 -257
  82. package/packages/fs/tsconfig.json +0 -22
  83. package/packages/preview/README.md +0 -3
  84. package/packages/preview/package.json +0 -16
  85. package/packages/preview/src/index.ts +0 -125
  86. package/packages/preview/tsconfig.json +0 -22
  87. package/packages/runtime/README.md +0 -3
  88. package/packages/runtime/package.json +0 -17
  89. package/packages/runtime/src/index.ts +0 -134
  90. package/packages/runtime/tsconfig.json +0 -23
  91. package/packages/settings/README.md +0 -7
  92. package/packages/settings/package.json +0 -16
  93. package/packages/settings/src/builtin-schemas.ts +0 -262
  94. package/packages/settings/src/configuration-service.ts +0 -609
  95. package/packages/settings/src/index.ts +0 -38
  96. package/packages/settings/src/jsonc.ts +0 -189
  97. package/packages/settings/src/schema.ts +0 -164
  98. package/packages/settings/tsconfig.json +0 -22
  99. package/packages/sql/README.md +0 -12
  100. package/packages/sql/package.json +0 -13
  101. package/packages/sql/src/completions.ts +0 -359
  102. package/packages/sql/src/diagnostics.ts +0 -200
  103. package/packages/sql/src/formatter.ts +0 -271
  104. package/packages/sql/src/index.ts +0 -54
  105. package/packages/sql/src/sql-editor.ts +0 -802
  106. package/packages/sql/src/styles.ts +0 -524
  107. package/packages/sql/src/tokenizer.ts +0 -457
  108. package/packages/sql/src/types.ts +0 -148
  109. package/packages/sql/tsconfig.json +0 -19
  110. package/packages/terminal/README.md +0 -3
  111. package/packages/terminal/package.json +0 -16
  112. package/packages/terminal/src/index.ts +0 -183
  113. package/packages/terminal/tsconfig.json +0 -22
  114. package/packages/ui/README.md +0 -8
  115. package/packages/ui/package.json +0 -18
  116. package/packages/ui/src/index.ts +0 -40
  117. package/packages/ui/src/observability.ts +0 -173
  118. package/packages/ui/src/plugin-registry.ts +0 -289
  119. package/packages/ui/src/settings-dialog.ts +0 -939
  120. package/packages/ui/src/themes.ts +0 -333
  121. package/packages/ui/tsconfig.json +0 -24
  122. package/src/code-lab.css +0 -8584
  123. package/src/csp.ts +0 -590
  124. package/src/diagnostics.ts +0 -287
  125. package/src/extensions/cpp.ts +0 -2389
  126. package/src/extensions/guided-lab.ts +0 -64
  127. package/src/extensions/javascript.ts +0 -54
  128. package/src/extensions/python.ts +0 -1737
  129. package/src/extensions/typescript.ts +0 -85
  130. package/src/extensions/umbrella.ts +0 -5
  131. package/src/html.ts +0 -88
  132. package/src/index.ts +0 -129
  133. package/src/logger.ts +0 -139
  134. package/src/modular-kernel.ts +0 -11
  135. package/src/preview-sw.js +0 -296
  136. package/src/runtime/test-harness.ts +0 -57
  137. package/src/runtime.ts +0 -10480
  138. package/src/sample.html +0 -304
  139. package/src/schemas.ts +0 -366
  140. package/src/scm.ts +0 -2453
  141. package/src/search.ts +0 -433
  142. package/src/shell.ts +0 -10987
  143. package/src/storage.ts +0 -773
  144. package/src/terminal.ts +0 -1400
  145. package/src/workbench/command-palette.ts +0 -381
  146. package/src/workbench/diff-editor.ts +0 -470
  147. package/src/workbench/drawer.ts +0 -157
  148. package/src/workbench/editor.ts +0 -49
  149. package/src/workbench/file-tree.ts +0 -51
  150. package/src/workbench/guided-pane.ts +0 -43
  151. package/src/workbench/icons.ts +0 -255
  152. package/src/workbench/index.ts +0 -44
  153. package/src/workbench/intellisense.ts +0 -1871
  154. package/src/workbench/share.ts +0 -128
  155. package/src/workbench/styles.ts +0 -211
  156. package/src/workbench/toolbar.ts +0 -182
  157. package/src/workbench/xterm-adapter.ts +0 -1571
  158. package/src/workbench.ts +0 -22132
  159. package/src/zip.ts +0 -348
package/src/csp.ts DELETED
@@ -1,590 +0,0 @@
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
- // `data:` is required for scripts: the preview import map serves every local
199
- // module as `data:text/javascript;...` so it works in a sandboxed frame (see
200
- // buildHtmlPreviewResponse in src/shell.ts). Without it, any project with
201
- // local ES modules fails to boot. `'unsafe-inline'` already allows inline
202
- // script, so this does not widen the practical attack surface.
203
- const script = (): string[] => [self, 'data:', 'blob:', "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, 'scriptSrc'));
204
- const style = (): string[] => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, 'styleSrc'));
205
- const withData = (key: keyof PreviewCspSources): string[] => [self, 'data:', 'blob:'].concat(sourcesFor(mode, allow, key));
206
-
207
- return [
208
- directive('default-src', [self, 'data:', 'blob:']),
209
- directive('base-uri', [self]),
210
- "object-src 'none'",
211
- directive('script-src', script()),
212
- directive('style-src', style()),
213
- directive('img-src', withData('imgSrc')),
214
- directive('font-src', [self, 'data:'].concat(sourcesFor(mode, allow, 'fontSrc'))),
215
- directive('connect-src', withData('connectSrc')),
216
- directive('media-src', withData('mediaSrc')),
217
- directive('worker-src', [self, 'blob:'].concat(sourcesFor(mode, allow, 'workerSrc'))),
218
- directive('frame-src', withData('frameSrc')),
219
- directive('form-action', [self]),
220
- directive('frame-ancestors', (() => {
221
- const rawFa = typeof options.frameAncestors === 'string' ? options.frameAncestors.trim() : '';
222
- if (!rawFa) return ["'self'"];
223
- const tokens = cleanSources(rawFa.split(/\s+/));
224
- return tokens.length > 0 ? tokens : ["'self'"];
225
- })())
226
- ].join('; ');
227
- }
228
-
229
- /**
230
- * Network hosts a preview may reach, for display in the Web Preview toolbar.
231
- * Returns remote origins only — the host origin and CSP keywords are omitted.
232
- */
233
- export function describePreviewNetwork(config: unknown): string[] {
234
- const normalized = normalizePreviewCspConfig(config);
235
- if (normalized.mode === 'strict') return [];
236
- const preset = normalized.mode === 'custom' ? {} : PRESETS[normalized.mode];
237
- const hosts: string[] = [];
238
- for (const key of ['scriptSrc', 'connectSrc', 'imgSrc', 'styleSrc', 'fontSrc'] as Array<keyof PreviewCspSources>) {
239
- for (const source of unique(preset[key], normalized.allow[key])) {
240
- if (!/^https?:\/\//i.test(source)) continue;
241
- let host: string;
242
- try {
243
- host = new URL(source).host;
244
- } catch (_) {
245
- continue;
246
- }
247
- if (hosts.indexOf(host) === -1) hosts.push(host);
248
- }
249
- }
250
- return hosts;
251
- }
252
-
253
- /**
254
- * Scripts injected into every preview document:
255
- *
256
- * 1. In-memory `localStorage`/`sessionStorage` — a sandboxed (opaque origin)
257
- * document throws `SecurityError` on access, which breaks any preview that
258
- * touches storage at module top level. In-memory equivalents keep the app
259
- * running; sub-resource loading is unaffected.
260
- * 2. A `securitypolicyviolation` reporter that forwards to the host via
261
- * `postMessage`. The host validates `event.source` (the document origin is
262
- * opaque, so `event.origin` is the string `"null"` and is not usable).
263
- */
264
- export function buildPreviewShims(): string {
265
- return `<script ${PREVIEW_SHIM_MARKER}>
266
- (function () {
267
- 'use strict';
268
- function memoryStorage() {
269
- var data = new Map();
270
- return {
271
- getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
272
- setItem: function (k, v) { data.set(String(k), String(v)); },
273
- removeItem: function (k) { data.delete(String(k)); },
274
- clear: function () { data.clear(); },
275
- key: function (i) { return Array.from(data.keys())[i] || null; },
276
- get length() { return data.size; }
277
- };
278
- }
279
- function shim(name) {
280
- try {
281
- Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
282
- } catch (err) {
283
- console.warn('[code-lab] preview: unable to shim ' + name, err);
284
- }
285
- }
286
- shim('localStorage');
287
- shim('sessionStorage');
288
- document.addEventListener('securitypolicyviolation', function (event) {
289
- try {
290
- parent.postMessage({
291
- type: 'codelab:preview-violation',
292
- directive: event.effectiveDirective || event.violatedDirective || '',
293
- blockedURI: event.blockedURI || '',
294
- sourceFile: event.sourceFile || '',
295
- line: event.lineNumber || 0
296
- }, '*');
297
- } catch (err) {
298
- console.warn('[code-lab] preview: could not report CSP violation', err);
299
- }
300
- });
301
- function serializeArg(arg) {
302
- if (typeof arg !== 'object' || arg === null) return String(arg);
303
- try {
304
- return JSON.stringify(arg);
305
- } catch (err) {
306
- void err;
307
- return '[Circular/Unserializable]';
308
- }
309
- }
310
- ['log', 'warn', 'error', 'info'].forEach(function (level) {
311
- var orig = console[level];
312
- if (typeof orig !== 'function') return;
313
- console[level] = function () {
314
- var args = Array.prototype.slice.call(arguments);
315
- try {
316
- parent.postMessage({
317
- type: 'codelab:preview-console',
318
- level: level,
319
- args: args.map(serializeArg)
320
- }, '*');
321
- } catch (err) {
322
- void err;
323
- }
324
- return orig.apply(console, args);
325
- };
326
- });
327
- function showPreviewErrorOverlay(msg, stack) {
328
- try {
329
- if (!document || !document.body) return;
330
- var existing = document.getElementById('codelab-preview-error-overlay');
331
- if (!existing) {
332
- existing = document.createElement('div');
333
- existing.id = 'codelab-preview-error-overlay';
334
- 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;';
335
- document.body.appendChild(existing);
336
- }
337
- existing.textContent = '';
338
- var topBar = document.createElement('div');
339
- 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);';
340
- var header = document.createElement('div');
341
- header.style.cssText = 'color:#f87171;font-weight:700;font-size:14px;';
342
- header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
343
- var closeBtn = document.createElement('button');
344
- closeBtn.type = 'button';
345
- closeBtn.textContent = 'Dismiss \u00d7';
346
- 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;';
347
- closeBtn.onclick = function () { if (existing && existing.parentNode) existing.parentNode.removeChild(existing); };
348
- topBar.appendChild(header);
349
- topBar.appendChild(closeBtn);
350
- var pre = document.createElement('pre');
351
- pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;line-height:1.55;';
352
- pre.textContent = String(stack || msg || '');
353
- existing.appendChild(topBar);
354
- existing.appendChild(pre);
355
- } catch (err) {
356
- void err;
357
- }
358
- }
359
- window.addEventListener('error', function (event) {
360
- var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
361
- var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
362
- showPreviewErrorOverlay(msg, stack);
363
- try {
364
- parent.postMessage({
365
- type: 'codelab:preview-error',
366
- message: msg,
367
- file: (event && event.filename) || null,
368
- line: (event && event.lineno) || null,
369
- col: (event && event.colno) || null,
370
- stack: stack || null
371
- }, '*');
372
- } catch (err) {
373
- void err;
374
- }
375
- });
376
- window.addEventListener('unhandledrejection', function (event) {
377
- var reason = event ? event.reason : null;
378
- var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
379
- var stack = reason && reason.stack ? String(reason.stack) : '';
380
- showPreviewErrorOverlay(msg, stack);
381
- try {
382
- parent.postMessage({
383
- type: 'codelab:preview-error',
384
- message: msg,
385
- file: null,
386
- line: null,
387
- col: null,
388
- stack: stack || null
389
- }, '*');
390
- } catch (err) {
391
- void err;
392
- }
393
- });
394
-
395
- // Virtual loopback bridge for fetch/XHR, link navigation, and SPA history in srcdoc/sandbox mode
396
- var pendingFetches = new Map();
397
- var fetchSeq = 0;
398
- function parseLoopbackTarget(rawUrl) {
399
- if (!rawUrl || typeof rawUrl !== 'string') return null;
400
- var trimmed = rawUrl.trim();
401
- if (!trimmed) return null;
402
- var lower = trimmed.toLowerCase();
403
- 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;
404
- if (lower.indexOf('http://') === 0 || lower.indexOf('https://') === 0) {
405
- try {
406
- var u = new URL(trimmed);
407
- if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') {
408
- return { port: u.port ? Number(u.port) : null, path: (u.pathname || '/') + (u.search || '') + (u.hash || '') };
409
- }
410
- if (u.pathname && u.pathname.indexOf('/__preview/') === 0) {
411
- var rest = u.pathname.slice('/__preview/'.length);
412
- var slashIdx = rest.indexOf('/');
413
- var portStr = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
414
- var subPath = slashIdx === -1 ? '/' : rest.slice(slashIdx);
415
- var portNum = Number(portStr);
416
- if (portNum > 0) {
417
- return { port: portNum, path: (subPath || '/') + (u.search || '') + (u.hash || '') };
418
- }
419
- }
420
- } catch (e) { void e; }
421
- return null;
422
- }
423
- if (trimmed.indexOf('/__preview/') === 0) {
424
- var restRel = trimmed.slice('/__preview/'.length);
425
- var sIdx = restRel.indexOf('/');
426
- var pStr = sIdx === -1 ? restRel : restRel.slice(0, sIdx);
427
- var sPath = sIdx === -1 ? '/' : restRel.slice(sIdx);
428
- var pNum = Number(pStr);
429
- if (pNum > 0) {
430
- return { port: pNum, path: sPath || '/' };
431
- }
432
- }
433
- var cleaned = trimmed.indexOf('./') === 0 ? trimmed.slice(2) : trimmed;
434
- var pathPart = cleaned.charAt(0) === '/' ? cleaned : '/' + cleaned;
435
- return { port: null, path: pathPart };
436
- }
437
-
438
- window.addEventListener('message', function (event) {
439
- if (event && event.source && event.source !== window.parent) return;
440
- var data = event && event.data;
441
- if (!data || typeof data !== 'object') return;
442
- if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
443
- var entry = pendingFetches.get(data.reqId);
444
- if (!entry) return;
445
- pendingFetches.delete(data.reqId);
446
- entry.resolve(data);
447
- }
448
- });
449
-
450
- if (typeof window.fetch === 'function') {
451
- var origFetch = window.fetch.bind(window);
452
- window.fetch = function (input, init) {
453
- var urlStr = typeof input === 'string' ? input : (input && typeof input.url === 'string' ? input.url : String(input || ''));
454
- var target = parseLoopbackTarget(urlStr);
455
- // Only bridge via postMessage when running inside a sandboxed/srcdoc document or targeting localhost
456
- var isOpaque = false;
457
- try {
458
- var lowerUrl = urlStr.toLowerCase();
459
- var isLocalTarget = lowerUrl.indexOf('http://localhost') === 0 || lowerUrl.indexOf('http://127.0.0.1') === 0 || lowerUrl.indexOf('http://0.0.0.0') === 0;
460
- isOpaque = (window.location.origin === 'null' || window.location.protocol === 'about:' || isLocalTarget);
461
- } catch (e) { isOpaque = true; void e; }
462
- if (!target || !isOpaque || window.parent === window) {
463
- return origFetch(input, init);
464
- }
465
- return new Promise(function (resolve, reject) {
466
- var reqId = 'clf_' + (++fetchSeq) + '_' + Date.now();
467
- var method = (init && init.method) || (input && input.method) || 'GET';
468
- var headersObj = {};
469
- try {
470
- var rawH = (init && init.headers) || (input && input.headers);
471
- if (rawH) {
472
- if (typeof rawH.forEach === 'function') {
473
- rawH.forEach(function (v, k) { headersObj[k] = v; });
474
- } else if (Array.isArray(rawH)) {
475
- rawH.forEach(function (pair) { if (pair && pair.length >= 2) headersObj[pair[0]] = pair[1]; });
476
- } else if (typeof rawH === 'object') {
477
- Object.keys(rawH).forEach(function (k) { headersObj[k] = String(rawH[k]); });
478
- }
479
- }
480
- } catch (e) { void e; }
481
- var bodyStr = (init && init.body !== undefined && init.body !== null) ? String(init.body) : undefined;
482
- var timer = setTimeout(function () {
483
- if (pendingFetches.has(reqId)) {
484
- pendingFetches.delete(reqId);
485
- origFetch(input, init).then(resolve, reject);
486
- }
487
- }, 5000);
488
- pendingFetches.set(reqId, {
489
- resolve: function (payload) {
490
- clearTimeout(timer);
491
- if (payload && payload.error) {
492
- reject(new TypeError(String(payload.error)));
493
- return;
494
- }
495
- var status = Number(payload && payload.status) || 200;
496
- var resHeaders = (payload && payload.headers) || { 'content-type': 'text/plain; charset=utf-8' };
497
- var body = payload && payload.body !== undefined ? String(payload.body) : '';
498
- try {
499
- resolve(new Response(body, { status: status, statusText: String(payload.statusText || 'OK'), headers: resHeaders }));
500
- } catch (err) {
501
- void err;
502
- resolve({
503
- ok: status >= 200 && status < 300,
504
- status: status,
505
- headers: { get: function (k) { return resHeaders[String(k).toLowerCase()] || resHeaders[k] || null; } },
506
- text: function () { return Promise.resolve(body); },
507
- json: function () { return Promise.resolve(JSON.parse(body)); }
508
- });
509
- }
510
- }
511
- });
512
- try {
513
- parent.postMessage({
514
- type: 'codelab:preview-fetch',
515
- reqId: reqId,
516
- port: target.port,
517
- path: target.path,
518
- method: String(method).toUpperCase(),
519
- headers: headersObj,
520
- body: bodyStr
521
- }, '*');
522
- } catch (err) {
523
- clearTimeout(timer);
524
- pendingFetches.delete(reqId);
525
- origFetch(input, init).then(resolve, reject);
526
- }
527
- });
528
- };
529
- }
530
-
531
- // Intercept relative <a href> clicks so multi-page navigation works inside srcdoc/preview
532
- document.addEventListener('click', function (event) {
533
- if (!event || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
534
- var el = event.target;
535
- while (el && el.tagName !== 'A') el = el.parentElement;
536
- if (!el || !el.getAttribute) return;
537
- var href = el.getAttribute('href');
538
- var targetAttr = el.getAttribute('target');
539
- if (!href || targetAttr === '_blank' || el.hasAttribute('download')) return;
540
- var lowerHref = href.toLowerCase();
541
- 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;
542
- var parsed = parseLoopbackTarget(href);
543
- if (!parsed) return;
544
- event.preventDefault();
545
- try {
546
- parent.postMessage({
547
- type: 'codelab:preview-navigate',
548
- port: parsed.port,
549
- path: parsed.path
550
- }, '*');
551
- } catch (e) { void e; }
552
- });
553
-
554
- // Sync SPA history.pushState / replaceState with the preview omni-address bar
555
- try {
556
- ['pushState', 'replaceState'].forEach(function (method) {
557
- var orig = history[method];
558
- if (typeof orig !== 'function') return;
559
- history[method] = function (state, title, url) {
560
- var ret;
561
- try { ret = orig.apply(history, arguments); } catch (e) { void e; }
562
- if (url !== undefined && url !== null) {
563
- var parsed = parseLoopbackTarget(String(url));
564
- if (parsed) {
565
- try {
566
- parent.postMessage({
567
- type: 'codelab:preview-url-change',
568
- path: parsed.path,
569
- replace: method === 'replaceState'
570
- }, '*');
571
- } catch (e) { void e; }
572
- }
573
- }
574
- return ret;
575
- };
576
- });
577
- } catch (e) { void e; }
578
- })();
579
- </script>`;
580
- }
581
-
582
- /** Default export keeps the IIFE global (`CodeLabCsp`) shaped like the sources. */
583
- export default {
584
- buildPreviewPolicy,
585
- buildPreviewShims,
586
- describePreviewNetwork,
587
- normalizePreviewCspConfig,
588
- normalizeOrigin,
589
- PREVIEW_SHIM_MARKER
590
- };