@innovatorved/code-lab 0.7.1 → 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 (71) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +10 -0
  3. package/README.md +5 -5
  4. package/dist/code-lab-sql.esm.js +2 -2
  5. package/dist/code-lab-sql.umd.js +3 -3
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +918 -884
  9. package/dist/code-lab.js +917 -881
  10. package/dist/extensions/cpp.esm.js +33 -33
  11. package/dist/extensions/cpp.js +33 -33
  12. package/dist/extensions/python.esm.js +79 -49
  13. package/dist/extensions/python.js +79 -49
  14. package/dist/index.d.ts +1 -1
  15. package/dist/logger.d.ts +4 -20
  16. package/dist/modular-kernel.d.ts +0 -1
  17. package/dist/packages/core/src/errors.d.ts +5 -1
  18. package/dist/packages/fs/src/backends.d.ts +0 -27
  19. package/dist/packages/fs/src/index.d.ts +1 -1
  20. package/dist/packages/ui/src/html.d.ts +1 -0
  21. package/dist/packages/ui/src/index.d.ts +1 -0
  22. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -2
  23. package/dist/packages/ui/src/observability.d.ts +1 -1
  24. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  25. package/dist/preview-sw.js +1 -1
  26. package/dist/runtime.d.ts +3 -0
  27. package/dist/runtime.esm.js +2 -2
  28. package/dist/runtime.js +2 -2
  29. package/dist/schemas.d.ts +1 -1
  30. package/dist/shell.esm.js +277 -285
  31. package/dist/shell.js +277 -285
  32. package/dist/terminal.esm.js +2 -2
  33. package/dist/terminal.js +2 -2
  34. package/dist/workbench/editor.d.ts +0 -4
  35. package/dist/workbench/index.d.ts +0 -2
  36. package/dist/workbench/intellisense.d.ts +0 -1
  37. package/dist/workbench/xterm-adapter.d.ts +0 -1
  38. package/package.json +2 -4
  39. package/src/code-lab.css +0 -8086
  40. package/src/csp.ts +0 -590
  41. package/src/diagnostics.ts +0 -287
  42. package/src/extensions/cpp.ts +0 -2371
  43. package/src/extensions/guided-lab.ts +0 -68
  44. package/src/extensions/javascript.ts +0 -54
  45. package/src/extensions/python.ts +0 -1743
  46. package/src/extensions/typescript.ts +0 -85
  47. package/src/extensions/umbrella.ts +0 -5
  48. package/src/html.ts +0 -88
  49. package/src/index.ts +0 -129
  50. package/src/logger.ts +0 -139
  51. package/src/modular-kernel.ts +0 -7
  52. package/src/preview-sw.js +0 -296
  53. package/src/runtime/test-harness.ts +0 -57
  54. package/src/runtime.ts +0 -10565
  55. package/src/sample.html +0 -304
  56. package/src/schemas.ts +0 -366
  57. package/src/scm.ts +0 -2453
  58. package/src/search.ts +0 -433
  59. package/src/shell.ts +0 -10990
  60. package/src/storage.ts +0 -773
  61. package/src/terminal.ts +0 -1402
  62. package/src/workbench/command-palette.ts +0 -101
  63. package/src/workbench/diff-editor.ts +0 -472
  64. package/src/workbench/editor.ts +0 -49
  65. package/src/workbench/icons.ts +0 -255
  66. package/src/workbench/index.ts +0 -29
  67. package/src/workbench/intellisense.ts +0 -1884
  68. package/src/workbench/share.ts +0 -128
  69. package/src/workbench/xterm-adapter.ts +0 -1571
  70. package/src/workbench.ts +0 -21825
  71. package/src/zip.ts +0 -348
