@innovatorved/code-lab 0.1.7 → 0.1.8
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 +26 -0
- package/dist/code-lab.d.ts +271 -1
- package/dist/code-lab.esm.js +2687 -172
- package/dist/code-lab.js +2647 -170
- 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 +412 -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 +216 -36
- package/dist/shell.js +216 -36
- 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 +26 -0
- package/src/csp.ts +396 -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 +114 -35
- package/src/storage.ts +377 -0
- package/src/terminal.ts +20 -6
- package/src/workbench.ts +728 -95
- package/src/zip.ts +326 -0
package/src/logger.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @innovatorved/code-lab — Shared Leveled Logger & Typed Error Hierarchy
|
|
3
|
+
* ============================================================================
|
|
4
|
+
* Bundled as `CodeLabLogger` into the runtime, shell, terminal, and workbench
|
|
5
|
+
* bundles so no subsystem needs empty `catch` blocks or ad-hoc console calls.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const LOG_PREFIX = '[code-lab]';
|
|
9
|
+
|
|
10
|
+
export type CodeLabLogLevel = 'debug' | 'info' | 'warn' | 'error';
|
|
11
|
+
|
|
12
|
+
export interface CodeLabLogSink {
|
|
13
|
+
debug?: (...args: unknown[]) => void;
|
|
14
|
+
info?: (...args: unknown[]) => void;
|
|
15
|
+
warn?: (...args: unknown[]) => void;
|
|
16
|
+
error?: (...args: unknown[]) => void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface CodeLabLoggerOptions {
|
|
20
|
+
logger?: CodeLabLogSink | null;
|
|
21
|
+
debug?: boolean;
|
|
22
|
+
prefix?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface CodeLabLogger {
|
|
26
|
+
debug: (...args: unknown[]) => void;
|
|
27
|
+
info: (...args: unknown[]) => void;
|
|
28
|
+
warn: (...args: unknown[]) => void;
|
|
29
|
+
error: (...args: unknown[]) => void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type CodeLabErrorCode =
|
|
33
|
+
| 'E_SAVE'
|
|
34
|
+
| 'E_PERSISTENCE'
|
|
35
|
+
| 'E_INSTALL'
|
|
36
|
+
| 'E_PREVIEW'
|
|
37
|
+
| 'E_RUNTIME'
|
|
38
|
+
| 'E_SHELL'
|
|
39
|
+
| 'E_CLONE'
|
|
40
|
+
| 'E_CONFIG';
|
|
41
|
+
|
|
42
|
+
export interface CodeLabErrorOptions {
|
|
43
|
+
cause?: unknown;
|
|
44
|
+
recoverable?: boolean;
|
|
45
|
+
details?: Record<string, unknown>;
|
|
46
|
+
context?: Record<string, unknown>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Structured error surfaced through `wb.on('error', ...)` and `wb.on('save-state', ...)`.
|
|
51
|
+
*/
|
|
52
|
+
export class CodeLabError extends Error {
|
|
53
|
+
readonly code: CodeLabErrorCode;
|
|
54
|
+
readonly options: CodeLabErrorOptions;
|
|
55
|
+
override readonly cause?: unknown;
|
|
56
|
+
readonly recoverable: boolean;
|
|
57
|
+
readonly details?: Record<string, unknown>;
|
|
58
|
+
readonly context?: Record<string, unknown>;
|
|
59
|
+
|
|
60
|
+
constructor(code: CodeLabErrorCode, message: string, options: CodeLabErrorOptions = {}) {
|
|
61
|
+
super(message);
|
|
62
|
+
this.name = 'CodeLabError';
|
|
63
|
+
this.code = code;
|
|
64
|
+
this.options = options;
|
|
65
|
+
this.cause = options.cause;
|
|
66
|
+
this.recoverable = options.recoverable !== false;
|
|
67
|
+
const meta = options.details ?? options.context;
|
|
68
|
+
if (meta !== undefined) {
|
|
69
|
+
this.details = meta;
|
|
70
|
+
this.context = meta;
|
|
71
|
+
}
|
|
72
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function isCodeLabError(value: unknown): value is CodeLabError {
|
|
77
|
+
return Boolean(
|
|
78
|
+
value &&
|
|
79
|
+
typeof value === 'object' &&
|
|
80
|
+
(value instanceof CodeLabError ||
|
|
81
|
+
((value as { name?: unknown }).name === 'CodeLabError' &&
|
|
82
|
+
typeof (value as { code?: unknown }).code === 'string'))
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Small leveled logger. Hosts can pass `options.logger` to route diagnostics
|
|
88
|
+
* into their own telemetry; `options.debug` enables verbose output. Errors and
|
|
89
|
+
* warnings are never silently discarded.
|
|
90
|
+
*/
|
|
91
|
+
export function createLogger(options: CodeLabLoggerOptions = {}): CodeLabLogger {
|
|
92
|
+
const sink = options.logger ?? null;
|
|
93
|
+
const debugEnabled = options.debug === true;
|
|
94
|
+
const prefix = options.prefix || LOG_PREFIX;
|
|
95
|
+
|
|
96
|
+
const write = (level: CodeLabLogLevel, args: unknown[]): void => {
|
|
97
|
+
if (level === 'debug' && !debugEnabled) return;
|
|
98
|
+
if (sink && typeof sink[level] === 'function') {
|
|
99
|
+
let sinkError: unknown = null;
|
|
100
|
+
try {
|
|
101
|
+
(sink[level] as (...a: unknown[]) => void)(...args);
|
|
102
|
+
return;
|
|
103
|
+
} catch (err) {
|
|
104
|
+
// A broken host logger must not break the IDE; fall through to console.
|
|
105
|
+
sinkError = err;
|
|
106
|
+
}
|
|
107
|
+
void sinkError;
|
|
108
|
+
}
|
|
109
|
+
const consoleObj = typeof console !== 'undefined' ? console : null;
|
|
110
|
+
const fn = consoleObj ? consoleObj[level] : null;
|
|
111
|
+
if (typeof fn === 'function') {
|
|
112
|
+
fn.call(consoleObj, prefix, ...args);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
debug: (...args: unknown[]) => write('debug', args),
|
|
118
|
+
info: (...args: unknown[]) => write('info', args),
|
|
119
|
+
warn: (...args: unknown[]) => write('warn', args),
|
|
120
|
+
error: (...args: unknown[]) => write('error', args)
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export const DEFAULT_LOGGER: CodeLabLogger = createLogger();
|
|
125
|
+
|
|
126
|
+
const _loggerNamespace = {
|
|
127
|
+
LOG_PREFIX,
|
|
128
|
+
CodeLabError,
|
|
129
|
+
isCodeLabError,
|
|
130
|
+
createLogger,
|
|
131
|
+
DEFAULT_LOGGER
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const _globalRoot = typeof globalThis !== 'undefined' ? (globalThis as Record<string, unknown>) : null;
|
|
135
|
+
if (_globalRoot && !_globalRoot.CodeLabLogger) {
|
|
136
|
+
_globalRoot.CodeLabLogger = _loggerNamespace;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export default _loggerNamespace;
|
package/src/preview-sw.js
CHANGED
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
* This enables "pop out to tab" Web Preview for virtual HTTP / Bun servers that
|
|
9
9
|
* exist only inside the workbench's in-memory runtime (no real OS socket).
|
|
10
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
|
+
*
|
|
11
15
|
* Zero dependencies. Plain Service Worker script (no module imports) so it can
|
|
12
16
|
* be registered directly from any host origin.
|
|
13
17
|
*/
|
|
@@ -16,49 +20,32 @@
|
|
|
16
20
|
|
|
17
21
|
const PREVIEW_PREFIX = '/__preview/';
|
|
18
22
|
const DISPATCH_TIMEOUT_MS = 15000;
|
|
23
|
+
const MAX_CONFIG_LENGTH = 8192;
|
|
19
24
|
|
|
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('; ');
|
|
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;
|
|
41
28
|
|
|
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;
|
|
29
|
+
function cspModule() {
|
|
30
|
+
// `CodeLabCsp` is declared by the prepended csp bundle (src/csp.ts).
|
|
31
|
+
return typeof CodeLabCsp !== 'undefined' ? CodeLabCsp : null;
|
|
32
|
+
}
|
|
51
33
|
|
|
52
|
-
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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' });
|
|
60
43
|
}
|
|
61
44
|
|
|
45
|
+
function previewShims() {
|
|
46
|
+
const csp = cspModule();
|
|
47
|
+
return csp ? csp.buildPreviewShims() : '';
|
|
48
|
+
}
|
|
62
49
|
|
|
63
50
|
self.addEventListener('install', () => {
|
|
64
51
|
self.skipWaiting();
|
|
@@ -68,6 +55,25 @@ self.addEventListener('activate', (event) => {
|
|
|
68
55
|
event.waitUntil(self.clients.claim());
|
|
69
56
|
});
|
|
70
57
|
|
|
58
|
+
self.addEventListener('message', (event) => {
|
|
59
|
+
const data = event && event.data;
|
|
60
|
+
if (!data || data.type !== 'codelab:config') return;
|
|
61
|
+
const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
|
|
62
|
+
if (!csp || csp.length > MAX_CONFIG_LENGTH) return;
|
|
63
|
+
configuredCsp = csp;
|
|
64
|
+
// Acknowledge so the host can wait for confirmation before loading a frame.
|
|
65
|
+
try {
|
|
66
|
+
if (event.ports && event.ports[0]) {
|
|
67
|
+
event.ports[0].postMessage({ type: 'codelab:config-ready' });
|
|
68
|
+
} else if (event.source && typeof event.source.postMessage === 'function') {
|
|
69
|
+
event.source.postMessage({ type: 'codelab:config-ready' });
|
|
70
|
+
}
|
|
71
|
+
} catch (err) {
|
|
72
|
+
// The client may have navigated away between postMessage and reply.
|
|
73
|
+
console.warn('[code-lab] preview-sw: config acknowledgement failed', err);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
|
|
71
77
|
function parsePreviewPath(pathname) {
|
|
72
78
|
const match = pathname.match(/^\/__preview\/(\d+)(\/.*)?$/);
|
|
73
79
|
if (!match) return null;
|
|
@@ -75,8 +81,9 @@ function parsePreviewPath(pathname) {
|
|
|
75
81
|
}
|
|
76
82
|
|
|
77
83
|
function previewErrorResponse(status, title, message) {
|
|
84
|
+
const csp = previewPolicy();
|
|
78
85
|
const body = `<!doctype html><meta charset="utf-8">` +
|
|
79
|
-
`<meta http-equiv="Content-Security-Policy" content="${
|
|
86
|
+
`<meta http-equiv="Content-Security-Policy" content="${csp}">` +
|
|
80
87
|
`<title>${title}</title>` +
|
|
81
88
|
`<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
|
|
82
89
|
`<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
|
|
@@ -84,12 +91,36 @@ function previewErrorResponse(status, title, message) {
|
|
|
84
91
|
status,
|
|
85
92
|
headers: {
|
|
86
93
|
'Content-Type': 'text/html; charset=utf-8',
|
|
87
|
-
'Content-Security-Policy':
|
|
94
|
+
'Content-Security-Policy': csp,
|
|
88
95
|
'X-Content-Type-Options': 'nosniff'
|
|
89
96
|
}
|
|
90
97
|
});
|
|
91
98
|
}
|
|
92
99
|
|
|
100
|
+
/** Inject the policy, a base URL and the sandbox shims into an HTML response. */
|
|
101
|
+
function injectPreviewHead(html, port) {
|
|
102
|
+
const csp = previewPolicy();
|
|
103
|
+
const shims = previewShims();
|
|
104
|
+
const tags = [];
|
|
105
|
+
const hasCsp = /<meta[^>]+http-equiv=["']?content-security-policy/i.test(html);
|
|
106
|
+
const hasBase = /<base\b/i.test(html);
|
|
107
|
+
const hasShims = html.indexOf('data-codelab-preview-shims') !== -1;
|
|
108
|
+
|
|
109
|
+
if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
|
|
110
|
+
if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
|
|
111
|
+
if (!hasShims && shims) tags.push(shims);
|
|
112
|
+
if (tags.length === 0) return html;
|
|
113
|
+
|
|
114
|
+
const injection = tags.join('');
|
|
115
|
+
if (/<head\b[^>]*>/i.test(html)) {
|
|
116
|
+
return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
|
|
117
|
+
}
|
|
118
|
+
if (/<html\b[^>]*>/i.test(html)) {
|
|
119
|
+
return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
|
|
120
|
+
}
|
|
121
|
+
return `<head>${injection}</head>${html}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
93
124
|
async function proxyVirtualRequest(event, port, targetPath) {
|
|
94
125
|
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
|
95
126
|
if (!clients || !clients.length) {
|
|
@@ -110,13 +141,18 @@ async function proxyVirtualRequest(event, port, targetPath) {
|
|
|
110
141
|
for (const [key, value] of request.headers.entries()) {
|
|
111
142
|
headers[key.toLowerCase()] = value;
|
|
112
143
|
}
|
|
113
|
-
} catch (
|
|
144
|
+
} catch (err) {
|
|
145
|
+
// Opaque or unsupported header collection; forward without request headers.
|
|
146
|
+
console.warn('[code-lab] preview-sw: could not read request headers', err);
|
|
147
|
+
}
|
|
114
148
|
|
|
115
149
|
let body = null;
|
|
116
150
|
if (!['GET', 'HEAD'].includes(method)) {
|
|
117
151
|
try {
|
|
118
152
|
body = await request.arrayBuffer();
|
|
119
|
-
} catch (
|
|
153
|
+
} catch (err) {
|
|
154
|
+
console.warn('[code-lab] preview-sw: could not read request body', err);
|
|
155
|
+
}
|
|
120
156
|
}
|
|
121
157
|
|
|
122
158
|
const response = await new Promise((resolve) => {
|
|
@@ -151,11 +187,11 @@ async function proxyVirtualRequest(event, port, targetPath) {
|
|
|
151
187
|
const responseHeaders = new Headers((response && response.headers) || {});
|
|
152
188
|
const contentType = responseHeaders.get('content-type') || '';
|
|
153
189
|
|
|
154
|
-
// Inject
|
|
155
|
-
// under the `/__preview/:port/` namespace rather than the host
|
|
190
|
+
// Inject the policy and a <base> so relative asset URLs in HTML responses
|
|
191
|
+
// resolve under the `/__preview/:port/` namespace rather than the host root.
|
|
156
192
|
if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
|
|
157
193
|
responseBody = injectPreviewHead(responseBody, port);
|
|
158
|
-
responseHeaders.set('Content-Security-Policy',
|
|
194
|
+
responseHeaders.set('Content-Security-Policy', previewPolicy());
|
|
159
195
|
responseHeaders.set('X-Content-Type-Options', 'nosniff');
|
|
160
196
|
}
|
|
161
197
|
|
|
@@ -170,7 +206,9 @@ self.addEventListener('fetch', (event) => {
|
|
|
170
206
|
let url;
|
|
171
207
|
try {
|
|
172
208
|
url = new URL(event.request.url);
|
|
173
|
-
} catch (
|
|
209
|
+
} catch (err) {
|
|
210
|
+
// Non-standard request URL; let the network handle it.
|
|
211
|
+
console.warn('[code-lab] preview-sw: unparsable request URL', err);
|
|
174
212
|
return;
|
|
175
213
|
}
|
|
176
214
|
|
package/src/runtime.ts
CHANGED
|
@@ -20,6 +20,14 @@ if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined')
|
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
22
|
function __initVirtualRuntime(rootScope) {
|
|
23
|
+
const _runtimeLogger = (rootScope && rootScope.CodeLabLogger && typeof rootScope.CodeLabLogger.createLogger === 'function')
|
|
24
|
+
? rootScope.CodeLabLogger.createLogger()
|
|
25
|
+
: {
|
|
26
|
+
debug() {},
|
|
27
|
+
info() {},
|
|
28
|
+
warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
|
|
29
|
+
error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
|
|
30
|
+
};
|
|
23
31
|
// =========================================================================
|
|
24
32
|
// 1. UTF-8 / HEX / BASE64 / BASE64URL CODECS & VIRTUAL BUFFER
|
|
25
33
|
// =========================================================================
|
|
@@ -1579,7 +1587,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
1579
1587
|
},
|
|
1580
1588
|
final(cb) {
|
|
1581
1589
|
if (fd !== null) {
|
|
1582
|
-
try { fsShim.closeSync(fd); } catch (
|
|
1590
|
+
try { fsShim.closeSync(fd); } catch (err) { _runtimeLogger.debug('vfs writeStream closeSync failed', err); }
|
|
1583
1591
|
fd = null;
|
|
1584
1592
|
}
|
|
1585
1593
|
cb(null);
|
|
@@ -2099,7 +2107,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
2099
2107
|
return pathname + search + hash;
|
|
2100
2108
|
}
|
|
2101
2109
|
return resolvedUrl.href;
|
|
2102
|
-
} catch (
|
|
2110
|
+
} catch (err) {
|
|
2111
|
+
_runtimeLogger.debug('url.resolve fallback used', err);
|
|
2112
|
+
}
|
|
2103
2113
|
}
|
|
2104
2114
|
if (toStr.startsWith('/')) {
|
|
2105
2115
|
const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]+)/.exec(fromStr);
|
|
@@ -2538,10 +2548,10 @@ function __initVirtualRuntime(rootScope) {
|
|
|
2538
2548
|
for (const [port, entry] of Array.from(table.entries())) {
|
|
2539
2549
|
if (entry.pid !== undefined && String(entry.pid) === pStr) {
|
|
2540
2550
|
if (entry.server && typeof entry.server.close === 'function') {
|
|
2541
|
-
try { entry.server.close(); } catch (
|
|
2551
|
+
try { entry.server.close(); } catch (err) { _runtimeLogger.debug('portTable server.close failed', err); }
|
|
2542
2552
|
}
|
|
2543
2553
|
if (typeof entry.stop === 'function') {
|
|
2544
|
-
try { entry.stop(); } catch (
|
|
2554
|
+
try { entry.stop(); } catch (err) { _runtimeLogger.debug('portTable entry.stop failed', err); }
|
|
2545
2555
|
}
|
|
2546
2556
|
// Avoid a double 'close' emission when entry.server.close() already
|
|
2547
2557
|
// unregistered the port through unregisterServer().
|
|
@@ -3178,7 +3188,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
3178
3188
|
},
|
|
3179
3189
|
closeAllServers() {
|
|
3180
3190
|
for (const s of Array.from(activeServers.values())) {
|
|
3181
|
-
try { s.close(); } catch (
|
|
3191
|
+
try { s.close(); } catch (err) { _runtimeLogger.debug('vhttp closeAllServers close failed', err); }
|
|
3182
3192
|
}
|
|
3183
3193
|
activeServers.clear();
|
|
3184
3194
|
}
|
|
@@ -4004,7 +4014,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4004
4014
|
|
|
4005
4015
|
function closeAllServers() {
|
|
4006
4016
|
for (const srv of servers.values()) {
|
|
4007
|
-
try { srv.close(); } catch (
|
|
4017
|
+
try { srv.close(); } catch (err) { _runtimeLogger.debug('vnet closeAllServers close failed', err); }
|
|
4008
4018
|
}
|
|
4009
4019
|
servers.clear();
|
|
4010
4020
|
}
|
|
@@ -5084,7 +5094,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5084
5094
|
try {
|
|
5085
5095
|
const pkgJson = JSON.parse(content);
|
|
5086
5096
|
for (const dep of Object.keys(pkgJson.dependencies || {})) addSpec(dep);
|
|
5087
|
-
} catch (
|
|
5097
|
+
} catch (err) {
|
|
5098
|
+
_runtimeLogger.debug('preloadNpmPackages invalid package.json', err);
|
|
5099
|
+
}
|
|
5088
5100
|
continue;
|
|
5089
5101
|
}
|
|
5090
5102
|
const reqRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
@@ -5113,7 +5125,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5113
5125
|
const meta = await res.json();
|
|
5114
5126
|
deps = Object.keys((meta && meta.dependencies) || {});
|
|
5115
5127
|
}
|
|
5116
|
-
} catch (
|
|
5128
|
+
} catch (err) {
|
|
5129
|
+
_runtimeLogger.debug('preloadNpmPackages metadata fetch failed', { pkg, err });
|
|
5130
|
+
}
|
|
5117
5131
|
_npmMetadataCache.set(pkg, deps);
|
|
5118
5132
|
}));
|
|
5119
5133
|
for (const pkg of pending) {
|
|
@@ -5131,7 +5145,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5131
5145
|
continue;
|
|
5132
5146
|
}
|
|
5133
5147
|
if (typeof onProgress === 'function') {
|
|
5134
|
-
try { onProgress(pkg); } catch (
|
|
5148
|
+
try { onProgress(pkg); } catch (err) { _runtimeLogger.debug('preloadNpmPackages onProgress callback failed', err); }
|
|
5135
5149
|
}
|
|
5136
5150
|
if (typeof fetch === 'function') {
|
|
5137
5151
|
try {
|
|
@@ -5141,7 +5155,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5141
5155
|
if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
|
|
5142
5156
|
loaded[pkg] = text;
|
|
5143
5157
|
}
|
|
5144
|
-
} catch (
|
|
5158
|
+
} catch (err) {
|
|
5159
|
+
_runtimeLogger.debug('preloadNpmPackages package fetch failed', { pkg, err });
|
|
5160
|
+
}
|
|
5145
5161
|
}
|
|
5146
5162
|
}
|
|
5147
5163
|
return loaded;
|
|
@@ -5333,7 +5349,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5333
5349
|
const dir = VirtualPath.dirname(abs);
|
|
5334
5350
|
if (!vfs.existsSync(dir)) vfs.mkdirSync(dir, { recursive: true });
|
|
5335
5351
|
vfs.writeFileSync(abs, content);
|
|
5336
|
-
} catch (
|
|
5352
|
+
} catch (err) {
|
|
5353
|
+
_runtimeLogger.warn('vfs initial file seed failed', { abs, err });
|
|
5354
|
+
}
|
|
5337
5355
|
}
|
|
5338
5356
|
}
|
|
5339
5357
|
const vhttp = createVirtualHttp(resourceTracker, activePortTable);
|
|
@@ -5778,7 +5796,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5778
5796
|
exitCode = Number(code) || 0;
|
|
5779
5797
|
if (!hasExited) {
|
|
5780
5798
|
hasExited = true;
|
|
5781
|
-
try { sandboxProcess.emit('exit', exitCode); } catch (
|
|
5799
|
+
try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('process exit listener threw', err); }
|
|
5782
5800
|
}
|
|
5783
5801
|
if (syncExecDepth > 0) {
|
|
5784
5802
|
throw new ProcessExitSignal(exitCode);
|
|
@@ -5811,8 +5829,8 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5811
5829
|
resourceTracker.inFlightHttp.clear();
|
|
5812
5830
|
|
|
5813
5831
|
if (!isBackground) {
|
|
5814
|
-
try { vhttp.closeAllServers(); } catch (
|
|
5815
|
-
try { vnet.closeAllServers(); } catch (
|
|
5832
|
+
try { vhttp.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vhttp closeAllServers failed', err); }
|
|
5833
|
+
try { vnet.closeAllServers(); } catch (err) { _runtimeLogger.debug('SIGINT vnet closeAllServers failed', err); }
|
|
5816
5834
|
}
|
|
5817
5835
|
};
|
|
5818
5836
|
|
|
@@ -5922,10 +5940,10 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5922
5940
|
sandboxConsole.log(`✗ ${fullName}\n ${e && e.stack ? e.stack : e}`);
|
|
5923
5941
|
} finally {
|
|
5924
5942
|
for (const ae of hooksSnapshot.afterEachList) {
|
|
5925
|
-
try { await ae(); } catch (
|
|
5943
|
+
try { await ae(); } catch (err) { _runtimeLogger.debug('node:test afterEach hook failed', err); }
|
|
5926
5944
|
}
|
|
5927
5945
|
for (const af of hooksSnapshot.afterToRun) {
|
|
5928
|
-
try { await af(); } catch (
|
|
5946
|
+
try { await af(); } catch (err) { _runtimeLogger.debug('node:test after hook failed', err); }
|
|
5929
5947
|
}
|
|
5930
5948
|
hooksSnapshot.afterToRun.length = 0;
|
|
5931
5949
|
}
|
|
@@ -5973,7 +5991,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5973
5991
|
const afters = [...suiteCtx.afterCallbacks];
|
|
5974
5992
|
const cleanupTask = nodeTestChain.then(async () => {
|
|
5975
5993
|
for (const af of afters) {
|
|
5976
|
-
try { await af(); } catch (
|
|
5994
|
+
try { await af(); } catch (err) { _runtimeLogger.debug('node:test suite after hook failed', err); }
|
|
5977
5995
|
}
|
|
5978
5996
|
});
|
|
5979
5997
|
nodeTestChain = cleanupTask.catch(() => {});
|
|
@@ -6019,7 +6037,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
6019
6037
|
getEntriesByName: (n, t) => (entry.name === n && (!t || entry.entryType === t) ? [entry] : []),
|
|
6020
6038
|
getEntriesByType: (t) => (entry.entryType === t ? [entry] : [])
|
|
6021
6039
|
};
|
|
6022
|
-
try { obs._cb(list, obs); } catch (
|
|
6040
|
+
try { obs._cb(list, obs); } catch (err) { _runtimeLogger.debug('PerformanceObserver callback failed', err); }
|
|
6023
6041
|
}
|
|
6024
6042
|
}
|
|
6025
6043
|
}
|
|
@@ -6124,7 +6142,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
6124
6142
|
getEntriesByName: (n, t) => buffered.filter((e) => e.name === n && (!t || e.entryType === t)),
|
|
6125
6143
|
getEntriesByType: (t) => buffered.filter((e) => e.entryType === t)
|
|
6126
6144
|
};
|
|
6127
|
-
queueMicrotask(() => { try { this._cb(list, this); } catch (
|
|
6145
|
+
queueMicrotask(() => { try { this._cb(list, this); } catch (err) { _runtimeLogger.debug('PerformanceObserver buffered callback failed', err); } });
|
|
6128
6146
|
}
|
|
6129
6147
|
}
|
|
6130
6148
|
}
|
|
@@ -7395,7 +7413,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7395
7413
|
const resolvedEntry = resolveFileOrDirCandidates(VirtualPath.resolve(base, entryRel));
|
|
7396
7414
|
if (resolvedEntry) return resolvedEntry;
|
|
7397
7415
|
}
|
|
7398
|
-
} catch (
|
|
7416
|
+
} catch (err) {
|
|
7417
|
+
_runtimeLogger.debug('resolveFileOrDirCandidates package.json parse failed', err);
|
|
7418
|
+
}
|
|
7399
7419
|
}
|
|
7400
7420
|
const indexCandidates = ['index.js', 'index.ts', 'index.mjs', 'index.cjs', 'index.json'];
|
|
7401
7421
|
for (const idx of indexCandidates) {
|
|
@@ -7465,7 +7485,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7465
7485
|
if (found) return found;
|
|
7466
7486
|
}
|
|
7467
7487
|
}
|
|
7468
|
-
} catch (
|
|
7488
|
+
} catch (err) {
|
|
7489
|
+
_runtimeLogger.debug('resolveModulePath subpath package.json parse failed', err);
|
|
7490
|
+
}
|
|
7469
7491
|
}
|
|
7470
7492
|
const foundSub = resolveFileOrDirCandidates(VirtualPath.join(pkgRoot, subpath));
|
|
7471
7493
|
if (foundSub) return foundSub;
|
|
@@ -7507,7 +7529,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7507
7529
|
if (isLocal && activePortTable) {
|
|
7508
7530
|
return await activePortTable.dispatchRequest(urlStr, finalInit);
|
|
7509
7531
|
}
|
|
7510
|
-
} catch (
|
|
7532
|
+
} catch (err) {
|
|
7533
|
+
_runtimeLogger.debug('virtualFetch local URL dispatch skipped', err);
|
|
7534
|
+
}
|
|
7511
7535
|
|
|
7512
7536
|
if (typeof globalThis.fetch === 'function') {
|
|
7513
7537
|
return await globalThis.fetch(urlOrReq, init);
|
|
@@ -7674,7 +7698,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7674
7698
|
if (err instanceof SyntaxError && (/\bawait\b/.test(body) || /await/i.test(err.message))) {
|
|
7675
7699
|
try {
|
|
7676
7700
|
return new AsyncFunction(...argNames, body);
|
|
7677
|
-
} catch (
|
|
7701
|
+
} catch (asyncErr) {
|
|
7702
|
+
_runtimeLogger.debug('AsyncFunction compilation fallback failed', asyncErr);
|
|
7703
|
+
}
|
|
7678
7704
|
}
|
|
7679
7705
|
if (
|
|
7680
7706
|
err &&
|
|
@@ -7728,7 +7754,9 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7728
7754
|
if (signal && onAbort) {
|
|
7729
7755
|
try {
|
|
7730
7756
|
signal.removeEventListener('abort', onAbort);
|
|
7731
|
-
} catch (
|
|
7757
|
+
} catch (err) {
|
|
7758
|
+
_runtimeLogger.debug('raceWithAbort removeEventListener failed', err);
|
|
7759
|
+
}
|
|
7732
7760
|
}
|
|
7733
7761
|
};
|
|
7734
7762
|
|
|
@@ -7887,11 +7915,11 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7887
7915
|
}
|
|
7888
7916
|
} finally {
|
|
7889
7917
|
if (signal && signalListener) {
|
|
7890
|
-
try { signal.removeEventListener('abort', signalListener); } catch (
|
|
7918
|
+
try { signal.removeEventListener('abort', signalListener); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime removeEventListener failed', err); }
|
|
7891
7919
|
}
|
|
7892
7920
|
if (!hasExited) {
|
|
7893
7921
|
hasExited = true;
|
|
7894
|
-
try { sandboxProcess.emit('exit', exitCode); } catch (
|
|
7922
|
+
try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
|
|
7895
7923
|
}
|
|
7896
7924
|
for (const rawId of resourceTracker.allTimers) {
|
|
7897
7925
|
clearTimeout(rawId);
|
|
@@ -7999,7 +8027,16 @@ function createWorkerRuntimeSource() {
|
|
|
7999
8027
|
return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
|
|
8000
8028
|
}
|
|
8001
8029
|
|
|
8002
|
-
const
|
|
8030
|
+
const _hostScope = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global);
|
|
8031
|
+
const _hostLogger = (_hostScope && _hostScope.CodeLabLogger && typeof _hostScope.CodeLabLogger.createLogger === 'function')
|
|
8032
|
+
? _hostScope.CodeLabLogger.createLogger()
|
|
8033
|
+
: {
|
|
8034
|
+
debug() {},
|
|
8035
|
+
info() {},
|
|
8036
|
+
warn(msg, meta) { if (typeof console !== 'undefined' && console.warn) console.warn('[CodeLab]', msg, meta || ''); },
|
|
8037
|
+
error(msg, meta) { if (typeof console !== 'undefined' && console.error) console.error('[CodeLab]', msg, meta || ''); }
|
|
8038
|
+
};
|
|
8039
|
+
const _hostRuntime = __initVirtualRuntime(_hostScope);
|
|
8003
8040
|
_hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
|
|
8004
8041
|
|
|
8005
8042
|
let _cachedWorkerUrl = null;
|
|
@@ -8023,7 +8060,7 @@ function _ensureWarmWorker() {
|
|
|
8023
8060
|
|
|
8024
8061
|
function _destroyWarmWorker() {
|
|
8025
8062
|
if (_warmWorker) {
|
|
8026
|
-
try { _warmWorker.terminate(); } catch (
|
|
8063
|
+
try { _warmWorker.terminate(); } catch (err) { _hostLogger.debug('warmWorker.terminate failed', err); }
|
|
8027
8064
|
_warmWorker = null;
|
|
8028
8065
|
}
|
|
8029
8066
|
_warmWorkerBusy = false;
|
|
@@ -8078,7 +8115,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
|
|
|
8078
8115
|
|
|
8079
8116
|
function releaseWorker(terminateWorker) {
|
|
8080
8117
|
if (options.signal && abortListener) {
|
|
8081
|
-
try { options.signal.removeEventListener('abort', abortListener); } catch (
|
|
8118
|
+
try { options.signal.removeEventListener('abort', abortListener); } catch (err) { _hostLogger.debug('executeInWorker removeEventListener failed', err); }
|
|
8082
8119
|
abortListener = null;
|
|
8083
8120
|
}
|
|
8084
8121
|
_activeWorkerJobs.delete(requestId);
|
|
@@ -8093,7 +8130,7 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
|
|
|
8093
8130
|
}
|
|
8094
8131
|
}
|
|
8095
8132
|
} else {
|
|
8096
|
-
try { worker.terminate(); } catch (
|
|
8133
|
+
try { worker.terminate(); } catch (err) { _hostLogger.debug('worker.terminate failed', err); }
|
|
8097
8134
|
}
|
|
8098
8135
|
}
|
|
8099
8136
|
|