@innovatorved/code-lab 0.1.0

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.
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @innovatorved/code-lab v2.0.0
3
+ * Browser-native IDE, POSIX Shell, Web Worker Node.js/Bun Runtime, and Git Engine.
4
+ */
5
+ export * from './schemas';
6
+ export * from './runtime';
7
+ export { createPosixShell, cloneGitHubRepository, parseGitHubRepoUrl, CodeLabShell } from './shell';
8
+ export * from './terminal';
9
+ export { guidedLabExtension } from './extensions/guided-lab';
10
+ declare const _default: any;
11
+ export default _default;
@@ -0,0 +1,149 @@
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
+ * Zero dependencies. Plain Service Worker script (no module imports) so it can
12
+ * be registered directly from any host origin.
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ const PREVIEW_PREFIX = '/__preview/';
18
+ const DISPATCH_TIMEOUT_MS = 15000;
19
+
20
+ self.addEventListener('install', () => {
21
+ self.skipWaiting();
22
+ });
23
+
24
+ self.addEventListener('activate', (event) => {
25
+ event.waitUntil(self.clients.claim());
26
+ });
27
+
28
+ function parsePreviewPath(pathname) {
29
+ const match = pathname.match(/^\/__preview\/(\d+)(\/.*)?$/);
30
+ if (!match) return null;
31
+ return { port: Number(match[1]), path: match[2] || '/' };
32
+ }
33
+
34
+ function previewErrorResponse(status, title, message) {
35
+ const body = `<!doctype html><meta charset="utf-8"><title>${title}</title>` +
36
+ `<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
37
+ `<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
38
+ return new Response(body, {
39
+ status,
40
+ headers: { 'Content-Type': 'text/html; charset=utf-8' }
41
+ });
42
+ }
43
+
44
+ async function proxyVirtualRequest(event, port, targetPath) {
45
+ const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
46
+ if (!clients || !clients.length) {
47
+ return previewErrorResponse(
48
+ 503,
49
+ 'No active CodeLab workbench',
50
+ 'Return to the CodeLab IDE tab so the virtual runtime can serve this preview.'
51
+ );
52
+ }
53
+
54
+ const client = clients[0];
55
+ const channel = new MessageChannel();
56
+ const request = event.request;
57
+ const method = request.method || 'GET';
58
+
59
+ const headers = {};
60
+ try {
61
+ for (const [key, value] of request.headers.entries()) {
62
+ headers[key.toLowerCase()] = value;
63
+ }
64
+ } catch (_) {}
65
+
66
+ let body = null;
67
+ if (!['GET', 'HEAD'].includes(method)) {
68
+ try {
69
+ body = await request.arrayBuffer();
70
+ } catch (_) {}
71
+ }
72
+
73
+ const response = await new Promise((resolve) => {
74
+ const timer = setTimeout(() => {
75
+ resolve({
76
+ status: 504,
77
+ statusText: 'Gateway Timeout',
78
+ headers: { 'Content-Type': 'text/html' },
79
+ body: '<h1>504 Gateway Timeout</h1><p>The virtual workbench did not respond in time.</p>'
80
+ });
81
+ }, DISPATCH_TIMEOUT_MS);
82
+
83
+ channel.port1.onmessage = (messageEvent) => {
84
+ clearTimeout(timer);
85
+ resolve(messageEvent.data);
86
+ };
87
+
88
+ client.postMessage(
89
+ {
90
+ type: 'CODELAB_SW_DISPATCH',
91
+ port,
92
+ url: `http://127.0.0.1:${port}${targetPath}`,
93
+ method,
94
+ headers,
95
+ body
96
+ },
97
+ [channel.port2]
98
+ );
99
+ });
100
+
101
+ let responseBody = response && response.body;
102
+ const responseHeaders = new Headers((response && response.headers) || {});
103
+ const contentType = responseHeaders.get('content-type') || '';
104
+
105
+ // Inject a <base> so relative asset URLs in HTML responses resolve under the
106
+ // `/__preview/:port/` namespace rather than the host document root.
107
+ 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
+ }
112
+ }
113
+
114
+ return new Response(responseBody, {
115
+ status: (response && response.status) || 200,
116
+ statusText: (response && response.statusText) || 'OK',
117
+ headers: responseHeaders
118
+ });
119
+ }
120
+
121
+ self.addEventListener('fetch', (event) => {
122
+ let url;
123
+ try {
124
+ url = new URL(event.request.url);
125
+ } catch (_) {
126
+ return;
127
+ }
128
+
129
+ // Only handle requests on this origin (never proxy third-party traffic).
130
+ if (url.origin !== self.location.origin) return;
131
+
132
+ const direct = parsePreviewPath(url.pathname);
133
+ if (direct) {
134
+ const targetPath = (direct.path || '/') + (url.search || '');
135
+ event.respondWith(proxyVirtualRequest(event, direct.port, targetPath));
136
+ return;
137
+ }
138
+
139
+ // Secondary route: root-relative sub-resources requested by a preview page
140
+ // (e.g. `/app.js` referenced from `/__preview/3000/`) are attributed to the
141
+ // originating preview tab via the request referrer.
142
+ const referrer = event.request.referrer || '';
143
+ const refMatch = referrer.match(/\/__preview\/(\d+)/);
144
+ if (refMatch) {
145
+ event.respondWith(
146
+ proxyVirtualRequest(event, Number(refMatch[1]), url.pathname + (url.search || ''))
147
+ );
148
+ }
149
+ });
@@ -0,0 +1,48 @@
1
+ declare const _hostRuntime: any;
2
+ export interface RuntimeExecutionResult {
3
+ ok: boolean;
4
+ exitCode: number;
5
+ durationMs: number;
6
+ stdout: string;
7
+ stderr: string;
8
+ testResults: any[];
9
+ fsSnapshot: any[];
10
+ httpTrace: any[];
11
+ error?: {
12
+ message: string;
13
+ stack?: string;
14
+ };
15
+ outputTruncated?: boolean;
16
+ replValue?: any;
17
+ cancelled?: boolean;
18
+ testSummary?: {
19
+ total: number;
20
+ passed: number;
21
+ failed: number;
22
+ };
23
+ }
24
+ export declare const VirtualBuffer: any;
25
+ export declare const VirtualCrypto: any;
26
+ export declare const VirtualZlib: any;
27
+ export declare const VirtualPath: any;
28
+ export declare const VirtualOs: any;
29
+ export declare const VirtualAssert: any;
30
+ export declare const EventEmitter: any;
31
+ export declare const VirtualUtil: any;
32
+ export declare const VirtualUrl: any;
33
+ export declare const VirtualQuerystring: any;
34
+ export declare const VirtualStream: any;
35
+ export declare const VirtualStreamPromises: any;
36
+ export declare const VirtualStringDecoder: any;
37
+ export declare const VirtualDns: any;
38
+ export declare const createVirtualFs: (options?: any) => any;
39
+ export declare const createVirtualHttp: (portTable?: any, vfs?: any) => any;
40
+ export declare const createVirtualNet: (portTable?: any) => any;
41
+ export declare const transpileTS: (code: string, filename?: string) => string;
42
+ export declare const preloadNpmPackages: (packages?: Record<string, any>) => void;
43
+ export declare const createVirtualPortTable: () => any;
44
+ export declare const executeInVirtualRuntime: (options?: any) => Promise<RuntimeExecutionResult>;
45
+ export declare const createWorkerRuntimeSource: () => string;
46
+ export declare const cancelWorkerExecution: (reason?: string, instanceId?: string) => boolean;
47
+ export declare const executeInWorker: (options?: any) => Promise<RuntimeExecutionResult>;
48
+ export default _hostRuntime;