package/src/preview-sw.js DELETED
@@ -1,296 +0,0 @@
1
- /**
2
- * @innovatorved/code-lab — Web Preview Virtual Loopback Service Worker (Milestone 3)
3
- * ============================================================================
4
- * Intercepts same-origin requests to `/__preview/:port/*`, forwards them to the
5
- * live CodeLab workbench window via a MessageChannel bridge, and streams the
6
- * in-browser virtual runtime's response back to the requesting tab.
7
- *
8
- * This enables "pop out to tab" Web Preview for virtual HTTP / Bun servers that
9
- * exist only inside the workbench's in-memory runtime (no real OS socket).
10
- *
11
- * The Content-Security-Policy, the storage shims and the violation reporter all
12
- * come from `src/csp.ts`, which the build prepends to this file. The workbench
13
- * embeds the same module, so the two can never drift.
14
- *
15
- * Zero dependencies. Plain Service Worker script (no module imports) so it can
16
- * be registered directly from any host origin.
17
- */
18
-
19
- 'use strict';
20
-
21
- const PREVIEW_PREFIX = '/__preview/';
22
- const DISPATCH_TIMEOUT_MS = 15000;
23
- const MAX_CONFIG_LENGTH = 8192;
24
-
25
- // Policy configured by the workbench via postMessage. The worker cannot read the
26
- // host's options, so the host pushes the resolved policy after registering.
27
- let configuredCsp = null;
28
-
29
- function cspModule() {
30
- // `CodeLabCsp` is declared by the prepended csp bundle (src/csp.ts).
31
- return typeof CodeLabCsp !== 'undefined' ? CodeLabCsp : null;
32
- }
33
-
34
- function previewPolicy() {
35
- if (configuredCsp) return configuredCsp;
36
- const csp = cspModule();
37
- if (!csp) return "default-src 'self'; object-src 'none'";
38
- // The workbench pushes its resolved policy on registration, so this branch
39
- // only runs in the brief window before that message arrives. Use the
40
- // documented default (`balanced`) rather than a stricter one, otherwise the
41
- // very first preview of a CDN-based app can be blocked by a race.
42
- return csp.buildPreviewPolicy({ hostOrigin: self.location.origin, mode: 'balanced' });
43
- }
44
-
45
- function previewShims() {
46
- const csp = cspModule();
47
- return csp ? csp.buildPreviewShims() : '';
48
- }
49
-
50
- self.addEventListener('install', () => {
51
- self.skipWaiting();
52
- });
53
-
54
- self.addEventListener('activate', (event) => {
55
- event.waitUntil(self.clients.claim());
56
- });
57
-
58
- self.addEventListener('message', (event) => {
59
- const data = event && event.data;
60
- if (!data || data.type !== 'codelab:config') return;
61
- // Reject configuration attempts originating from preview tabs/frames or opaque/blob frames.
62
- if (event.source && typeof event.source.url === 'string') {
63
- if (
64
- /\/__preview\//.test(event.source.url) ||
65
- /^(?:blob:|data:|about:srcdoc)/i.test(event.source.url)
66
- ) {
67
- return;
68
- }
69
- }
70
- const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
71
- if (!csp || csp.length > MAX_CONFIG_LENGTH || /[\r\n]/.test(csp)) return;
72
- configuredCsp = csp;
73
- // Acknowledge so the host can wait for confirmation before loading a frame.
74
- try {
75
- if (event.ports && event.ports[0]) {
76
- event.ports[0].postMessage({ type: 'codelab:config-ready' });
77
- } else if (event.source && typeof event.source.postMessage === 'function') {
78
- event.source.postMessage({ type: 'codelab:config-ready' });
79
- }
80
- } catch (err) {
81
- // The client may have navigated away between postMessage and reply.
82
- console.warn('[code-lab] preview-sw: config acknowledgement failed', err);
83
- }
84
- });
85
-
86
- function parsePreviewPath(pathname) {
87
- const match = pathname.match(/^\/__preview\/(\d+)(\/.*)?$/);
88
- if (!match) return null;
89
- return { port: Number(match[1]), path: match[2] || '/' };
90
- }
91
-
92
- function escapeMetaAttr(val) {
93
- return String(val || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
94
- }
95
-
96
- function previewErrorResponse(status, title, message) {
97
- const csp = previewPolicy();
98
- const safeCsp = escapeMetaAttr(csp);
99
- const body = `<!doctype html><meta charset="utf-8">` +
100
- `<meta http-equiv="Content-Security-Policy" content="${safeCsp}">` +
101
- `<title>${title}</title>` +
102
- `<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
103
- `<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
104
- return new Response(body, {
105
- status,
106
- headers: {
107
- 'Content-Type': 'text/html; charset=utf-8',
108
- 'Content-Security-Policy': csp,
109
- 'X-Content-Type-Options': 'nosniff'
110
- }
111
- });
112
- }
113
-
114
- /** Inject the policy, a base URL and the sandbox shims into an HTML response. */
115
- function injectPreviewHead(html, port) {
116
- const csp = previewPolicy();
117
- const safeCsp = escapeMetaAttr(csp);
118
- const shims = previewShims();
119
- const tags = [];
120
- const hasCsp = /<meta[^>]+http-equiv=["']?content-security-policy/i.test(html);
121
- const hasBase = /<base\b/i.test(html);
122
- const hasShims = html.indexOf('data-codelab-preview-shims') !== -1;
123
-
124
- if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${safeCsp}">`);
125
- if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${Number(port) || 3000}/">`);
126
- if (!hasShims && shims) tags.push(shims);
127
- if (tags.length === 0) return html;
128
-
129
- const injection = tags.join('');
130
- if (/<head\b[^>]*>/i.test(html)) {
131
- return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
132
- }
133
- if (/<html\b[^>]*>/i.test(html)) {
134
- return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
135
- }
136
- return `<head>${injection}</head>${html}`;
137
- }
138
-
139
- async function proxyVirtualRequest(event, port, targetPath) {
140
- const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
141
- const workbenchClients = (clients || []).filter((c) => !c.url || !/\/__preview\//.test(c.url));
142
- if (!workbenchClients.length) {
143
- return previewErrorResponse(
144
- 503,
145
- 'No active CodeLab workbench',
146
- 'Return to the CodeLab IDE tab so the virtual runtime can serve this preview.'
147
- );
148
- }
149
-
150
- const client = workbenchClients[0];
151
- const channel = new MessageChannel();
152
- const request = event.request;
153
- const method = request.method || 'GET';
154
-
155
- const headers = {};
156
- try {
157
- for (const [key, value] of request.headers.entries()) {
158
- headers[key.toLowerCase()] = value;
159
- }
160
- } catch (err) {
161
- // Opaque or unsupported header collection; forward without request headers.
162
- console.warn('[code-lab] preview-sw: could not read request headers', err);
163
- }
164
-
165
- let body = null;
166
- if (!['GET', 'HEAD'].includes(method)) {
167
- try {
168
- body = await request.arrayBuffer();
169
- } catch (err) {
170
- console.warn('[code-lab] preview-sw: could not read request body', err);
171
- }
172
- }
173
-
174
- const response = await new Promise((resolve) => {
175
- const closePort = () => {
176
- try {
177
- channel.port1.onmessage = null;
178
- if (typeof channel.port1.close === 'function') channel.port1.close();
179
- } catch (err) {
180
- console.debug('[code-lab] preview-sw: port1.close failed', err);
181
- }
182
- };
183
-
184
- const timer = setTimeout(() => {
185
- closePort();
186
- resolve({
187
- status: 504,
188
- statusText: 'Gateway Timeout',
189
- headers: { 'Content-Type': 'text/html' },
190
- body: '<h1>504 Gateway Timeout</h1><p>The virtual workbench did not respond in time.</p>'
191
- });
192
- }, DISPATCH_TIMEOUT_MS);
193
-
194
- channel.port1.onmessage = (messageEvent) => {
195
- clearTimeout(timer);
196
- closePort();
197
- resolve(messageEvent.data);
198
- };
199
-
200
- client.postMessage(
201
- {
202
- type: 'CODELAB_SW_DISPATCH',
203
- port,
204
- url: `http://127.0.0.1:${port}${targetPath}`,
205
- method,
206
- headers,
207
- body
208
- },
209
- [channel.port2]
210
- );
211
- });
212
-
213
- let responseBody = response && response.body;
214
- const responseHeaders = new Headers((response && response.headers) || {});
215
- const contentType = (responseHeaders.get('content-type') || '').trim();
216
- const isHtmlLike = /\b(?:text\/html|application\/xhtml\+xml)\b/i.test(contentType);
217
- const isExecutableMarkup =
218
- isHtmlLike ||
219
- /\b(?:image\/svg\+xml|application\/xml|text\/xml)\b/i.test(contentType) ||
220
- !contentType;
221
-
222
- if (!contentType) {
223
- responseHeaders.set('Content-Type', 'text/plain; charset=utf-8');
224
- }
225
- // Prevent MIME-sniffing binary/JSON/text responses into executable HTML/SVG on all responses.
226
- responseHeaders.set('X-Content-Type-Options', 'nosniff');
227
-
228
- // Decode Uint8Array / ArrayBuffer HTML/XHTML bodies so head injection always applies.
229
- if (isHtmlLike && responseBody && typeof responseBody !== 'string') {
230
- try {
231
- if (responseBody instanceof ArrayBuffer || ArrayBuffer.isView(responseBody)) {
232
- responseBody = new TextDecoder('utf-8').decode(responseBody);
233
- }
234
- } catch (err) {
235
- console.warn('[code-lab] preview-sw: failed to decode HTML buffer', err);
236
- }
237
- }
238
-
239
- // Inject the policy and a <base> so relative asset URLs in HTML/XHTML responses
240
- // resolve under the `/__preview/:port/` namespace rather than the host root.
241
- if (isHtmlLike && typeof responseBody === 'string') {
242
- responseBody = injectPreviewHead(responseBody, port);
243
- }
244
-
245
- // Attach Content-Security-Policy to every executable document/markup response
246
- // (HTML, XHTML, SVG, XML, and untyped responses) so inline scripts cannot bypass CSP.
247
- if (isExecutableMarkup) {
248
- responseHeaders.set('Content-Security-Policy', previewPolicy());
249
- }
250
-
251
- return new Response(responseBody, {
252
- status: (response && response.status) || 200,
253
- statusText: (response && response.statusText) || 'OK',
254
- headers: responseHeaders
255
- });
256
- }
257
-
258
- self.addEventListener('fetch', (event) => {
259
- let url;
260
- try {
261
- url = new URL(event.request.url);
262
- } catch (err) {
263
- // Non-standard request URL; let the network handle it.
264
- console.warn('[code-lab] preview-sw: unparsable request URL', err);
265
- return;
266
- }
267
-
268
- // Only handle requests on this origin (never proxy third-party traffic).
269
- if (url.origin !== self.location.origin) return;
270
-
271
- const direct = parsePreviewPath(url.pathname);
272
- if (direct) {
273
- const targetPath = (direct.path || '/') + (url.search || '');
274
- event.respondWith(proxyVirtualRequest(event, direct.port, targetPath));
275
- return;
276
- }
277
-
278
- // Secondary route: root-relative sub-resources requested by a preview page
279
- // (e.g. `/app.js` referenced from `/__preview/3000/`) are attributed to the
280
- // originating preview tab via the request referrer. Top-level navigations are
281
- // redirected back under `/__preview/:port/` so no preview document ever runs
282
- // at a non-`/__preview/` URL on the host origin.
283
- const referrer = event.request.referrer || '';
284
- const refMatch = referrer.match(/\/__preview\/(\d+)/);
285
- if (refMatch) {
286
- const refPort = Number(refMatch[1]);
287
- if (event.request.mode === 'navigate') {
288
- const redirectUrl = `${url.origin}${PREVIEW_PREFIX}${refPort}${url.pathname}${url.search || ''}`;
289
- event.respondWith(Response.redirect(redirectUrl, 302));
290
- return;
291
- }
292
- event.respondWith(
293
- proxyVirtualRequest(event, refPort, url.pathname + (url.search || ''))
294
- );
295
- }
296
- });
@@ -1,57 +0,0 @@
1
- /**
2
- * @innovatorved/code-lab — Structured Test Harness & __CODELAB_TEST__: Telemetry Parser
3
- * Normalizes test events from node:test, <codelab/test.hpp>, and codelab_test.py.
4
- */
5
-
6
- export interface TestResultItem {
7
- index: number;
8
- name: string;
9
- status: 'pass' | 'fail';
10
- passed: boolean;
11
- durationMs: number;
12
- error: {
13
- name?: string;
14
- message?: string;
15
- stack?: string;
16
- actual?: string;
17
- expected?: string;
18
- } | null;
19
- }
20
-
21
- export class CodeLabTestParser {
22
- private count = 0;
23
- private onResult: ((item: TestResultItem) => void) | null;
24
-
25
- constructor(onResult?: (item: TestResultItem) => void) {
26
- this.onResult = onResult || null;
27
- }
28
-
29
- public parseLine(line: string): TestResultItem | null {
30
- const trimmed = String(line || '').trim();
31
- const prefix = '__CODELAB_TEST__:';
32
- const idx = trimmed.indexOf(prefix);
33
- if (idx === -1) return null;
34
-
35
- const payload = trimmed.slice(idx + prefix.length).trim();
36
- try {
37
- const data = JSON.parse(payload);
38
- this.count++;
39
- const item: TestResultItem = {
40
- index: typeof data.index === 'number' ? data.index : this.count,
41
- name: String(data.name || `Test #${this.count}`),
42
- status: data.passed ? 'pass' : 'fail',
43
- passed: Boolean(data.passed),
44
- durationMs: typeof data.durationMs === 'number' ? data.durationMs : 0,
45
- error: data.error || null
46
- };
47
-
48
- if (this.onResult) {
49
- this.onResult(item);
50
- }
51
- return item;
52
- } catch (err) {
53
- void err;
54
- return null;
55
- }
56
- }
57
- }