@snap/valdi 1.1.7 → 1.2.1
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/.metadata/.bazelrc.template +9 -7
- package/.metadata/AGENTS.md.template +7 -0
- package/.metadata/MODULE.bazel.template +47 -3
- package/.metadata/README.md.template +2 -2
- package/.metadata/bzl/patches/rules_python/1.9.0/BUILD.bazel.template +1 -0
- package/.metadata/bzl/patches/rules_python/1.9.0/remove_setuptools_spaces.patch.template +96 -0
- package/.metadata/skill-tests-README.md.template +1 -1
- package/README.md +47 -14
- package/bundled-skills/registry.json +2 -1
- package/bundled-skills/skills/valdi-animations/skill.md +49 -0
- package/bundled-skills/skills/valdi-async/skill.md +3 -2
- package/bundled-skills/skills/valdi-async/tests/README.md +1 -1
- package/bundled-skills/skills/valdi-bazel/skill.md +2 -6
- package/bundled-skills/skills/valdi-component-tests/tests/README.md +1 -1
- package/bundled-skills/skills/valdi-cpp-runtime/skill.md +18 -0
- package/bundled-skills/skills/valdi-custom-view/skill.md +1 -1
- package/bundled-skills/skills/valdi-error-handling/skill.md +1 -1
- package/bundled-skills/skills/valdi-gestures/skill.md +3 -3
- package/bundled-skills/skills/valdi-migrate/skill.md +2 -1
- package/bundled-skills/skills/valdi-migrate/tests/README.md +2 -2
- package/bundled-skills/skills/valdi-mock-breakdown/skill.md +4 -4
- package/bundled-skills/skills/valdi-mock-to-module/skill.md +9 -6
- package/bundled-skills/skills/valdi-overview/skill.md +2 -1
- package/bundled-skills/skills/valdi-perf/skill.md +121 -5
- package/bundled-skills/skills/valdi-perf/tests/README.md +1 -1
- package/bundled-skills/skills/valdi-pr-review/skill.md +189 -0
- package/bundled-skills/skills/valdi-profile/skill.md +5 -3
- package/bundled-skills/skills/valdi-setup/skill.md +3 -6
- package/bundled-skills/skills/valdi-testing/skill.md +1 -1
- package/bundled-skills/skills/valdi-tsx/skill.md +47 -11
- package/bundled-skills/skills/valdi-tsx/tests/README.md +1 -1
- package/debugger/README.md +356 -0
- package/debugger/debugger-actions.js +373 -0
- package/debugger/debugger-api.js +225 -0
- package/debugger/debugger-bootstrap.js +295 -0
- package/debugger/debugger-model.js +790 -0
- package/debugger/debugger-performance.js +573 -0
- package/debugger/debugger-preview-html.js +676 -0
- package/debugger/debugger-providers.js +389 -0
- package/debugger/debugger-render.js +529 -0
- package/debugger/debugger-runtime.js +387 -0
- package/debugger/debugger-session.js +188 -0
- package/debugger/debugger-settings.js +209 -0
- package/debugger/debugger-state.js +221 -0
- package/debugger/debugger-tree-model.js +539 -0
- package/debugger/debugger.css +1865 -0
- package/debugger/devtools-panel.css +1318 -0
- package/debugger/devtools-panel.html +273 -0
- package/debugger/devtools-panel.js +3329 -0
- package/debugger/index.html +279 -0
- package/dist/commands/bootstrap.js +7 -6
- package/dist/commands/build.js +7 -1
- package/dist/commands/debugger.js +163 -0
- package/dist/commands/doctor.js +3 -62
- package/dist/commands/export.js +47 -16
- package/dist/commands/hotreload.js +247 -27
- package/dist/commands/inspect.js +5 -2
- package/dist/commands/inspect_commands/input.js +176 -0
- package/dist/commands/inspect_commands/snapshot.js +1 -1
- package/dist/commands/inspect_commands/tree.js +1 -1
- package/dist/commands/install.js +79 -2
- package/dist/commands/projectsync.js +15 -0
- package/dist/commands/webHotreload.js +31 -0
- package/dist/core/constants.js +34 -7
- package/dist/debugger/chromiumConsole.js +279 -0
- package/dist/debugger/inputClient.js +473 -0
- package/dist/debugger/server.js +3801 -0
- package/dist/debugger/targetRegistry.js +436 -0
- package/dist/debugger/webPreviewPerformance.js +864 -0
- package/dist/index.js +0 -0
- package/dist/utils/BazelClient.js +34 -5
- package/dist/utils/applicationUtils.js +20 -2
- package/dist/utils/buildInfo.js +5 -1
- package/dist/utils/chromiumDevToolsClient.js +350 -0
- package/dist/utils/cliUtils.js +2 -2
- package/dist/utils/daemonClient.js +364 -44
- package/dist/utils/directorySync.js +153 -0
- package/dist/utils/githubUtils.js +1 -1
- package/dist/utils/hermesClient.js +82 -176
- package/dist/utils/loopbackHost.js +14 -0
- package/dist/utils/owlCdpClient.js +282 -0
- package/dist/utils/owlDevToolsExtension.js +142 -0
- package/dist/utils/processUtils.js +14 -0
- package/dist/utils/stringUtils.js +13 -1
- package/dist/utils/webApplicationSession.js +58 -0
- package/dist/utils/webHotReloadSession.js +212 -0
- package/dist/utils/webServerUtils.js +195 -0
- package/dist/utils/zipUtils.js +20 -2
- package/package.json +4 -2
- package/dist/commands/inspect_commands/snapshot.spec.js +0 -105
- package/dist/core/packageFiles.spec.js +0 -29
- package/dist/preview/previewGenerator.spec.js +0 -203
- package/dist/preview/viewModelParser.spec.js +0 -171
- package/dist/utils/linuxDistro.spec.js +0 -122
- package/dist/utils/skillsAdapters.spec.js +0 -141
- package/dist/utils/stringUtils.spec.js +0 -81
|
@@ -0,0 +1,3801 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ConsoleSseWriter = exports.PerformanceTraceCoordinator = exports.PerformanceTraceAction = exports.MAX_CONSOLE_SSE_BUFFERED_EVENTS = exports.MAX_CONSOLE_SSE_BUFFERED_BYTES = exports.MAX_TRACE_HTTP_RESPONSE_BYTES = exports.MAX_TRACE_EVENT_COUNT = void 0;
|
|
4
|
+
exports.resolveDebuggerUiPort = resolveDebuggerUiPort;
|
|
5
|
+
exports.resolveDebuggerServicePort = resolveDebuggerServicePort;
|
|
6
|
+
exports.projectDebuggerTreeForJson = projectDebuggerTreeForJson;
|
|
7
|
+
exports.normalizeTraceCaptureDurationMs = normalizeTraceCaptureDurationMs;
|
|
8
|
+
exports.createInterruptibleOperation = createInterruptibleOperation;
|
|
9
|
+
exports.assertPerformanceTraceContext = assertPerformanceTraceContext;
|
|
10
|
+
exports.runPerformanceTraceCapture = runPerformanceTraceCapture;
|
|
11
|
+
exports.decorateTraceResult = decorateTraceResult;
|
|
12
|
+
exports.readRecordedTraces = readRecordedTraces;
|
|
13
|
+
exports.summarizeTraces = summarizeTraces;
|
|
14
|
+
exports.isRendererViewModelChangeTrace = isRendererViewModelChangeTrace;
|
|
15
|
+
exports.buildPerfettoTracePayload = buildPerfettoTracePayload;
|
|
16
|
+
exports.summarizeCpuProfile = summarizeCpuProfile;
|
|
17
|
+
exports.startDebuggerServer = startDebuggerServer;
|
|
18
|
+
const tslib_1 = require("tslib");
|
|
19
|
+
const node_fs_1 = require("node:fs");
|
|
20
|
+
const promises_1 = tslib_1.__importDefault(require("node:fs/promises"));
|
|
21
|
+
const node_crypto_1 = require("node:crypto");
|
|
22
|
+
const node_http_1 = tslib_1.__importDefault(require("node:http"));
|
|
23
|
+
const node_net_1 = tslib_1.__importDefault(require("node:net"));
|
|
24
|
+
const node_path_1 = tslib_1.__importDefault(require("node:path"));
|
|
25
|
+
const node_util_1 = require("node:util");
|
|
26
|
+
const daemonClient_1 = require("../utils/daemonClient");
|
|
27
|
+
const fileUtils_1 = require("../utils/fileUtils");
|
|
28
|
+
const hermesClient_1 = require("../utils/hermesClient");
|
|
29
|
+
const loopbackHost_1 = require("../utils/loopbackHost");
|
|
30
|
+
const owlCdpClient_1 = require("../utils/owlCdpClient");
|
|
31
|
+
const chromiumConsole_1 = require("./chromiumConsole");
|
|
32
|
+
const inputClient_1 = require("./inputClient");
|
|
33
|
+
const targetRegistry_1 = require("./targetRegistry");
|
|
34
|
+
const webPreviewPerformance_1 = require("./webPreviewPerformance");
|
|
35
|
+
const DEFAULT_HOST = process.env['VALDI_DEBUGGER_HOST'] || '127.0.0.1';
|
|
36
|
+
const DEFAULT_UI_PORT = 8765;
|
|
37
|
+
const DEFAULT_CHROMIUM_DEBUGGING_PORT = Number.parseInt(process.env['VALDI_CHROMIUM_DEBUGGING_PORT'] || '9222', 10);
|
|
38
|
+
const HOT_RELOAD_PROXY_PORT = Number.parseInt(process.env['VALDI_HOT_RELOAD_PROXY_PORT'] || '9010', 10);
|
|
39
|
+
const PORT_SEARCH_LIMIT = 50;
|
|
40
|
+
const MAX_RUNTIME_LOG_READ_BYTES = 1024 * 1024;
|
|
41
|
+
const API_TOKEN_HEADER = 'X-Valdi-Debugger-Token';
|
|
42
|
+
const API_TOKEN_QUERY_PARAMETER = 'valdiDebuggerToken';
|
|
43
|
+
const API_TOKEN_META_NAME = 'valdi-debugger-api-token';
|
|
44
|
+
const FATAL_JSON_UTF8_DECODER = new node_util_1.TextDecoder('utf8', { fatal: true });
|
|
45
|
+
const WEB_PREVIEW_NONCE_PATTERN = /^[\w-]{16,128}$/;
|
|
46
|
+
const COMPONENT_PROPERTY_TOKEN_PATTERN = /^[\da-f]{32}$/;
|
|
47
|
+
const COMPONENT_PROPERTY_EDIT_ERROR = 'The component property edit is stale or invalid.';
|
|
48
|
+
const COMPONENT_PROPERTY_EDIT_PROTOCOL_VERSION = 1;
|
|
49
|
+
const COMPONENT_PROPERTY_EDIT_REQUEST_KEYS_BY_PROTOCOL_VERSION = new Map([
|
|
50
|
+
[
|
|
51
|
+
COMPONENT_PROPERTY_EDIT_PROTOCOL_VERSION,
|
|
52
|
+
[
|
|
53
|
+
'componentId',
|
|
54
|
+
'componentToken',
|
|
55
|
+
'inspectedUrl',
|
|
56
|
+
'propertyName',
|
|
57
|
+
'protocolVersion',
|
|
58
|
+
'sessionId',
|
|
59
|
+
'snapshotRevision',
|
|
60
|
+
'targetNonce',
|
|
61
|
+
'value',
|
|
62
|
+
],
|
|
63
|
+
],
|
|
64
|
+
]);
|
|
65
|
+
const MAX_COMPONENT_PROPERTY_NAME_CHARACTERS = 256;
|
|
66
|
+
const MAX_COMPONENT_PROPERTY_STRING_BYTES = 65_536;
|
|
67
|
+
const MAX_COMPONENT_ID_CHARACTERS = 4096;
|
|
68
|
+
const FORBIDDEN_COMPONENT_PROPERTY_NAMES = new Set(['__proto__', 'children', 'constructor', 'prototype']);
|
|
69
|
+
const MAX_DEBUGGER_TREE_NODES = 25_000;
|
|
70
|
+
const MAX_DEBUGGER_PROJECTION_VALUES = 250_000;
|
|
71
|
+
const MAX_DEBUGGER_PROJECTION_DEPTH = 64;
|
|
72
|
+
const MAX_DEBUGGER_PROJECTION_STRING_LENGTH = MAX_COMPONENT_PROPERTY_STRING_BYTES;
|
|
73
|
+
const DEFAULT_TRACE_CAPTURE_DURATION_MS = 5000;
|
|
74
|
+
const MIN_TRACE_CAPTURE_DURATION_MS = 100;
|
|
75
|
+
const MAX_TRACE_CAPTURE_DURATION_MS = 15_000;
|
|
76
|
+
exports.MAX_TRACE_EVENT_COUNT = 10_000;
|
|
77
|
+
const MAX_TRACE_NAME_BYTES = 2048;
|
|
78
|
+
const MAX_TRACE_THREAD_METADATA_COUNT = 256;
|
|
79
|
+
exports.MAX_TRACE_HTTP_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
80
|
+
const MAX_TRACE_HTTP_STRING_BYTES = 64 * 1024;
|
|
81
|
+
const TRACE_DAEMON_TIMEOUT_MS = 30_000;
|
|
82
|
+
const CHROMIUM_CONSOLE_COMMAND_TIMEOUT_MS = 8000;
|
|
83
|
+
const CHROMIUM_CONSOLE_IDENTITY_INTERVAL_MS = 15_000;
|
|
84
|
+
const CHROMIUM_CONSOLE_DEDUPLICATION_WINDOW_MS = 500;
|
|
85
|
+
const MAX_PENDING_CHROMIUM_CONSOLE_ENTRIES = 128;
|
|
86
|
+
const MAX_DISCOVERY_CLIENTS_PER_ENDPOINT = 16;
|
|
87
|
+
const MAX_DISCOVERY_CONTEXTS_PER_CLIENT = 64;
|
|
88
|
+
const MAX_DISCOVERY_DAEMON_ENDPOINTS = 10;
|
|
89
|
+
const MAX_CONCURRENT_DAEMON_DISCOVERIES = 4;
|
|
90
|
+
const DAEMON_DISCOVERY_CONFIGURE_TIMEOUT_MS = 1500;
|
|
91
|
+
const MAX_WEB_PREVIEW_URL_BYTES = 4096;
|
|
92
|
+
const MAX_WEB_PREVIEW_TARGET_NAME_BYTES = 256;
|
|
93
|
+
const MAX_DEVTOOLS_TARGETS_RESPONSE_BYTES = 512 * 1024;
|
|
94
|
+
exports.MAX_CONSOLE_SSE_BUFFERED_BYTES = 512 * 1024;
|
|
95
|
+
exports.MAX_CONSOLE_SSE_BUFFERED_EVENTS = 128;
|
|
96
|
+
const PERFETTO_PROCESS_ID = 1;
|
|
97
|
+
const PERFETTO_PROCESS_NAME = 'Valdi';
|
|
98
|
+
const PERFETTO_TRACE_CATEGORY = 'valdi';
|
|
99
|
+
const PROCESS_WIDE_CAPTURE_SCOPE = 'process-wide';
|
|
100
|
+
const TRACE_CAPTURE_TARGET_STRING_KEYS = [
|
|
101
|
+
'id',
|
|
102
|
+
'name',
|
|
103
|
+
'platform',
|
|
104
|
+
'transport',
|
|
105
|
+
'state',
|
|
106
|
+
'clientId',
|
|
107
|
+
'contextId',
|
|
108
|
+
'applicationId',
|
|
109
|
+
'sessionId',
|
|
110
|
+
];
|
|
111
|
+
const DEBUGGER_PROVIDERS_IDENTIFIER = 'ValdiDebuggerProviders';
|
|
112
|
+
const DEBUG_SETTINGS_IDENTIFIER = 'ValdiDebuggerSettings';
|
|
113
|
+
const NOOP = () => { };
|
|
114
|
+
const MIME_TYPES = {
|
|
115
|
+
'.html': 'text/html; charset=utf-8',
|
|
116
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
117
|
+
'.css': 'text/css; charset=utf-8',
|
|
118
|
+
'.json': 'application/json; charset=utf-8',
|
|
119
|
+
'.png': 'image/png',
|
|
120
|
+
'.svg': 'image/svg+xml',
|
|
121
|
+
};
|
|
122
|
+
var PerformanceTraceAction;
|
|
123
|
+
(function (PerformanceTraceAction) {
|
|
124
|
+
PerformanceTraceAction[PerformanceTraceAction["Status"] = 0] = "Status";
|
|
125
|
+
PerformanceTraceAction[PerformanceTraceAction["Start"] = 1] = "Start";
|
|
126
|
+
PerformanceTraceAction[PerformanceTraceAction["Stop"] = 2] = "Stop";
|
|
127
|
+
})(PerformanceTraceAction || (exports.PerformanceTraceAction = PerformanceTraceAction = {}));
|
|
128
|
+
class ApiRequestError extends Error {
|
|
129
|
+
statusCode;
|
|
130
|
+
constructor(statusCode, message) {
|
|
131
|
+
super(message);
|
|
132
|
+
this.statusCode = statusCode;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const devEventClients = new Set();
|
|
136
|
+
const debuggerEventClients = new Set();
|
|
137
|
+
const eventStreamClosers = new Set();
|
|
138
|
+
const assetWatchers = new Set();
|
|
139
|
+
const debuggerActions = [
|
|
140
|
+
'attach',
|
|
141
|
+
'detach',
|
|
142
|
+
'refreshTargets',
|
|
143
|
+
'refreshSnapshot',
|
|
144
|
+
'selectTarget',
|
|
145
|
+
'selectNode',
|
|
146
|
+
'setActiveSection',
|
|
147
|
+
'setActiveTab',
|
|
148
|
+
'setOverlayMode',
|
|
149
|
+
'setAutoRefresh',
|
|
150
|
+
'setPort',
|
|
151
|
+
'clearLogs',
|
|
152
|
+
'captureElementSnapshot',
|
|
153
|
+
'dumpHeap',
|
|
154
|
+
'startRendererTrace',
|
|
155
|
+
'stopRendererTrace',
|
|
156
|
+
'captureRendererTrace',
|
|
157
|
+
'refreshHermesContexts',
|
|
158
|
+
'startCpuProfile',
|
|
159
|
+
'stopCpuProfile',
|
|
160
|
+
'captureCpuProfile',
|
|
161
|
+
'refreshDebuggerProviders',
|
|
162
|
+
'refreshDebugSettings',
|
|
163
|
+
'setDebugSetting',
|
|
164
|
+
'resetDebugSetting',
|
|
165
|
+
];
|
|
166
|
+
const DEFAULT_DEBUGGER_TARGET_DISCOVERY = {
|
|
167
|
+
defaultDaemonEndpoints: [
|
|
168
|
+
{ autoForward: false, port: daemonClient_1.STANDALONE_PORT },
|
|
169
|
+
{ autoForward: false, port: daemonClient_1.MOBILE_PORT },
|
|
170
|
+
],
|
|
171
|
+
discoverAndroidDaemonEndpoints: targetRegistry_1.discoverAndroidDaemonEndpoints,
|
|
172
|
+
discoverDebuggerProxyTargets: targetRegistry_1.discoverDebuggerProxyTargets,
|
|
173
|
+
probeDebuggerProxy: async (port) => await probeTcpPort(port, 750),
|
|
174
|
+
};
|
|
175
|
+
let devRevision = 0;
|
|
176
|
+
let debuggerEventRevision = 0;
|
|
177
|
+
let devReloadTimer = null;
|
|
178
|
+
let activeHost = DEFAULT_HOST;
|
|
179
|
+
let assetRoot = getDefaultAssetRoot();
|
|
180
|
+
let activeLogsDirectory = null;
|
|
181
|
+
let activeServicePort;
|
|
182
|
+
let activeWebPreviewTarget = null;
|
|
183
|
+
let activeDebuggerTargetDiscovery = DEFAULT_DEBUGGER_TARGET_DISCOVERY;
|
|
184
|
+
let activeProfileSession = null;
|
|
185
|
+
let activeProfileCapture = null;
|
|
186
|
+
let profileTransitionInProgress = false;
|
|
187
|
+
let debuggerServerLifecycleActive = false;
|
|
188
|
+
let debuggerServerClosing = false;
|
|
189
|
+
let debuggerUiState = createDebuggerUiState(daemonClient_1.STANDALONE_PORT);
|
|
190
|
+
class PerformanceTraceCoordinator {
|
|
191
|
+
states = new Map();
|
|
192
|
+
async runTransition(targetKey, transition) {
|
|
193
|
+
const state = this.stateForTarget(targetKey);
|
|
194
|
+
if (state.transitionInProgress) {
|
|
195
|
+
throw new Error('Another renderer trace transition is already in progress for this runtime.');
|
|
196
|
+
}
|
|
197
|
+
state.transitionInProgress = true;
|
|
198
|
+
try {
|
|
199
|
+
return await transition();
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
state.transitionInProgress = false;
|
|
203
|
+
this.deleteStateIfIdle(targetKey, state);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
async capture(targetKey, options, dependencies) {
|
|
207
|
+
const state = this.stateForTarget(targetKey);
|
|
208
|
+
if (state.activeCapture) {
|
|
209
|
+
throw new Error('A one-shot renderer trace capture is already in progress for this runtime.');
|
|
210
|
+
}
|
|
211
|
+
let canceled = false;
|
|
212
|
+
let resolveCancellation;
|
|
213
|
+
const cancellation = new Promise(resolve => {
|
|
214
|
+
resolveCancellation = resolve;
|
|
215
|
+
});
|
|
216
|
+
const cancel = () => {
|
|
217
|
+
if (canceled)
|
|
218
|
+
return;
|
|
219
|
+
canceled = true;
|
|
220
|
+
resolveCancellation();
|
|
221
|
+
};
|
|
222
|
+
const operation = runPerformanceTraceCapture(options, {
|
|
223
|
+
send: async (action, data) => await this.runTransition(targetKey, async () => await dependencies.send(action, data)),
|
|
224
|
+
wait: async (durationMs) => {
|
|
225
|
+
await Promise.race([dependencies.wait(durationMs), cancellation]);
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
const result = operation.finally(() => {
|
|
229
|
+
delete state.activeCapture;
|
|
230
|
+
this.deleteStateIfIdle(targetKey, state);
|
|
231
|
+
});
|
|
232
|
+
state.activeCapture = { cancel, result };
|
|
233
|
+
return await result;
|
|
234
|
+
}
|
|
235
|
+
async stop(targetKey, transition) {
|
|
236
|
+
const activeCapture = this.states.get(targetKey)?.activeCapture;
|
|
237
|
+
if (activeCapture) {
|
|
238
|
+
activeCapture.cancel();
|
|
239
|
+
return await activeCapture.result;
|
|
240
|
+
}
|
|
241
|
+
return await this.runTransition(targetKey, transition);
|
|
242
|
+
}
|
|
243
|
+
stateForTarget(targetKey) {
|
|
244
|
+
const existing = this.states.get(targetKey);
|
|
245
|
+
if (existing)
|
|
246
|
+
return existing;
|
|
247
|
+
const state = { transitionInProgress: false };
|
|
248
|
+
this.states.set(targetKey, state);
|
|
249
|
+
return state;
|
|
250
|
+
}
|
|
251
|
+
deleteStateIfIdle(targetKey, state) {
|
|
252
|
+
if (!state.transitionInProgress && !state.activeCapture && this.states.get(targetKey) === state) {
|
|
253
|
+
this.states.delete(targetKey);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
exports.PerformanceTraceCoordinator = PerformanceTraceCoordinator;
|
|
258
|
+
const performanceTraceCoordinator = new PerformanceTraceCoordinator();
|
|
259
|
+
const webPreviewPerformanceController = (0, webPreviewPerformance_1.createWebPreviewPerformanceController)();
|
|
260
|
+
function getDefaultAssetRoot() {
|
|
261
|
+
return node_path_1.default.resolve(__dirname, '..', '..', 'debugger');
|
|
262
|
+
}
|
|
263
|
+
function readEnvironmentPort(name) {
|
|
264
|
+
const value = process.env[name];
|
|
265
|
+
if (value === undefined || value === '')
|
|
266
|
+
return undefined;
|
|
267
|
+
if (!/^\d+$/.test(value)) {
|
|
268
|
+
throw new Error(`${name} must be an integer between 1 and 65535.`);
|
|
269
|
+
}
|
|
270
|
+
const port = Number(value);
|
|
271
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) {
|
|
272
|
+
throw new Error(`${name} must be an integer between 1 and 65535.`);
|
|
273
|
+
}
|
|
274
|
+
return port;
|
|
275
|
+
}
|
|
276
|
+
function resolveDebuggerUiPort() {
|
|
277
|
+
return readEnvironmentPort('VALDI_DEBUGGER_UI_PORT') ?? DEFAULT_UI_PORT;
|
|
278
|
+
}
|
|
279
|
+
function resolveDebuggerServicePort() {
|
|
280
|
+
return readEnvironmentPort('VALDI_DEBUGGER_SERVICE_PORT');
|
|
281
|
+
}
|
|
282
|
+
function defaultServicePort() {
|
|
283
|
+
return activeServicePort ?? daemonClient_1.STANDALONE_PORT;
|
|
284
|
+
}
|
|
285
|
+
function discoveryServicePorts() {
|
|
286
|
+
return activeServicePort === undefined ? [daemonClient_1.STANDALONE_PORT, daemonClient_1.MOBILE_PORT] : [activeServicePort];
|
|
287
|
+
}
|
|
288
|
+
function hostForUrl(host) {
|
|
289
|
+
return node_net_1.default.isIP((0, loopbackHost_1.normalizedHostname)(host)) === 6 ? `[${(0, loopbackHost_1.normalizedHostname)(host)}]` : host;
|
|
290
|
+
}
|
|
291
|
+
function parseHttpUrl(value) {
|
|
292
|
+
try {
|
|
293
|
+
return new URL(value);
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function hasExpectedLoopbackAuthority(url, port) {
|
|
300
|
+
const effectivePort = url.port || (url.protocol === 'http:' ? '80' : '443');
|
|
301
|
+
return (url.protocol === 'http:' &&
|
|
302
|
+
(0, loopbackHost_1.isLoopbackHost)(url.hostname) &&
|
|
303
|
+
effectivePort === String(port) &&
|
|
304
|
+
!url.username &&
|
|
305
|
+
!url.password);
|
|
306
|
+
}
|
|
307
|
+
function isAllowedRequestHost(hostHeader, port) {
|
|
308
|
+
if (!hostHeader)
|
|
309
|
+
return false;
|
|
310
|
+
const parsed = parseHttpUrl(`http://${hostHeader}`);
|
|
311
|
+
return parsed !== null && hasExpectedLoopbackAuthority(parsed, port);
|
|
312
|
+
}
|
|
313
|
+
function isAllowedRequestOrigin(originHeader, hostHeader, port) {
|
|
314
|
+
if (originHeader === undefined)
|
|
315
|
+
return true;
|
|
316
|
+
const parsed = parseHttpUrl(originHeader);
|
|
317
|
+
const requestAuthority = hostHeader ? parseHttpUrl(`http://${hostHeader}`) : null;
|
|
318
|
+
return (parsed !== null &&
|
|
319
|
+
requestAuthority !== null &&
|
|
320
|
+
hasExpectedLoopbackAuthority(parsed, port) &&
|
|
321
|
+
hasExpectedLoopbackAuthority(requestAuthority, port) &&
|
|
322
|
+
(0, loopbackHost_1.normalizedHostname)(parsed.hostname) === (0, loopbackHost_1.normalizedHostname)(requestAuthority.hostname) &&
|
|
323
|
+
parsed.pathname === '/' &&
|
|
324
|
+
!parsed.search &&
|
|
325
|
+
!parsed.hash);
|
|
326
|
+
}
|
|
327
|
+
function isAllowedApiFetchSite(fetchSiteHeader) {
|
|
328
|
+
return fetchSiteHeader === undefined || fetchSiteHeader === 'same-origin' || fetchSiteHeader === 'none';
|
|
329
|
+
}
|
|
330
|
+
function isEventStreamPath(pathname) {
|
|
331
|
+
return (pathname === '/api/dev-events' ||
|
|
332
|
+
pathname === '/api/debugger/events' ||
|
|
333
|
+
pathname === '/api/devtools/console/stream' ||
|
|
334
|
+
pathname === '/api/runtime-logs/stream');
|
|
335
|
+
}
|
|
336
|
+
function tokenMatches(expectedToken, suppliedToken) {
|
|
337
|
+
if (suppliedToken === undefined)
|
|
338
|
+
return false;
|
|
339
|
+
const expected = Buffer.from(expectedToken);
|
|
340
|
+
const supplied = Buffer.from(suppliedToken);
|
|
341
|
+
return expected.length === supplied.length && (0, node_crypto_1.timingSafeEqual)(expected, supplied);
|
|
342
|
+
}
|
|
343
|
+
function hasValidApiToken(request, url, apiToken) {
|
|
344
|
+
const header = request.headers[API_TOKEN_HEADER.toLowerCase()];
|
|
345
|
+
const suppliedHeader = Array.isArray(header) ? undefined : header;
|
|
346
|
+
if (tokenMatches(apiToken, suppliedHeader))
|
|
347
|
+
return true;
|
|
348
|
+
if (!isEventStreamPath(url.pathname))
|
|
349
|
+
return false;
|
|
350
|
+
return tokenMatches(apiToken, url.searchParams.get(API_TOKEN_QUERY_PARAMETER) ?? undefined);
|
|
351
|
+
}
|
|
352
|
+
function probeTcpPort(port, timeoutMs) {
|
|
353
|
+
return new Promise(resolve => {
|
|
354
|
+
const socket = connectToTcpPort(port);
|
|
355
|
+
let settled = false;
|
|
356
|
+
const done = (connected) => {
|
|
357
|
+
if (settled)
|
|
358
|
+
return;
|
|
359
|
+
settled = true;
|
|
360
|
+
socket.destroy();
|
|
361
|
+
resolve(connected);
|
|
362
|
+
};
|
|
363
|
+
socket.setTimeout(timeoutMs, () => done(false));
|
|
364
|
+
socket.once('connect', () => done(true));
|
|
365
|
+
socket.once('error', () => done(false));
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
function connectToTcpPort(port) {
|
|
369
|
+
return node_net_1.default.connect({ host: activeHost, port });
|
|
370
|
+
}
|
|
371
|
+
function portName(port) {
|
|
372
|
+
if (port === daemonClient_1.STANDALONE_PORT)
|
|
373
|
+
return 'standalone';
|
|
374
|
+
if (port === daemonClient_1.MOBILE_PORT)
|
|
375
|
+
return 'mobile';
|
|
376
|
+
return 'custom';
|
|
377
|
+
}
|
|
378
|
+
function truncateStringForJson(value, maximumBytes) {
|
|
379
|
+
if (Buffer.byteLength(JSON.stringify(value), 'utf8') <= maximumBytes)
|
|
380
|
+
return value;
|
|
381
|
+
const suffix = '…';
|
|
382
|
+
let minimumLength = 0;
|
|
383
|
+
let maximumLength = value.length;
|
|
384
|
+
let truncated = suffix;
|
|
385
|
+
while (minimumLength <= maximumLength) {
|
|
386
|
+
const candidateLength = Math.floor((minimumLength + maximumLength) / 2);
|
|
387
|
+
const candidate = `${value.slice(0, candidateLength)}${suffix}`;
|
|
388
|
+
if (Buffer.byteLength(JSON.stringify(candidate), 'utf8') <= maximumBytes) {
|
|
389
|
+
truncated = candidate;
|
|
390
|
+
minimumLength = candidateLength + 1;
|
|
391
|
+
}
|
|
392
|
+
else {
|
|
393
|
+
maximumLength = candidateLength - 1;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return truncated;
|
|
397
|
+
}
|
|
398
|
+
function errorPayload(error) {
|
|
399
|
+
return {
|
|
400
|
+
error: truncateStringForJson(error instanceof Error ? error.message : String(error), MAX_TRACE_HTTP_STRING_BYTES),
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
function isFileSystemError(error) {
|
|
404
|
+
if (!(error instanceof Error))
|
|
405
|
+
return false;
|
|
406
|
+
const fileSystemError = error;
|
|
407
|
+
return (typeof fileSystemError.code === 'string' &&
|
|
408
|
+
typeof fileSystemError.path === 'string' &&
|
|
409
|
+
typeof fileSystemError.syscall === 'string');
|
|
410
|
+
}
|
|
411
|
+
function clientErrorPayload(error) {
|
|
412
|
+
if (!isFileSystemError(error))
|
|
413
|
+
return errorPayload(error);
|
|
414
|
+
console.warn(`Debugger filesystem error: ${errorPayload(error).error}`);
|
|
415
|
+
return { error: 'A local filesystem operation failed. See the debugger server output for details.' };
|
|
416
|
+
}
|
|
417
|
+
function isValidSnapshotBase64(value) {
|
|
418
|
+
if (!value || value.length % 4 === 1)
|
|
419
|
+
return false;
|
|
420
|
+
const firstPaddingIndex = value.indexOf('=');
|
|
421
|
+
const dataLength = firstPaddingIndex === -1 ? value.length : firstPaddingIndex;
|
|
422
|
+
const paddingLength = value.length - dataLength;
|
|
423
|
+
if (paddingLength > 2 || (paddingLength > 0 && value.length % 4 !== 0))
|
|
424
|
+
return false;
|
|
425
|
+
for (let index = 0; index < dataLength; index += 1) {
|
|
426
|
+
const code = value.codePointAt(index) ?? 0;
|
|
427
|
+
const valid = (code >= 65 && code <= 90) ||
|
|
428
|
+
(code >= 97 && code <= 122) ||
|
|
429
|
+
(code >= 48 && code <= 57) ||
|
|
430
|
+
code === 43 ||
|
|
431
|
+
code === 47;
|
|
432
|
+
if (!valid)
|
|
433
|
+
return false;
|
|
434
|
+
}
|
|
435
|
+
for (let index = dataLength; index < value.length; index += 1) {
|
|
436
|
+
if (value[index] !== '=')
|
|
437
|
+
return false;
|
|
438
|
+
}
|
|
439
|
+
return true;
|
|
440
|
+
}
|
|
441
|
+
function createDebuggerJsonRecord() {
|
|
442
|
+
return Object.create(null);
|
|
443
|
+
}
|
|
444
|
+
function setDebuggerJsonProperty(target, key, value) {
|
|
445
|
+
Object.defineProperty(target, key, {
|
|
446
|
+
configurable: true,
|
|
447
|
+
enumerable: true,
|
|
448
|
+
value,
|
|
449
|
+
writable: true,
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
function debuggerProjectionTruncation(reason, path) {
|
|
453
|
+
const marker = createDebuggerJsonRecord();
|
|
454
|
+
setDebuggerJsonProperty(marker, '$at', path);
|
|
455
|
+
setDebuggerJsonProperty(marker, '$truncated', reason);
|
|
456
|
+
return marker;
|
|
457
|
+
}
|
|
458
|
+
function markDebuggerProjectionTruncated(target, reason, path) {
|
|
459
|
+
const marker = debuggerProjectionTruncation(reason, path);
|
|
460
|
+
if (Array.isArray(target)) {
|
|
461
|
+
target.push(marker);
|
|
462
|
+
}
|
|
463
|
+
else if (target['$type'] === 'array' && Array.isArray(target['$entries'])) {
|
|
464
|
+
target['$entries'].push(marker);
|
|
465
|
+
}
|
|
466
|
+
else {
|
|
467
|
+
setDebuggerJsonProperty(target, '$at', marker['$at']);
|
|
468
|
+
setDebuggerJsonProperty(target, '$truncated', marker['$truncated']);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
function isDebuggerArrayIndex(key) {
|
|
472
|
+
const index = Number(key);
|
|
473
|
+
return Number.isInteger(index) && index >= 0 && index < 4_294_967_295 && String(index) === key;
|
|
474
|
+
}
|
|
475
|
+
function debuggerPrimitiveProjection(value, state) {
|
|
476
|
+
if (typeof value === 'string') {
|
|
477
|
+
if (value.length <= MAX_DEBUGGER_PROJECTION_STRING_LENGTH)
|
|
478
|
+
return value;
|
|
479
|
+
state.complete = false;
|
|
480
|
+
const suffix = '…[truncated]';
|
|
481
|
+
return `${value.slice(0, MAX_DEBUGGER_PROJECTION_STRING_LENGTH - suffix.length)}${suffix}`;
|
|
482
|
+
}
|
|
483
|
+
if (value === null || typeof value === 'boolean')
|
|
484
|
+
return value;
|
|
485
|
+
if (typeof value === 'number')
|
|
486
|
+
return Number.isFinite(value) ? value : String(value);
|
|
487
|
+
if (typeof value === 'bigint')
|
|
488
|
+
return `${value}n`;
|
|
489
|
+
if (value === undefined)
|
|
490
|
+
return '[undefined]';
|
|
491
|
+
if (typeof value === 'function')
|
|
492
|
+
return `[Function ${value.name || 'anonymous'}]`;
|
|
493
|
+
if (typeof value === 'symbol')
|
|
494
|
+
return String(value);
|
|
495
|
+
return undefined;
|
|
496
|
+
}
|
|
497
|
+
function debuggerOwnEntries(source, path, state) {
|
|
498
|
+
let descriptors;
|
|
499
|
+
try {
|
|
500
|
+
descriptors = Object.getOwnPropertyDescriptors(source);
|
|
501
|
+
}
|
|
502
|
+
catch {
|
|
503
|
+
state.complete = false;
|
|
504
|
+
return { entries: [], inspectionError: debuggerProjectionTruncation('unavailable-properties', path) };
|
|
505
|
+
}
|
|
506
|
+
const entries = [];
|
|
507
|
+
for (const key of Object.keys(descriptors)) {
|
|
508
|
+
const descriptor = descriptors[key];
|
|
509
|
+
if (!descriptor?.enumerable)
|
|
510
|
+
continue;
|
|
511
|
+
if (entries.length >= MAX_DEBUGGER_PROJECTION_VALUES) {
|
|
512
|
+
state.complete = false;
|
|
513
|
+
break;
|
|
514
|
+
}
|
|
515
|
+
const childPath = isDebuggerArrayIndex(key) ? `${path}[${key}]` : `${path}.${key}`;
|
|
516
|
+
if (!Object.prototype.hasOwnProperty.call(descriptor, 'value')) {
|
|
517
|
+
state.complete = false;
|
|
518
|
+
entries.push({
|
|
519
|
+
accessor: true,
|
|
520
|
+
childPath,
|
|
521
|
+
key,
|
|
522
|
+
value: debuggerProjectionTruncation('accessor', childPath),
|
|
523
|
+
});
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
entries.push({ accessor: false, childPath, key, value: descriptor.value });
|
|
527
|
+
}
|
|
528
|
+
return { descriptors, entries, inspectionError: null };
|
|
529
|
+
}
|
|
530
|
+
function debuggerProjectionFrame(source, targetPath, state) {
|
|
531
|
+
const inspection = debuggerOwnEntries(source, targetPath, state);
|
|
532
|
+
if (inspection.inspectionError) {
|
|
533
|
+
return { entries: [], sparse: false, target: inspection.inspectionError };
|
|
534
|
+
}
|
|
535
|
+
if (!Array.isArray(source)) {
|
|
536
|
+
return { entries: inspection.entries, sparse: false, target: createDebuggerJsonRecord() };
|
|
537
|
+
}
|
|
538
|
+
const lengthDescriptor = inspection.descriptors?.['length'];
|
|
539
|
+
const length = lengthDescriptor && Object.prototype.hasOwnProperty.call(lengthDescriptor, 'value')
|
|
540
|
+
? Number(lengthDescriptor.value)
|
|
541
|
+
: 0;
|
|
542
|
+
let expectedIndex = 0;
|
|
543
|
+
let dense = Number.isSafeInteger(length) && length >= 0;
|
|
544
|
+
for (const key of Object.keys(inspection.descriptors ?? {})) {
|
|
545
|
+
const descriptor = inspection.descriptors?.[key];
|
|
546
|
+
if (!descriptor?.enumerable)
|
|
547
|
+
continue;
|
|
548
|
+
if (!Object.prototype.hasOwnProperty.call(descriptor, 'value') ||
|
|
549
|
+
!isDebuggerArrayIndex(key) ||
|
|
550
|
+
Number(key) !== expectedIndex) {
|
|
551
|
+
dense = false;
|
|
552
|
+
break;
|
|
553
|
+
}
|
|
554
|
+
expectedIndex += 1;
|
|
555
|
+
}
|
|
556
|
+
if (expectedIndex !== length)
|
|
557
|
+
dense = false;
|
|
558
|
+
if (dense)
|
|
559
|
+
return { entries: inspection.entries, sparse: false, target: [] };
|
|
560
|
+
state.complete = false;
|
|
561
|
+
const target = createDebuggerJsonRecord();
|
|
562
|
+
setDebuggerJsonProperty(target, '$at', targetPath);
|
|
563
|
+
setDebuggerJsonProperty(target, '$entries', []);
|
|
564
|
+
setDebuggerJsonProperty(target, '$length', Number.isSafeInteger(length) && length >= 0 ? length : '[unavailable]');
|
|
565
|
+
setDebuggerJsonProperty(target, '$truncated', 'sparse-array');
|
|
566
|
+
setDebuggerJsonProperty(target, '$type', 'array');
|
|
567
|
+
return {
|
|
568
|
+
entries: inspection.entries,
|
|
569
|
+
sparse: true,
|
|
570
|
+
target,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
function setDebuggerProjectionEntry(frame, entry, value) {
|
|
574
|
+
if (frame.sparse && !Array.isArray(frame.target)) {
|
|
575
|
+
const entries = frame.target['$entries'];
|
|
576
|
+
if (Array.isArray(entries)) {
|
|
577
|
+
const projectedEntry = createDebuggerJsonRecord();
|
|
578
|
+
setDebuggerJsonProperty(projectedEntry, isDebuggerArrayIndex(entry.key) ? '$index' : '$key', isDebuggerArrayIndex(entry.key) ? Number(entry.key) : entry.key);
|
|
579
|
+
setDebuggerJsonProperty(projectedEntry, 'value', value);
|
|
580
|
+
entries.push(projectedEntry);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
else if (Array.isArray(frame.target)) {
|
|
584
|
+
const index = Number(entry.key);
|
|
585
|
+
if (Number.isInteger(index) && index >= 0)
|
|
586
|
+
frame.target[index] = value;
|
|
587
|
+
}
|
|
588
|
+
else {
|
|
589
|
+
setDebuggerJsonProperty(frame.target, entry.key, value);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
function projectDebuggerValue(value, state, path) {
|
|
593
|
+
if (value === null || typeof value !== 'object') {
|
|
594
|
+
if (state.valueCount >= MAX_DEBUGGER_PROJECTION_VALUES) {
|
|
595
|
+
state.complete = false;
|
|
596
|
+
return debuggerProjectionTruncation('value-limit', path);
|
|
597
|
+
}
|
|
598
|
+
state.valueCount += 1;
|
|
599
|
+
return debuggerPrimitiveProjection(value, state);
|
|
600
|
+
}
|
|
601
|
+
const knownPath = state.seen.get(value);
|
|
602
|
+
if (knownPath !== undefined) {
|
|
603
|
+
if (state.valueCount >= MAX_DEBUGGER_PROJECTION_VALUES) {
|
|
604
|
+
state.complete = false;
|
|
605
|
+
return debuggerProjectionTruncation('value-limit', path);
|
|
606
|
+
}
|
|
607
|
+
state.valueCount += 1;
|
|
608
|
+
const reference = createDebuggerJsonRecord();
|
|
609
|
+
setDebuggerJsonProperty(reference, '$ref', knownPath);
|
|
610
|
+
return reference;
|
|
611
|
+
}
|
|
612
|
+
if (state.valueCount >= MAX_DEBUGGER_PROJECTION_VALUES) {
|
|
613
|
+
state.complete = false;
|
|
614
|
+
return debuggerProjectionTruncation('value-limit', path);
|
|
615
|
+
}
|
|
616
|
+
const rootFrame = debuggerProjectionFrame(value, path, state);
|
|
617
|
+
const root = rootFrame.target;
|
|
618
|
+
state.seen.set(value, path);
|
|
619
|
+
state.valueCount += 1;
|
|
620
|
+
const stack = [{ ...rootFrame, depth: 0, index: 0, path }];
|
|
621
|
+
while (stack.length > 0) {
|
|
622
|
+
const frame = stack.at(-1);
|
|
623
|
+
if (!frame)
|
|
624
|
+
break;
|
|
625
|
+
if (frame.index >= frame.entries.length) {
|
|
626
|
+
stack.pop();
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
if (state.valueCount >= MAX_DEBUGGER_PROJECTION_VALUES) {
|
|
630
|
+
state.complete = false;
|
|
631
|
+
markDebuggerProjectionTruncated(frame.target, 'value-limit', frame.path);
|
|
632
|
+
stack.pop();
|
|
633
|
+
continue;
|
|
634
|
+
}
|
|
635
|
+
const entry = frame.entries[frame.index];
|
|
636
|
+
if (!entry) {
|
|
637
|
+
stack.pop();
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
frame.index += 1;
|
|
641
|
+
const childValue = entry.value;
|
|
642
|
+
if (entry.accessor || childValue === null || typeof childValue !== 'object') {
|
|
643
|
+
setDebuggerProjectionEntry(frame, entry, entry.accessor ? childValue : debuggerPrimitiveProjection(childValue, state));
|
|
644
|
+
state.valueCount += 1;
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
const childKnownPath = state.seen.get(childValue);
|
|
648
|
+
if (childKnownPath !== undefined) {
|
|
649
|
+
const reference = createDebuggerJsonRecord();
|
|
650
|
+
setDebuggerJsonProperty(reference, '$ref', childKnownPath);
|
|
651
|
+
setDebuggerProjectionEntry(frame, entry, reference);
|
|
652
|
+
state.valueCount += 1;
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
if (frame.depth + 1 >= MAX_DEBUGGER_PROJECTION_DEPTH) {
|
|
656
|
+
state.complete = false;
|
|
657
|
+
setDebuggerProjectionEntry(frame, entry, debuggerProjectionTruncation('depth-limit', entry.childPath));
|
|
658
|
+
state.valueCount += 1;
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
const childFrame = debuggerProjectionFrame(childValue, entry.childPath, state);
|
|
662
|
+
setDebuggerProjectionEntry(frame, entry, childFrame.target);
|
|
663
|
+
state.seen.set(childValue, entry.childPath);
|
|
664
|
+
state.valueCount += 1;
|
|
665
|
+
stack.push({ ...childFrame, depth: frame.depth + 1, index: 0, path: entry.childPath });
|
|
666
|
+
}
|
|
667
|
+
return root;
|
|
668
|
+
}
|
|
669
|
+
function debuggerTreeRecord(value) {
|
|
670
|
+
if (typeof value !== 'object' || value === null)
|
|
671
|
+
return { record: null, unavailable: false };
|
|
672
|
+
try {
|
|
673
|
+
return Array.isArray(value)
|
|
674
|
+
? { record: null, unavailable: false }
|
|
675
|
+
: { record: value, unavailable: false };
|
|
676
|
+
}
|
|
677
|
+
catch {
|
|
678
|
+
return { record: null, unavailable: true };
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
function debuggerTreeChildren(node, path) {
|
|
682
|
+
let childrenDescriptor;
|
|
683
|
+
try {
|
|
684
|
+
childrenDescriptor = Object.getOwnPropertyDescriptor(node, 'children');
|
|
685
|
+
}
|
|
686
|
+
catch {
|
|
687
|
+
return {
|
|
688
|
+
complete: false,
|
|
689
|
+
entries: [],
|
|
690
|
+
truncations: [debuggerProjectionTruncation('unavailable-children', path)],
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
if (!childrenDescriptor)
|
|
694
|
+
return { complete: true, entries: [], truncations: [] };
|
|
695
|
+
if (!Object.prototype.hasOwnProperty.call(childrenDescriptor, 'value')) {
|
|
696
|
+
return {
|
|
697
|
+
complete: false,
|
|
698
|
+
entries: [],
|
|
699
|
+
truncations: [debuggerProjectionTruncation('accessor', path)],
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
const children = childrenDescriptor.value;
|
|
703
|
+
try {
|
|
704
|
+
if (!Array.isArray(children))
|
|
705
|
+
return { complete: true, entries: [], truncations: [] };
|
|
706
|
+
}
|
|
707
|
+
catch {
|
|
708
|
+
return {
|
|
709
|
+
complete: false,
|
|
710
|
+
entries: [],
|
|
711
|
+
truncations: [debuggerProjectionTruncation('unavailable-children', path)],
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
let descriptors;
|
|
715
|
+
try {
|
|
716
|
+
descriptors = Object.getOwnPropertyDescriptors(children);
|
|
717
|
+
}
|
|
718
|
+
catch {
|
|
719
|
+
return {
|
|
720
|
+
complete: false,
|
|
721
|
+
entries: [],
|
|
722
|
+
truncations: [debuggerProjectionTruncation('unavailable-children', path)],
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
const lengthDescriptor = descriptors['length'];
|
|
726
|
+
const length = lengthDescriptor && Object.prototype.hasOwnProperty.call(lengthDescriptor, 'value')
|
|
727
|
+
? Number(lengthDescriptor.value)
|
|
728
|
+
: 0;
|
|
729
|
+
const entries = [];
|
|
730
|
+
const truncations = [];
|
|
731
|
+
let complete = true;
|
|
732
|
+
let numericProperties = 0;
|
|
733
|
+
for (const key of Object.keys(descriptors)) {
|
|
734
|
+
if (!isDebuggerArrayIndex(key))
|
|
735
|
+
continue;
|
|
736
|
+
numericProperties += 1;
|
|
737
|
+
const descriptor = descriptors[key];
|
|
738
|
+
if (!descriptor?.enumerable || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) {
|
|
739
|
+
complete = false;
|
|
740
|
+
truncations.push(debuggerProjectionTruncation('unavailable-child', `${path}[${key}]`));
|
|
741
|
+
continue;
|
|
742
|
+
}
|
|
743
|
+
if (entries.length >= MAX_DEBUGGER_TREE_NODES) {
|
|
744
|
+
complete = false;
|
|
745
|
+
truncations.push(debuggerProjectionTruncation('tree-node-limit', path));
|
|
746
|
+
break;
|
|
747
|
+
}
|
|
748
|
+
const child = debuggerTreeRecord(descriptor.value);
|
|
749
|
+
if (child.record) {
|
|
750
|
+
entries.push({ index: Number(key), node: child.record });
|
|
751
|
+
}
|
|
752
|
+
else if (child.unavailable) {
|
|
753
|
+
complete = false;
|
|
754
|
+
truncations.push(debuggerProjectionTruncation('unavailable-child', `${path}[${key}]`));
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
if (!Number.isSafeInteger(length) || length < 0 || numericProperties !== length) {
|
|
758
|
+
complete = false;
|
|
759
|
+
truncations.push(debuggerProjectionTruncation('sparse-children', path));
|
|
760
|
+
}
|
|
761
|
+
return { complete, entries, truncations };
|
|
762
|
+
}
|
|
763
|
+
function projectDebuggerTreeForJson(rootValue) {
|
|
764
|
+
const root = debuggerTreeRecord(rootValue).record;
|
|
765
|
+
if (!root)
|
|
766
|
+
throw new Error('The debugger snapshot tree must be a non-null object.');
|
|
767
|
+
const nodes = [];
|
|
768
|
+
const truncations = [];
|
|
769
|
+
const visited = new Set();
|
|
770
|
+
const projectionState = { complete: true, seen: new Map(), valueCount: 0 };
|
|
771
|
+
const stack = [
|
|
772
|
+
{
|
|
773
|
+
childEntries: null,
|
|
774
|
+
childIndex: 0,
|
|
775
|
+
depth: 0,
|
|
776
|
+
entered: false,
|
|
777
|
+
index: null,
|
|
778
|
+
node: root,
|
|
779
|
+
parentIndex: null,
|
|
780
|
+
sourceChildIndex: null,
|
|
781
|
+
},
|
|
782
|
+
];
|
|
783
|
+
while (stack.length > 0) {
|
|
784
|
+
const frame = stack.at(-1);
|
|
785
|
+
if (!frame)
|
|
786
|
+
break;
|
|
787
|
+
if (!frame.entered) {
|
|
788
|
+
if (visited.has(frame.node)) {
|
|
789
|
+
stack.pop();
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
if (nodes.length >= MAX_DEBUGGER_TREE_NODES) {
|
|
793
|
+
projectionState.complete = false;
|
|
794
|
+
truncations.push(debuggerProjectionTruncation('tree-node-limit', '$.nodes'));
|
|
795
|
+
break;
|
|
796
|
+
}
|
|
797
|
+
visited.add(frame.node);
|
|
798
|
+
frame.entered = true;
|
|
799
|
+
frame.index = nodes.length;
|
|
800
|
+
const data = createDebuggerJsonRecord();
|
|
801
|
+
projectionState.seen.set(frame.node, `$.nodes[${frame.index}].data`);
|
|
802
|
+
const inspection = debuggerOwnEntries(frame.node, `$.nodes[${frame.index}].data`, projectionState);
|
|
803
|
+
if (inspection.inspectionError) {
|
|
804
|
+
markDebuggerProjectionTruncated(data, 'unavailable-properties', `$.nodes[${frame.index}].data`);
|
|
805
|
+
}
|
|
806
|
+
for (const entry of inspection.entries) {
|
|
807
|
+
if (entry.key === 'children')
|
|
808
|
+
continue;
|
|
809
|
+
if (projectionState.valueCount >= MAX_DEBUGGER_PROJECTION_VALUES) {
|
|
810
|
+
projectionState.complete = false;
|
|
811
|
+
markDebuggerProjectionTruncated(data, 'value-limit', `$.nodes[${frame.index}].data`);
|
|
812
|
+
break;
|
|
813
|
+
}
|
|
814
|
+
setDebuggerJsonProperty(data, entry.key, entry.accessor ? entry.value : projectDebuggerValue(entry.value, projectionState, entry.childPath));
|
|
815
|
+
}
|
|
816
|
+
nodes.push({
|
|
817
|
+
childIndexes: [],
|
|
818
|
+
data,
|
|
819
|
+
depth: frame.depth,
|
|
820
|
+
index: frame.index,
|
|
821
|
+
parentIndex: frame.parentIndex,
|
|
822
|
+
sourceChildIndex: frame.sourceChildIndex,
|
|
823
|
+
});
|
|
824
|
+
if (frame.parentIndex !== null)
|
|
825
|
+
nodes[frame.parentIndex]?.childIndexes.push(frame.index);
|
|
826
|
+
const children = debuggerTreeChildren(frame.node, `$.nodes[${frame.index}].children`);
|
|
827
|
+
if (!children.complete)
|
|
828
|
+
projectionState.complete = false;
|
|
829
|
+
truncations.push(...children.truncations);
|
|
830
|
+
frame.childEntries = children.entries;
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
let child = null;
|
|
834
|
+
while (frame.childEntries && frame.childIndex < frame.childEntries.length && !child) {
|
|
835
|
+
const candidate = frame.childEntries[frame.childIndex];
|
|
836
|
+
frame.childIndex += 1;
|
|
837
|
+
if (candidate && !visited.has(candidate.node))
|
|
838
|
+
child = candidate;
|
|
839
|
+
}
|
|
840
|
+
if (child) {
|
|
841
|
+
stack.push({
|
|
842
|
+
childEntries: null,
|
|
843
|
+
childIndex: 0,
|
|
844
|
+
depth: frame.depth + 1,
|
|
845
|
+
entered: false,
|
|
846
|
+
index: null,
|
|
847
|
+
node: child.node,
|
|
848
|
+
parentIndex: frame.index,
|
|
849
|
+
sourceChildIndex: child.index,
|
|
850
|
+
});
|
|
851
|
+
continue;
|
|
852
|
+
}
|
|
853
|
+
stack.pop();
|
|
854
|
+
}
|
|
855
|
+
return {
|
|
856
|
+
complete: projectionState.complete,
|
|
857
|
+
format: 'valdi-debugger-tree-v1',
|
|
858
|
+
nodeCount: nodes.length,
|
|
859
|
+
nodes,
|
|
860
|
+
rootIndex: 0,
|
|
861
|
+
truncations,
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
function sendJson(response, status, payload) {
|
|
865
|
+
if (response.headersSent) {
|
|
866
|
+
if (!response.writableEnded)
|
|
867
|
+
response.end();
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
response.writeHead(status, {
|
|
871
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
872
|
+
'Cache-Control': 'no-store',
|
|
873
|
+
});
|
|
874
|
+
response.end(JSON.stringify(payload));
|
|
875
|
+
}
|
|
876
|
+
function sendTraceJson(response, status, payload) {
|
|
877
|
+
const serialized = JSON.stringify(payload);
|
|
878
|
+
if (Buffer.byteLength(serialized, 'utf8') > exports.MAX_TRACE_HTTP_RESPONSE_BYTES) {
|
|
879
|
+
sendJson(response, 500, { error: 'Valdi performance trace response exceeded the HTTP size limit.' });
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
response.writeHead(status, {
|
|
883
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
884
|
+
'Cache-Control': 'no-store',
|
|
885
|
+
});
|
|
886
|
+
response.end(serialized);
|
|
887
|
+
}
|
|
888
|
+
async function readJsonBody(request) {
|
|
889
|
+
const chunks = [];
|
|
890
|
+
let byteLength = 0;
|
|
891
|
+
for await (const chunk of request) {
|
|
892
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
893
|
+
byteLength += buffer.length;
|
|
894
|
+
if (byteLength > 1024 * 1024) {
|
|
895
|
+
throw new ApiRequestError(413, 'Request body is too large.');
|
|
896
|
+
}
|
|
897
|
+
chunks.push(buffer);
|
|
898
|
+
}
|
|
899
|
+
let raw;
|
|
900
|
+
try {
|
|
901
|
+
raw = FATAL_JSON_UTF8_DECODER.decode(Buffer.concat(chunks, byteLength));
|
|
902
|
+
}
|
|
903
|
+
catch {
|
|
904
|
+
throw new ApiRequestError(400, 'Request body must contain valid UTF-8.');
|
|
905
|
+
}
|
|
906
|
+
if (!raw.trim())
|
|
907
|
+
return {};
|
|
908
|
+
let parsed;
|
|
909
|
+
try {
|
|
910
|
+
parsed = JSON.parse(raw);
|
|
911
|
+
}
|
|
912
|
+
catch {
|
|
913
|
+
throw new ApiRequestError(400, 'Request body must contain valid JSON.');
|
|
914
|
+
}
|
|
915
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
916
|
+
throw new ApiRequestError(400, 'Request body must be a JSON object.');
|
|
917
|
+
}
|
|
918
|
+
return parsed;
|
|
919
|
+
}
|
|
920
|
+
function readNumber(searchParams, key, fallback) {
|
|
921
|
+
const value = searchParams.get(key);
|
|
922
|
+
if (!value)
|
|
923
|
+
return fallback;
|
|
924
|
+
const parsed = Number.parseInt(value, 10);
|
|
925
|
+
return Number.isNaN(parsed) ? fallback : parsed;
|
|
926
|
+
}
|
|
927
|
+
function readBodyNumber(body, key, fallback) {
|
|
928
|
+
const value = body[key];
|
|
929
|
+
if (value === undefined)
|
|
930
|
+
return fallback;
|
|
931
|
+
const parsed = Number.parseInt(String(value), 10);
|
|
932
|
+
return Number.isNaN(parsed) ? fallback : parsed;
|
|
933
|
+
}
|
|
934
|
+
function readRendererTracing(body) {
|
|
935
|
+
const value = body['rendererTracing'];
|
|
936
|
+
if (value === undefined)
|
|
937
|
+
return true;
|
|
938
|
+
if (typeof value !== 'boolean') {
|
|
939
|
+
throw new ApiRequestError(400, 'rendererTracing must be a boolean when provided.');
|
|
940
|
+
}
|
|
941
|
+
return value;
|
|
942
|
+
}
|
|
943
|
+
function normalizeTraceCaptureDurationMs(body) {
|
|
944
|
+
const value = body['durationMs'];
|
|
945
|
+
if (value === undefined)
|
|
946
|
+
return DEFAULT_TRACE_CAPTURE_DURATION_MS;
|
|
947
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
948
|
+
throw new ApiRequestError(400, 'durationMs must be a finite number when provided.');
|
|
949
|
+
}
|
|
950
|
+
return clampNumber(Math.round(value), MIN_TRACE_CAPTURE_DURATION_MS, MAX_TRACE_CAPTURE_DURATION_MS);
|
|
951
|
+
}
|
|
952
|
+
function readBodyString(body, key) {
|
|
953
|
+
const value = body[key];
|
|
954
|
+
if (value === undefined || value === null || value === '')
|
|
955
|
+
return undefined;
|
|
956
|
+
return String(value);
|
|
957
|
+
}
|
|
958
|
+
function readRecordString(record, key) {
|
|
959
|
+
const value = record[key];
|
|
960
|
+
if (value === undefined || value === null || value === '')
|
|
961
|
+
return undefined;
|
|
962
|
+
return String(value);
|
|
963
|
+
}
|
|
964
|
+
function readDebuggerExactString(record, key, maximumLength, required = true) {
|
|
965
|
+
const value = record[key];
|
|
966
|
+
if (value === undefined && !required)
|
|
967
|
+
return undefined;
|
|
968
|
+
if (typeof value !== 'string' || value.trim().length === 0 || value.length > maximumLength) {
|
|
969
|
+
throw new ApiRequestError(400, `${key} must be a non-empty string of at most ${maximumLength.toString()} characters.`);
|
|
970
|
+
}
|
|
971
|
+
return value;
|
|
972
|
+
}
|
|
973
|
+
function readDebuggerBoundedRecord(record, key, maximumKeys, maximumBytes) {
|
|
974
|
+
const value = record[key];
|
|
975
|
+
if (value === undefined)
|
|
976
|
+
return {};
|
|
977
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
978
|
+
throw new ApiRequestError(400, `${key} must be an object.`);
|
|
979
|
+
}
|
|
980
|
+
const output = value;
|
|
981
|
+
if (Object.keys(output).length > maximumKeys || Buffer.byteLength(JSON.stringify(output), 'utf8') > maximumBytes) {
|
|
982
|
+
throw new ApiRequestError(400, `${key} exceeds debugger request bounds.`);
|
|
983
|
+
}
|
|
984
|
+
return output;
|
|
985
|
+
}
|
|
986
|
+
function readDebuggerPort(value, key = 'port') {
|
|
987
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > 65_535) {
|
|
988
|
+
throw new ApiRequestError(400, `${key} must be an integer between 1 and 65535.`);
|
|
989
|
+
}
|
|
990
|
+
return value;
|
|
991
|
+
}
|
|
992
|
+
function readDebuggerTargetSearchParams(record) {
|
|
993
|
+
const searchParams = new URLSearchParams();
|
|
994
|
+
searchParams.set('port', readDebuggerPort(record['port']).toString());
|
|
995
|
+
searchParams.set('clientId', readDebuggerExactString(record, 'clientId', 256));
|
|
996
|
+
searchParams.set('contextId', readDebuggerExactString(record, 'contextId', 256));
|
|
997
|
+
return searchParams;
|
|
998
|
+
}
|
|
999
|
+
function validateDebuggerSearchParams(searchParams) {
|
|
1000
|
+
const rawPort = searchParams.get('port');
|
|
1001
|
+
if (rawPort === null || !/^\d{1,5}$/.test(rawPort)) {
|
|
1002
|
+
throw new ApiRequestError(400, 'port must be an integer between 1 and 65535.');
|
|
1003
|
+
}
|
|
1004
|
+
const record = {
|
|
1005
|
+
port: Number(rawPort),
|
|
1006
|
+
clientId: searchParams.get('clientId'),
|
|
1007
|
+
contextId: searchParams.get('contextId'),
|
|
1008
|
+
};
|
|
1009
|
+
return readDebuggerTargetSearchParams(record);
|
|
1010
|
+
}
|
|
1011
|
+
function readDebuggerSettingValue(value) {
|
|
1012
|
+
if (typeof value === 'number') {
|
|
1013
|
+
if (!Number.isFinite(value))
|
|
1014
|
+
throw new ApiRequestError(400, 'Debug setting numbers must be finite.');
|
|
1015
|
+
return value;
|
|
1016
|
+
}
|
|
1017
|
+
if (typeof value === 'string') {
|
|
1018
|
+
if (value.length > 4096)
|
|
1019
|
+
throw new ApiRequestError(400, 'Debug setting strings cannot exceed 4096 characters.');
|
|
1020
|
+
return value;
|
|
1021
|
+
}
|
|
1022
|
+
if (typeof value === 'boolean')
|
|
1023
|
+
return value;
|
|
1024
|
+
throw new ApiRequestError(400, 'Debug setting values must be boolean, number, or string primitives.');
|
|
1025
|
+
}
|
|
1026
|
+
function readRecordBoolean(record, key) {
|
|
1027
|
+
const value = record[key];
|
|
1028
|
+
if (value === undefined || value === null || value === '')
|
|
1029
|
+
return undefined;
|
|
1030
|
+
if (typeof value === 'boolean')
|
|
1031
|
+
return value;
|
|
1032
|
+
const normalized = String(value).toLowerCase();
|
|
1033
|
+
if (['1', 'true', 'yes', 'on'].includes(normalized))
|
|
1034
|
+
return true;
|
|
1035
|
+
if (['0', 'false', 'no', 'off'].includes(normalized))
|
|
1036
|
+
return false;
|
|
1037
|
+
return Boolean(value);
|
|
1038
|
+
}
|
|
1039
|
+
function clampNumber(value, min, max) {
|
|
1040
|
+
return Math.max(min, Math.min(max, value));
|
|
1041
|
+
}
|
|
1042
|
+
function createInterruptibleOperation(durationMs, complete) {
|
|
1043
|
+
let signalCompletion;
|
|
1044
|
+
const signal = new Promise(resolve => {
|
|
1045
|
+
signalCompletion = resolve;
|
|
1046
|
+
});
|
|
1047
|
+
const timer = setTimeout(() => signalCompletion?.(), durationMs);
|
|
1048
|
+
let completion;
|
|
1049
|
+
const stop = () => {
|
|
1050
|
+
clearTimeout(timer);
|
|
1051
|
+
signalCompletion?.();
|
|
1052
|
+
completion ??= Promise.resolve().then(complete);
|
|
1053
|
+
return completion;
|
|
1054
|
+
};
|
|
1055
|
+
return {
|
|
1056
|
+
result: signal.then(stop),
|
|
1057
|
+
stop,
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
function delay(durationMs) {
|
|
1061
|
+
return new Promise(resolve => {
|
|
1062
|
+
const timer = setTimeout(resolve, durationMs);
|
|
1063
|
+
timer.unref();
|
|
1064
|
+
});
|
|
1065
|
+
}
|
|
1066
|
+
function createWebPreviewDebuggerTarget(webPreviewUrl, debuggingPort) {
|
|
1067
|
+
if (webPreviewUrl !== undefined && Buffer.byteLength(webPreviewUrl, 'utf8') > MAX_WEB_PREVIEW_URL_BYTES) {
|
|
1068
|
+
throw new Error(`The integrated DevTools web preview URL cannot exceed ${MAX_WEB_PREVIEW_URL_BYTES} bytes.`);
|
|
1069
|
+
}
|
|
1070
|
+
const rawUrl = webPreviewUrl?.trim();
|
|
1071
|
+
if (!rawUrl)
|
|
1072
|
+
return null;
|
|
1073
|
+
if (!Number.isInteger(debuggingPort) || debuggingPort < 1 || debuggingPort > 65_535) {
|
|
1074
|
+
throw new Error(`Chromium debugging port must be an integer between 1 and 65535; received '${String(debuggingPort)}'.`);
|
|
1075
|
+
}
|
|
1076
|
+
let applicationUrl;
|
|
1077
|
+
try {
|
|
1078
|
+
applicationUrl = new URL(rawUrl);
|
|
1079
|
+
}
|
|
1080
|
+
catch {
|
|
1081
|
+
throw new Error(`Invalid web preview URL: ${rawUrl}`);
|
|
1082
|
+
}
|
|
1083
|
+
if (applicationUrl.protocol !== 'http:' ||
|
|
1084
|
+
!(0, loopbackHost_1.isLoopbackHost)(applicationUrl.hostname) ||
|
|
1085
|
+
applicationUrl.username ||
|
|
1086
|
+
applicationUrl.password) {
|
|
1087
|
+
throw new Error('The integrated DevTools web preview must use an unauthenticated loopback HTTP URL.');
|
|
1088
|
+
}
|
|
1089
|
+
const normalizedApplicationUrl = applicationUrl.toString();
|
|
1090
|
+
if (Buffer.byteLength(normalizedApplicationUrl, 'utf8') > MAX_WEB_PREVIEW_URL_BYTES) {
|
|
1091
|
+
throw new Error(`The integrated DevTools web preview URL cannot exceed ${MAX_WEB_PREVIEW_URL_BYTES} bytes.`);
|
|
1092
|
+
}
|
|
1093
|
+
const name = applicationUrl.pathname.split('/').filter(Boolean).at(-1) ?? applicationUrl.hostname;
|
|
1094
|
+
if (Buffer.byteLength(name, 'utf8') > MAX_WEB_PREVIEW_TARGET_NAME_BYTES) {
|
|
1095
|
+
throw new Error(`The integrated DevTools web preview target name cannot exceed ${MAX_WEB_PREVIEW_TARGET_NAME_BYTES} bytes.`);
|
|
1096
|
+
}
|
|
1097
|
+
return {
|
|
1098
|
+
applicationUrl: normalizedApplicationUrl,
|
|
1099
|
+
debuggingPort,
|
|
1100
|
+
id: 'owl:web-preview',
|
|
1101
|
+
name,
|
|
1102
|
+
sessionId: 'web-preview',
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
function webPreviewTargetPayload(target) {
|
|
1106
|
+
return {
|
|
1107
|
+
applicationId: target.applicationUrl,
|
|
1108
|
+
applicationUrl: target.applicationUrl,
|
|
1109
|
+
attachable: true,
|
|
1110
|
+
capabilities: [
|
|
1111
|
+
targetRegistry_1.DebuggerTargetCapability.Components,
|
|
1112
|
+
targetRegistry_1.DebuggerTargetCapability.ComponentProperties,
|
|
1113
|
+
targetRegistry_1.DebuggerTargetCapability.Snapshot,
|
|
1114
|
+
targetRegistry_1.DebuggerTargetCapability.Highlight,
|
|
1115
|
+
targetRegistry_1.DebuggerTargetCapability.Console,
|
|
1116
|
+
targetRegistry_1.DebuggerTargetCapability.Performance,
|
|
1117
|
+
],
|
|
1118
|
+
debuggingPort: target.debuggingPort,
|
|
1119
|
+
id: target.id,
|
|
1120
|
+
identityMode: targetRegistry_1.DebuggerTargetIdentityMode.InspectedPage,
|
|
1121
|
+
name: target.name,
|
|
1122
|
+
owlTarget: true,
|
|
1123
|
+
platform: targetRegistry_1.DebuggerTargetPlatform.Web,
|
|
1124
|
+
sessionId: target.sessionId,
|
|
1125
|
+
state: targetRegistry_1.DebuggerTargetState.Available,
|
|
1126
|
+
transport: targetRegistry_1.DebuggerTargetTransport.ChromiumCDP,
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
function legacyWebPreviewTargetPayload(target) {
|
|
1130
|
+
return {
|
|
1131
|
+
applicationId: target.applicationUrl,
|
|
1132
|
+
applicationUrl: target.applicationUrl,
|
|
1133
|
+
debuggingPort: target.debuggingPort,
|
|
1134
|
+
id: target.id,
|
|
1135
|
+
name: target.name,
|
|
1136
|
+
owlTarget: true,
|
|
1137
|
+
platform: 'web',
|
|
1138
|
+
sessionId: target.sessionId,
|
|
1139
|
+
state: 'available',
|
|
1140
|
+
transport: 'chromium-cdp',
|
|
1141
|
+
};
|
|
1142
|
+
}
|
|
1143
|
+
function resolveWebPreviewDebuggerTarget(sessionId) {
|
|
1144
|
+
if (!activeWebPreviewTarget ||
|
|
1145
|
+
!sessionId ||
|
|
1146
|
+
![activeWebPreviewTarget.id, activeWebPreviewTarget.sessionId].includes(sessionId)) {
|
|
1147
|
+
throw new ApiRequestError(404, 'The configured web preview debugger target is not available.');
|
|
1148
|
+
}
|
|
1149
|
+
return activeWebPreviewTarget;
|
|
1150
|
+
}
|
|
1151
|
+
function resolveInspectedWebPreviewContext(target, inspectedUrl, targetNonce) {
|
|
1152
|
+
if (!inspectedUrl) {
|
|
1153
|
+
throw new ApiRequestError(400, 'DevTools target discovery requires the inspected page URL.');
|
|
1154
|
+
}
|
|
1155
|
+
if (!targetNonce || !WEB_PREVIEW_NONCE_PATTERN.test(targetNonce)) {
|
|
1156
|
+
throw new ApiRequestError(400, 'DevTools target discovery requires a valid inspected-tab nonce.');
|
|
1157
|
+
}
|
|
1158
|
+
let inspected;
|
|
1159
|
+
try {
|
|
1160
|
+
inspected = new URL(inspectedUrl);
|
|
1161
|
+
}
|
|
1162
|
+
catch {
|
|
1163
|
+
throw new ApiRequestError(400, 'The inspected web preview URL is invalid.');
|
|
1164
|
+
}
|
|
1165
|
+
if (inspected.protocol !== 'http:' ||
|
|
1166
|
+
!(0, loopbackHost_1.isLoopbackHost)(inspected.hostname) ||
|
|
1167
|
+
inspected.username ||
|
|
1168
|
+
inspected.password) {
|
|
1169
|
+
throw new ApiRequestError(400, 'Valdi DevTools only attaches to an unauthenticated loopback application page.');
|
|
1170
|
+
}
|
|
1171
|
+
if (!(0, owlCdpClient_1.matchesOwlApplicationUrl)(inspected.toString(), target.applicationUrl)) {
|
|
1172
|
+
throw new ApiRequestError(404, 'The inspected page does not match the configured Valdi web preview target.');
|
|
1173
|
+
}
|
|
1174
|
+
return { inspectedUrl: inspected.toString(), targetNonce };
|
|
1175
|
+
}
|
|
1176
|
+
function resolveWebPreviewPerformanceIdentity(searchParams) {
|
|
1177
|
+
if (searchParams.getAll('targetId').length > 0) {
|
|
1178
|
+
throw new ApiRequestError(400, 'Web preview performance requests do not accept debugger target IDs.');
|
|
1179
|
+
}
|
|
1180
|
+
const sessionId = readExactWebPreviewPerformanceParameter(searchParams, 'sessionId');
|
|
1181
|
+
const target = resolveWebPreviewDebuggerTarget(sessionId);
|
|
1182
|
+
if (sessionId !== target.sessionId) {
|
|
1183
|
+
throw new ApiRequestError(404, 'The inspected web preview session is no longer available.');
|
|
1184
|
+
}
|
|
1185
|
+
const context = resolveInspectedWebPreviewContext(target, readExactWebPreviewPerformanceParameter(searchParams, 'inspectedUrl'), readExactWebPreviewPerformanceParameter(searchParams, 'targetNonce'));
|
|
1186
|
+
return {
|
|
1187
|
+
identity: {
|
|
1188
|
+
applicationUrl: target.applicationUrl,
|
|
1189
|
+
debuggingPort: target.debuggingPort,
|
|
1190
|
+
inspectedUrl: context.inspectedUrl,
|
|
1191
|
+
sessionId: target.sessionId,
|
|
1192
|
+
targetNonce: context.targetNonce,
|
|
1193
|
+
},
|
|
1194
|
+
target,
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
function readExactWebPreviewPerformanceParameter(searchParams, name) {
|
|
1198
|
+
const values = searchParams.getAll(name);
|
|
1199
|
+
if (values.length !== 1 || !values[0]) {
|
|
1200
|
+
throw new ApiRequestError(400, `${name} must appear exactly once for web preview performance requests.`);
|
|
1201
|
+
}
|
|
1202
|
+
return values[0];
|
|
1203
|
+
}
|
|
1204
|
+
function readAtMostOneDebuggerParameter(searchParams, name) {
|
|
1205
|
+
const values = searchParams.getAll(name);
|
|
1206
|
+
if (values.length > 1) {
|
|
1207
|
+
throw new ApiRequestError(400, `${name} must not appear more than once in a debugger target identity.`);
|
|
1208
|
+
}
|
|
1209
|
+
return values[0] || undefined;
|
|
1210
|
+
}
|
|
1211
|
+
function readExactDebuggerParameter(searchParams, name) {
|
|
1212
|
+
const value = readAtMostOneDebuggerParameter(searchParams, name);
|
|
1213
|
+
if (!value) {
|
|
1214
|
+
throw new ApiRequestError(400, `${name} must appear exactly once in a debugger target identity.`);
|
|
1215
|
+
}
|
|
1216
|
+
return value;
|
|
1217
|
+
}
|
|
1218
|
+
function rejectDebuggerIdentityParameters(searchParams, names) {
|
|
1219
|
+
const present = names.find(name => searchParams.getAll(name).length > 0);
|
|
1220
|
+
if (present !== undefined) {
|
|
1221
|
+
throw new ApiRequestError(400, `Debugger target identity modes cannot mix ${present} with this request.`);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
function resolveInspectedWebPreviewTarget(searchParams) {
|
|
1225
|
+
if (!activeWebPreviewTarget) {
|
|
1226
|
+
throw new ApiRequestError(404, 'Start valdi debugger with --web-preview-url before opening the DevTools panel.');
|
|
1227
|
+
}
|
|
1228
|
+
rejectDebuggerIdentityParameters(searchParams, ['targetId', 'sessionId', 'port', 'clientId', 'contextId']);
|
|
1229
|
+
resolveInspectedWebPreviewContext(activeWebPreviewTarget, readAtMostOneDebuggerParameter(searchParams, 'inspectedUrl'), readAtMostOneDebuggerParameter(searchParams, 'targetNonce'));
|
|
1230
|
+
return { target: webPreviewTargetPayload(activeWebPreviewTarget) };
|
|
1231
|
+
}
|
|
1232
|
+
function decorateWebPreviewTraceResult(result, target) {
|
|
1233
|
+
return decorateTraceResult({ ...result, webPreviewTrace: true }, { ...webPreviewTargetPayload(target), state: 'attached' });
|
|
1234
|
+
}
|
|
1235
|
+
function webPreviewTraceCaptureResult(capture) {
|
|
1236
|
+
return {
|
|
1237
|
+
...capture,
|
|
1238
|
+
completedRecordingAvailable: false,
|
|
1239
|
+
recording: false,
|
|
1240
|
+
tracingSupported: true,
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
async function inspectWebPreviewPerformanceSnapshot(request, searchParams) {
|
|
1244
|
+
if (request.method !== 'GET') {
|
|
1245
|
+
throw new ApiRequestError(405, 'Web preview performance snapshots require GET.');
|
|
1246
|
+
}
|
|
1247
|
+
const { identity, target } = resolveWebPreviewPerformanceIdentity(searchParams);
|
|
1248
|
+
return {
|
|
1249
|
+
...(await webPreviewPerformanceController.snapshot(identity)),
|
|
1250
|
+
target: { ...webPreviewTargetPayload(target), state: 'attached' },
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
async function inspectWebPreviewPerformanceTraceStatus(request, searchParams) {
|
|
1254
|
+
if (request.method !== 'GET') {
|
|
1255
|
+
throw new ApiRequestError(405, 'Web preview performance trace status requires GET.');
|
|
1256
|
+
}
|
|
1257
|
+
const { identity, target } = resolveWebPreviewPerformanceIdentity(searchParams);
|
|
1258
|
+
return decorateWebPreviewTraceResult({ ...(await webPreviewPerformanceController.status(identity)) }, target);
|
|
1259
|
+
}
|
|
1260
|
+
async function startWebPreviewPerformanceTrace(request, searchParams) {
|
|
1261
|
+
if (request.method !== 'POST') {
|
|
1262
|
+
throw new ApiRequestError(405, 'Web preview performance trace start requires POST.');
|
|
1263
|
+
}
|
|
1264
|
+
await readJsonBody(request);
|
|
1265
|
+
const { identity, target } = resolveWebPreviewPerformanceIdentity(searchParams);
|
|
1266
|
+
return decorateWebPreviewTraceResult({ ...(await webPreviewPerformanceController.start(identity)) }, target);
|
|
1267
|
+
}
|
|
1268
|
+
async function stopWebPreviewPerformanceTrace(request, searchParams) {
|
|
1269
|
+
if (request.method !== 'POST') {
|
|
1270
|
+
throw new ApiRequestError(405, 'Web preview performance trace stop requires POST.');
|
|
1271
|
+
}
|
|
1272
|
+
await readJsonBody(request);
|
|
1273
|
+
const { identity, target } = resolveWebPreviewPerformanceIdentity(searchParams);
|
|
1274
|
+
const capture = await webPreviewPerformanceController.stop(identity);
|
|
1275
|
+
return decorateWebPreviewTraceResult(webPreviewTraceCaptureResult(capture), target);
|
|
1276
|
+
}
|
|
1277
|
+
async function captureWebPreviewPerformanceTrace(request, searchParams) {
|
|
1278
|
+
if (request.method !== 'POST') {
|
|
1279
|
+
throw new ApiRequestError(405, 'Web preview performance trace capture requires POST.');
|
|
1280
|
+
}
|
|
1281
|
+
const body = await readJsonBody(request);
|
|
1282
|
+
const durationMs = normalizeTraceCaptureDurationMs(body);
|
|
1283
|
+
const { identity, target } = resolveWebPreviewPerformanceIdentity(searchParams);
|
|
1284
|
+
const capture = await webPreviewPerformanceController.capture(identity, durationMs);
|
|
1285
|
+
return decorateWebPreviewTraceResult(webPreviewTraceCaptureResult(capture), target);
|
|
1286
|
+
}
|
|
1287
|
+
async function enableWebPreviewPerformanceTracing(request, searchParams) {
|
|
1288
|
+
if (request.method !== 'POST') {
|
|
1289
|
+
throw new ApiRequestError(405, 'Web preview renderer tracing enablement requires POST.');
|
|
1290
|
+
}
|
|
1291
|
+
await readJsonBody(request);
|
|
1292
|
+
const { identity, target } = resolveWebPreviewPerformanceIdentity(searchParams);
|
|
1293
|
+
const inspectedUrl = await webPreviewPerformanceController.enableTracing(identity);
|
|
1294
|
+
return {
|
|
1295
|
+
inspectedUrl,
|
|
1296
|
+
rendererTracingEnabled: true,
|
|
1297
|
+
target: { ...webPreviewTargetPayload(target), state: 'attached' },
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
function readUnknownRecord(value) {
|
|
1301
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
|
|
1302
|
+
}
|
|
1303
|
+
async function inspectWebPreviewSnapshot(searchParams) {
|
|
1304
|
+
rejectDebuggerIdentityParameters(searchParams, ['targetId', 'port', 'clientId', 'contextId']);
|
|
1305
|
+
const sessionId = readExactDebuggerParameter(searchParams, 'sessionId');
|
|
1306
|
+
const target = resolveWebPreviewDebuggerTarget(sessionId);
|
|
1307
|
+
if (sessionId !== target.sessionId) {
|
|
1308
|
+
throw new ApiRequestError(404, 'The inspected web preview session is no longer available.');
|
|
1309
|
+
}
|
|
1310
|
+
const context = resolveInspectedWebPreviewContext(target, readExactDebuggerParameter(searchParams, 'inspectedUrl'), readExactDebuggerParameter(searchParams, 'targetNonce'));
|
|
1311
|
+
const bridgePayload = await (0, owlCdpClient_1.readOwlDebuggerSnapshot)(target.debuggingPort, target.applicationUrl, context.targetNonce);
|
|
1312
|
+
if (bridgePayload['channel'] !== 'valdi-web-debugger' || bridgePayload['type'] !== 'snapshot') {
|
|
1313
|
+
throw new Error('The running web preview returned an invalid Valdi debugger bridge payload.');
|
|
1314
|
+
}
|
|
1315
|
+
const snapshot = readUnknownRecord(bridgePayload['snapshot']);
|
|
1316
|
+
const tree = snapshot['tree'];
|
|
1317
|
+
if (typeof tree !== 'object' || tree === null || Array.isArray(tree)) {
|
|
1318
|
+
throw new Error('The running web preview has not mounted a Valdi renderer.');
|
|
1319
|
+
}
|
|
1320
|
+
let snapshotTarget = webPreviewTargetPayload(target);
|
|
1321
|
+
if (bridgePayload['componentPropertyEditingAvailable'] === true &&
|
|
1322
|
+
bridgePayload['componentPropertyEditProtocolVersion'] === COMPONENT_PROPERTY_EDIT_PROTOCOL_VERSION) {
|
|
1323
|
+
snapshotTarget = {
|
|
1324
|
+
...snapshotTarget,
|
|
1325
|
+
capabilities: snapshotTarget.capabilities.flatMap(capability => capability === targetRegistry_1.DebuggerTargetCapability.ComponentProperties
|
|
1326
|
+
? [capability, targetRegistry_1.DebuggerTargetCapability.ComponentPropertyEdit]
|
|
1327
|
+
: [capability]),
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
return {
|
|
1331
|
+
issues: [],
|
|
1332
|
+
logs: [],
|
|
1333
|
+
selectedNodeId: bridgePayload['selectedNodeId'],
|
|
1334
|
+
source: 'owl',
|
|
1335
|
+
target: { ...snapshotTarget, state: 'attached' },
|
|
1336
|
+
targets: [snapshotTarget],
|
|
1337
|
+
tree: projectDebuggerTreeForJson(tree),
|
|
1338
|
+
viewport: snapshot['viewport'],
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1341
|
+
function readComponentPropertyEditRequest(body) {
|
|
1342
|
+
const protocolVersion = body['protocolVersion'];
|
|
1343
|
+
if (!Number.isSafeInteger(protocolVersion)) {
|
|
1344
|
+
throw new ApiRequestError(400, 'protocolVersion must be a supported safe integer.');
|
|
1345
|
+
}
|
|
1346
|
+
const expectedKeys = COMPONENT_PROPERTY_EDIT_REQUEST_KEYS_BY_PROTOCOL_VERSION.get(protocolVersion);
|
|
1347
|
+
if (expectedKeys === undefined) {
|
|
1348
|
+
throw new ApiRequestError(400, 'protocolVersion is not supported.');
|
|
1349
|
+
}
|
|
1350
|
+
const keys = Object.keys(body).sort();
|
|
1351
|
+
if (keys.length !== expectedKeys.length || keys.some((key, index) => key !== expectedKeys[index])) {
|
|
1352
|
+
throw new ApiRequestError(400, 'Component property edits require the exact debugger identity and edit tuple.');
|
|
1353
|
+
}
|
|
1354
|
+
const componentId = readDebuggerExactString(body, 'componentId', MAX_COMPONENT_ID_CHARACTERS);
|
|
1355
|
+
const componentToken = readDebuggerExactString(body, 'componentToken', 32);
|
|
1356
|
+
const inspectedUrl = readDebuggerExactString(body, 'inspectedUrl', MAX_WEB_PREVIEW_URL_BYTES);
|
|
1357
|
+
const propertyName = readDebuggerExactString(body, 'propertyName', MAX_COMPONENT_PROPERTY_NAME_CHARACTERS);
|
|
1358
|
+
const sessionId = readDebuggerExactString(body, 'sessionId', 256);
|
|
1359
|
+
const targetNonce = readDebuggerExactString(body, 'targetNonce', 128);
|
|
1360
|
+
const snapshotRevision = body['snapshotRevision'];
|
|
1361
|
+
const value = body['value'];
|
|
1362
|
+
if (!COMPONENT_PROPERTY_TOKEN_PATTERN.test(componentToken)) {
|
|
1363
|
+
throw new ApiRequestError(400, 'componentToken must be a 128-bit lowercase hexadecimal token.');
|
|
1364
|
+
}
|
|
1365
|
+
if (!Number.isSafeInteger(snapshotRevision) || snapshotRevision <= 0) {
|
|
1366
|
+
throw new ApiRequestError(400, 'snapshotRevision must be a positive safe integer.');
|
|
1367
|
+
}
|
|
1368
|
+
if (FORBIDDEN_COMPONENT_PROPERTY_NAMES.has(propertyName)) {
|
|
1369
|
+
throw new ApiRequestError(400, 'propertyName is not editable.');
|
|
1370
|
+
}
|
|
1371
|
+
if (!(typeof value === 'boolean' ||
|
|
1372
|
+
(typeof value === 'string' && Buffer.byteLength(value, 'utf8') <= MAX_COMPONENT_PROPERTY_STRING_BYTES) ||
|
|
1373
|
+
(typeof value === 'number' && Number.isFinite(value) && !Object.is(value, -0)))) {
|
|
1374
|
+
throw new ApiRequestError(400, 'value must be a bounded string, boolean, or finite non-negative-zero number.');
|
|
1375
|
+
}
|
|
1376
|
+
return {
|
|
1377
|
+
componentId,
|
|
1378
|
+
componentToken,
|
|
1379
|
+
inspectedUrl,
|
|
1380
|
+
propertyName,
|
|
1381
|
+
protocolVersion: protocolVersion,
|
|
1382
|
+
sessionId,
|
|
1383
|
+
snapshotRevision: snapshotRevision,
|
|
1384
|
+
targetNonce,
|
|
1385
|
+
value,
|
|
1386
|
+
};
|
|
1387
|
+
}
|
|
1388
|
+
async function editWebPreviewComponentProperty(request, searchParams) {
|
|
1389
|
+
if (request.method !== 'POST') {
|
|
1390
|
+
throw new ApiRequestError(405, 'Component property edits require POST.');
|
|
1391
|
+
}
|
|
1392
|
+
if (Array.from(searchParams).length > 0) {
|
|
1393
|
+
throw new ApiRequestError(400, 'Component property edits accept identity only in the exact request body.');
|
|
1394
|
+
}
|
|
1395
|
+
const editRequest = readComponentPropertyEditRequest(await readJsonBody(request));
|
|
1396
|
+
const target = resolveWebPreviewDebuggerTarget(editRequest.sessionId);
|
|
1397
|
+
if (editRequest.sessionId !== target.sessionId) {
|
|
1398
|
+
throw new ApiRequestError(404, 'The inspected web preview session is no longer available.');
|
|
1399
|
+
}
|
|
1400
|
+
const context = resolveInspectedWebPreviewContext(target, editRequest.inspectedUrl, editRequest.targetNonce);
|
|
1401
|
+
const bridgeRequest = {
|
|
1402
|
+
componentId: editRequest.componentId,
|
|
1403
|
+
componentToken: editRequest.componentToken,
|
|
1404
|
+
propertyName: editRequest.propertyName,
|
|
1405
|
+
protocolVersion: editRequest.protocolVersion,
|
|
1406
|
+
snapshotRevision: editRequest.snapshotRevision,
|
|
1407
|
+
value: editRequest.value,
|
|
1408
|
+
};
|
|
1409
|
+
try {
|
|
1410
|
+
const updated = await (0, owlCdpClient_1.evaluateOwlApplicationExpression)(target.debuggingPort, target.applicationUrl, context.targetNonce, `globalThis.__VALDI_WEB_DEBUGGER__?.editComponentProperty?.(${JSON.stringify(bridgeRequest)})`);
|
|
1411
|
+
if (updated !== true)
|
|
1412
|
+
throw new Error(COMPONENT_PROPERTY_EDIT_ERROR);
|
|
1413
|
+
}
|
|
1414
|
+
catch {
|
|
1415
|
+
throw new ApiRequestError(409, COMPONENT_PROPERTY_EDIT_ERROR);
|
|
1416
|
+
}
|
|
1417
|
+
return { updated: true };
|
|
1418
|
+
}
|
|
1419
|
+
async function evaluateWebPreviewConsole(params) {
|
|
1420
|
+
const target = resolveWebPreviewDebuggerTarget(readRecordString(params, 'sessionId'));
|
|
1421
|
+
const context = resolveInspectedWebPreviewContext(target, readRecordString(params, 'inspectedUrl'), readRecordString(params, 'targetNonce'));
|
|
1422
|
+
const expression = readRecordString(params, 'expression')?.trim();
|
|
1423
|
+
if (!expression) {
|
|
1424
|
+
throw new ApiRequestError(400, 'Web preview console evaluation requires a JavaScript expression.');
|
|
1425
|
+
}
|
|
1426
|
+
if (expression.length > 10_000) {
|
|
1427
|
+
throw new ApiRequestError(400, 'Web preview console expressions cannot exceed 10,000 characters.');
|
|
1428
|
+
}
|
|
1429
|
+
const wrapped = `Promise.resolve().then(() => (0, eval)(${JSON.stringify(expression)})).then(value => ({ ` +
|
|
1430
|
+
"type: value === null ? 'null' : typeof value, value: value === undefined ? null : value }))";
|
|
1431
|
+
const result = await (0, owlCdpClient_1.evaluateOwlApplicationExpression)(target.debuggingPort, target.applicationUrl, context.targetNonce, wrapped);
|
|
1432
|
+
if (typeof result !== 'object' || result === null || Array.isArray(result)) {
|
|
1433
|
+
throw new Error('The web preview console returned an invalid evaluation result.');
|
|
1434
|
+
}
|
|
1435
|
+
return { ...result, sessionId: target.sessionId };
|
|
1436
|
+
}
|
|
1437
|
+
async function highlightWebPreviewNode(params) {
|
|
1438
|
+
const target = resolveWebPreviewDebuggerTarget(readRecordString(params, 'sessionId'));
|
|
1439
|
+
const context = resolveInspectedWebPreviewContext(target, readRecordString(params, 'inspectedUrl'), readRecordString(params, 'targetNonce'));
|
|
1440
|
+
const nodeId = readRecordString(params, 'nodeId');
|
|
1441
|
+
const expression = nodeId === undefined
|
|
1442
|
+
? 'Boolean(globalThis.__VALDI_WEB_DEBUGGER__?.clearHighlight?.())'
|
|
1443
|
+
: `Boolean(globalThis.__VALDI_WEB_DEBUGGER__?.highlightNode?.(${JSON.stringify(nodeId)}))`;
|
|
1444
|
+
const highlighted = await (0, owlCdpClient_1.evaluateOwlApplicationExpression)(target.debuggingPort, target.applicationUrl, context.targetNonce, expression);
|
|
1445
|
+
return {
|
|
1446
|
+
highlighted: highlighted === true,
|
|
1447
|
+
...(nodeId === undefined ? {} : { nodeId }),
|
|
1448
|
+
sessionId: target.sessionId,
|
|
1449
|
+
};
|
|
1450
|
+
}
|
|
1451
|
+
function createDebuggerUiState(port) {
|
|
1452
|
+
return {
|
|
1453
|
+
revision: 0,
|
|
1454
|
+
selectedNodeId: null,
|
|
1455
|
+
selectedTargetId: null,
|
|
1456
|
+
activeSection: 'ui',
|
|
1457
|
+
activeTab: 'overview',
|
|
1458
|
+
overlayMode: 'live',
|
|
1459
|
+
autoRefresh: false,
|
|
1460
|
+
followLatestTarget: true,
|
|
1461
|
+
port,
|
|
1462
|
+
updatedAt: new Date().toISOString(),
|
|
1463
|
+
lastAction: null,
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
function normalizeDebuggerSection(section) {
|
|
1467
|
+
const normalized = section.trim().toLowerCase();
|
|
1468
|
+
if (normalized === 'logger' || normalized === 'loger')
|
|
1469
|
+
return 'logs';
|
|
1470
|
+
return normalized;
|
|
1471
|
+
}
|
|
1472
|
+
function readValdiLogsDirectory() {
|
|
1473
|
+
if (activeLogsDirectory !== null)
|
|
1474
|
+
return activeLogsDirectory;
|
|
1475
|
+
const logsOutputDirectory = (0, fileUtils_1.getUserConfig)().logs_output_dir;
|
|
1476
|
+
if (typeof logsOutputDirectory !== 'string' || logsOutputDirectory.trim() === '') {
|
|
1477
|
+
throw new Error("Missing 'logs_output_dir' config value in the Valdi config file.");
|
|
1478
|
+
}
|
|
1479
|
+
return (0, fileUtils_1.resolveFilePath)(logsOutputDirectory);
|
|
1480
|
+
}
|
|
1481
|
+
async function collectLogFiles(directory) {
|
|
1482
|
+
const files = [];
|
|
1483
|
+
async function visit(dir) {
|
|
1484
|
+
const entries = await promises_1.default.readdir(dir, { withFileTypes: true });
|
|
1485
|
+
for (const entry of entries) {
|
|
1486
|
+
const fullPath = node_path_1.default.join(dir, entry.name);
|
|
1487
|
+
if (entry.isDirectory()) {
|
|
1488
|
+
await visit(fullPath);
|
|
1489
|
+
}
|
|
1490
|
+
else if (entry.isFile() && fullPath.endsWith('.log')) {
|
|
1491
|
+
const stat = await promises_1.default.stat(fullPath);
|
|
1492
|
+
files.push({ path: fullPath, stat });
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
await visit(directory);
|
|
1497
|
+
return files.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
|
|
1498
|
+
}
|
|
1499
|
+
function parseValdiLogRecords(content, limit, startOffset) {
|
|
1500
|
+
const records = [];
|
|
1501
|
+
let current = null;
|
|
1502
|
+
let byteOffset = startOffset;
|
|
1503
|
+
const linePattern = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) [+-]\d{4} \[(debug|log|info|warn|error)] (.*)$/;
|
|
1504
|
+
function pushCurrent() {
|
|
1505
|
+
if (current)
|
|
1506
|
+
records.push(current);
|
|
1507
|
+
current = null;
|
|
1508
|
+
}
|
|
1509
|
+
for (const rawLine of content.match(/[^\n]*(?:\n|$)/g) ?? []) {
|
|
1510
|
+
if (rawLine === '')
|
|
1511
|
+
continue;
|
|
1512
|
+
const lineOffset = byteOffset;
|
|
1513
|
+
byteOffset += Buffer.byteLength(rawLine, 'utf8');
|
|
1514
|
+
const line = rawLine.endsWith('\n') ? rawLine.slice(0, -1).replace(/\r$/, '') : rawLine;
|
|
1515
|
+
const match = line.match(linePattern);
|
|
1516
|
+
if (match) {
|
|
1517
|
+
pushCurrent();
|
|
1518
|
+
const rawMessage = match[4] ?? '';
|
|
1519
|
+
const isJsLog = rawMessage.startsWith('[JS]');
|
|
1520
|
+
current = {
|
|
1521
|
+
entry: {
|
|
1522
|
+
time: match[2] ?? '',
|
|
1523
|
+
level: match[3] === 'log' ? 'info' : (match[3] ?? 'info'),
|
|
1524
|
+
source: isJsLog ? 'js' : 'valdi',
|
|
1525
|
+
message: isJsLog ? rawMessage.replace(/^\[JS]\s*/, '') : rawMessage,
|
|
1526
|
+
timestamp: `${match[1] ?? ''}T${match[2] ?? ''}Z`,
|
|
1527
|
+
},
|
|
1528
|
+
offset: lineOffset,
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
else if (/^-+ Session started /.test(line)) {
|
|
1532
|
+
pushCurrent();
|
|
1533
|
+
records.length = 0;
|
|
1534
|
+
}
|
|
1535
|
+
else if (/^-+ Session /.test(line)) {
|
|
1536
|
+
pushCurrent();
|
|
1537
|
+
}
|
|
1538
|
+
else if (current && line.trim()) {
|
|
1539
|
+
current.entry.message += `\n${line}`;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
pushCurrent();
|
|
1543
|
+
return records.slice(-limit);
|
|
1544
|
+
}
|
|
1545
|
+
function parseValdiLog(content, limit) {
|
|
1546
|
+
return parseValdiLogRecords(content, limit, 0).map(record => record.entry);
|
|
1547
|
+
}
|
|
1548
|
+
async function inspectRuntimeLogs(searchParams) {
|
|
1549
|
+
const limit = clampNumber(readNumber(searchParams, 'limit', 120), 1, 1000);
|
|
1550
|
+
const selected = await selectRuntimeLogFile(searchParams);
|
|
1551
|
+
if (!selected.latest)
|
|
1552
|
+
return { logFile: null, logs: [] };
|
|
1553
|
+
const { content } = await readRuntimeLogTail(selected.latest);
|
|
1554
|
+
return {
|
|
1555
|
+
logFile: node_path_1.default.basename(selected.latest.path),
|
|
1556
|
+
size: selected.latest.stat.size,
|
|
1557
|
+
modifiedAt: selected.latest.stat.mtime.toISOString(),
|
|
1558
|
+
logs: parseValdiLog(content, limit),
|
|
1559
|
+
};
|
|
1560
|
+
}
|
|
1561
|
+
async function readRuntimeLogTail(logFile) {
|
|
1562
|
+
if (logFile.stat.size <= MAX_RUNTIME_LOG_READ_BYTES) {
|
|
1563
|
+
return {
|
|
1564
|
+
content: await promises_1.default.readFile(logFile.path, 'utf8'),
|
|
1565
|
+
startOffset: 0,
|
|
1566
|
+
};
|
|
1567
|
+
}
|
|
1568
|
+
const file = await promises_1.default.open(logFile.path, 'r');
|
|
1569
|
+
try {
|
|
1570
|
+
const buffer = Buffer.alloc(MAX_RUNTIME_LOG_READ_BYTES);
|
|
1571
|
+
const position = Math.max(0, logFile.stat.size - MAX_RUNTIME_LOG_READ_BYTES);
|
|
1572
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
|
|
1573
|
+
const tail = buffer.subarray(0, bytesRead);
|
|
1574
|
+
const firstLineBreak = tail.indexOf(10);
|
|
1575
|
+
if (firstLineBreak === -1)
|
|
1576
|
+
return { content: '', startOffset: position + bytesRead };
|
|
1577
|
+
return {
|
|
1578
|
+
content: tail.subarray(firstLineBreak + 1).toString('utf8'),
|
|
1579
|
+
startOffset: position + firstLineBreak + 1,
|
|
1580
|
+
};
|
|
1581
|
+
}
|
|
1582
|
+
finally {
|
|
1583
|
+
await file.close();
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
async function selectRuntimeLogFile(searchParams) {
|
|
1587
|
+
const applicationId = searchParams.get('applicationId');
|
|
1588
|
+
const platform = searchParams.get('platform');
|
|
1589
|
+
const logsDirectory = readValdiLogsDirectory();
|
|
1590
|
+
const logFiles = await collectLogFiles(logsDirectory);
|
|
1591
|
+
let latest;
|
|
1592
|
+
if (applicationId !== null && platform !== null) {
|
|
1593
|
+
latest = logFiles.find(file => node_path_1.default.basename(file.path) === `${platform}-${applicationId}.log`);
|
|
1594
|
+
}
|
|
1595
|
+
else if (applicationId !== null) {
|
|
1596
|
+
latest = logFiles.find(file => node_path_1.default.basename(file.path).endsWith(`-${applicationId}.log`));
|
|
1597
|
+
}
|
|
1598
|
+
else if (platform !== null) {
|
|
1599
|
+
latest = logFiles.find(file => node_path_1.default.basename(file.path).startsWith(`${platform}-`));
|
|
1600
|
+
}
|
|
1601
|
+
else if (logFiles.length === 1) {
|
|
1602
|
+
latest = logFiles[0];
|
|
1603
|
+
}
|
|
1604
|
+
return { logsDirectory, latest: latest ?? null };
|
|
1605
|
+
}
|
|
1606
|
+
class ConsoleSseWriter {
|
|
1607
|
+
response;
|
|
1608
|
+
onFailure;
|
|
1609
|
+
backpressured = false;
|
|
1610
|
+
bufferedBytes = 0;
|
|
1611
|
+
bufferedFrames = [];
|
|
1612
|
+
closed = false;
|
|
1613
|
+
constructor(response, onFailure) {
|
|
1614
|
+
this.response = response;
|
|
1615
|
+
this.onFailure = onFailure;
|
|
1616
|
+
}
|
|
1617
|
+
send(event, payload) {
|
|
1618
|
+
if (this.closed)
|
|
1619
|
+
return false;
|
|
1620
|
+
let data;
|
|
1621
|
+
try {
|
|
1622
|
+
data = JSON.stringify(payload);
|
|
1623
|
+
}
|
|
1624
|
+
catch {
|
|
1625
|
+
this.fail(new Error('Could not serialize a Chromium console event.'));
|
|
1626
|
+
return false;
|
|
1627
|
+
}
|
|
1628
|
+
if (data === undefined || !/^[a-z][a-z-]{0,63}$/.test(event)) {
|
|
1629
|
+
this.fail(new Error('Could not encode a Chromium console event.'));
|
|
1630
|
+
return false;
|
|
1631
|
+
}
|
|
1632
|
+
const frame = `event: ${event}\ndata: ${data}\n\n`;
|
|
1633
|
+
if (this.backpressured)
|
|
1634
|
+
return this.buffer(frame);
|
|
1635
|
+
return this.write(frame);
|
|
1636
|
+
}
|
|
1637
|
+
close() {
|
|
1638
|
+
if (this.closed)
|
|
1639
|
+
return;
|
|
1640
|
+
this.closed = true;
|
|
1641
|
+
this.response.off('drain', this.flush);
|
|
1642
|
+
this.bufferedFrames.length = 0;
|
|
1643
|
+
this.bufferedBytes = 0;
|
|
1644
|
+
}
|
|
1645
|
+
buffer(frame) {
|
|
1646
|
+
const frameBytes = Buffer.byteLength(frame);
|
|
1647
|
+
if (this.bufferedFrames.length >= exports.MAX_CONSOLE_SSE_BUFFERED_EVENTS ||
|
|
1648
|
+
frameBytes > exports.MAX_CONSOLE_SSE_BUFFERED_BYTES - this.bufferedBytes) {
|
|
1649
|
+
this.fail(new Error(`Chromium console stream exceeded its ${exports.MAX_CONSOLE_SSE_BUFFERED_EVENTS} event or ${exports.MAX_CONSOLE_SSE_BUFFERED_BYTES} byte backpressure limit.`));
|
|
1650
|
+
return false;
|
|
1651
|
+
}
|
|
1652
|
+
this.bufferedFrames.push(frame);
|
|
1653
|
+
this.bufferedBytes += frameBytes;
|
|
1654
|
+
return true;
|
|
1655
|
+
}
|
|
1656
|
+
flush = () => {
|
|
1657
|
+
if (this.closed)
|
|
1658
|
+
return;
|
|
1659
|
+
this.backpressured = false;
|
|
1660
|
+
while (this.bufferedFrames.length > 0) {
|
|
1661
|
+
const frame = this.bufferedFrames.shift();
|
|
1662
|
+
if (frame === undefined)
|
|
1663
|
+
return;
|
|
1664
|
+
this.bufferedBytes -= Buffer.byteLength(frame);
|
|
1665
|
+
if (!this.write(frame))
|
|
1666
|
+
return;
|
|
1667
|
+
if (this.backpressured)
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
};
|
|
1671
|
+
write(frame) {
|
|
1672
|
+
try {
|
|
1673
|
+
if (!this.response.write(frame)) {
|
|
1674
|
+
this.backpressured = true;
|
|
1675
|
+
this.response.once('drain', this.flush);
|
|
1676
|
+
}
|
|
1677
|
+
return true;
|
|
1678
|
+
}
|
|
1679
|
+
catch (error) {
|
|
1680
|
+
this.fail(error instanceof Error ? error : new Error('Could not write a Chromium console event.'));
|
|
1681
|
+
return false;
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
fail(error) {
|
|
1685
|
+
if (this.closed)
|
|
1686
|
+
return;
|
|
1687
|
+
this.close();
|
|
1688
|
+
this.onFailure(error);
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
exports.ConsoleSseWriter = ConsoleSseWriter;
|
|
1692
|
+
function sendSse(response, event, payload) {
|
|
1693
|
+
response.write(`event: ${event}\n`);
|
|
1694
|
+
response.write(`data: ${JSON.stringify(payload)}\n\n`);
|
|
1695
|
+
}
|
|
1696
|
+
function registerEventStreamLifetime(request, response, onClose) {
|
|
1697
|
+
let active = true;
|
|
1698
|
+
const detach = () => {
|
|
1699
|
+
if (!active)
|
|
1700
|
+
return;
|
|
1701
|
+
active = false;
|
|
1702
|
+
eventStreamClosers.delete(close);
|
|
1703
|
+
request.off('aborted', close);
|
|
1704
|
+
response.off('close', close);
|
|
1705
|
+
response.off('finish', close);
|
|
1706
|
+
};
|
|
1707
|
+
const close = () => {
|
|
1708
|
+
if (!active)
|
|
1709
|
+
return;
|
|
1710
|
+
detach();
|
|
1711
|
+
onClose();
|
|
1712
|
+
if (!response.writableEnded)
|
|
1713
|
+
response.end();
|
|
1714
|
+
};
|
|
1715
|
+
eventStreamClosers.add(close);
|
|
1716
|
+
request.once('aborted', close);
|
|
1717
|
+
response.once('close', close);
|
|
1718
|
+
response.once('finish', close);
|
|
1719
|
+
return { close, detach };
|
|
1720
|
+
}
|
|
1721
|
+
function registerEventStream(request, response, onClose) {
|
|
1722
|
+
return registerEventStreamLifetime(request, response, onClose).close;
|
|
1723
|
+
}
|
|
1724
|
+
function isTerminalChromiumConsoleEvent(method) {
|
|
1725
|
+
return (method === 'Inspector.detached' ||
|
|
1726
|
+
method === 'Runtime.executionContextsCleared' ||
|
|
1727
|
+
method === 'Target.detachedFromTarget');
|
|
1728
|
+
}
|
|
1729
|
+
async function streamWebPreviewConsole(request, response, searchParams) {
|
|
1730
|
+
const target = resolveWebPreviewDebuggerTarget(searchParams.get('sessionId') ?? undefined);
|
|
1731
|
+
const context = resolveInspectedWebPreviewContext(target, searchParams.get('inspectedUrl') ?? undefined, searchParams.get('targetNonce') ?? undefined);
|
|
1732
|
+
const recentEntries = new Map();
|
|
1733
|
+
const pendingEntries = [];
|
|
1734
|
+
let connection = null;
|
|
1735
|
+
let pendingDroppedEntryCount = 0;
|
|
1736
|
+
let sequence = 0;
|
|
1737
|
+
let setupFailure = null;
|
|
1738
|
+
let writer = null;
|
|
1739
|
+
let closeStream = NOOP;
|
|
1740
|
+
let removeEventListener = NOOP;
|
|
1741
|
+
let removeConnectionClose = NOOP;
|
|
1742
|
+
let identityTimer = null;
|
|
1743
|
+
let identityCheckInFlight = false;
|
|
1744
|
+
let closing = false;
|
|
1745
|
+
const closeWithError = (error) => {
|
|
1746
|
+
if (closing)
|
|
1747
|
+
return;
|
|
1748
|
+
if (!writer) {
|
|
1749
|
+
setupFailure ??= error;
|
|
1750
|
+
return;
|
|
1751
|
+
}
|
|
1752
|
+
writer.send('stream-error', {
|
|
1753
|
+
error: error.message,
|
|
1754
|
+
sessionId: target.sessionId,
|
|
1755
|
+
targetId: target.id,
|
|
1756
|
+
});
|
|
1757
|
+
closeStream();
|
|
1758
|
+
};
|
|
1759
|
+
const cleanup = () => {
|
|
1760
|
+
if (closing)
|
|
1761
|
+
return;
|
|
1762
|
+
closing = true;
|
|
1763
|
+
if (identityTimer)
|
|
1764
|
+
clearInterval(identityTimer);
|
|
1765
|
+
identityTimer = null;
|
|
1766
|
+
removeEventListener();
|
|
1767
|
+
removeConnectionClose();
|
|
1768
|
+
writer?.close();
|
|
1769
|
+
connection?.close();
|
|
1770
|
+
};
|
|
1771
|
+
const streamLifetime = registerEventStreamLifetime(request, response, cleanup);
|
|
1772
|
+
closeStream = streamLifetime.close;
|
|
1773
|
+
if (request.aborted || request.destroyed || response.destroyed || response.writableEnded) {
|
|
1774
|
+
closeStream();
|
|
1775
|
+
return;
|
|
1776
|
+
}
|
|
1777
|
+
const sendEntry = (entry) => {
|
|
1778
|
+
const key = `${entry.level}:${entry.message}`;
|
|
1779
|
+
const previous = recentEntries.get(key);
|
|
1780
|
+
if (previous !== undefined &&
|
|
1781
|
+
previous.source !== entry.source &&
|
|
1782
|
+
Math.abs(previous.timestamp - entry.timestamp) < CHROMIUM_CONSOLE_DEDUPLICATION_WINDOW_MS) {
|
|
1783
|
+
return;
|
|
1784
|
+
}
|
|
1785
|
+
recentEntries.delete(key);
|
|
1786
|
+
recentEntries.set(key, entry);
|
|
1787
|
+
if (recentEntries.size > MAX_PENDING_CHROMIUM_CONSOLE_ENTRIES) {
|
|
1788
|
+
const oldest = recentEntries.keys().next().value;
|
|
1789
|
+
if (oldest !== undefined)
|
|
1790
|
+
recentEntries.delete(oldest);
|
|
1791
|
+
}
|
|
1792
|
+
const payload = { ...entry, sequence: ++sequence };
|
|
1793
|
+
if (writer) {
|
|
1794
|
+
writer.send('console', {
|
|
1795
|
+
...payload,
|
|
1796
|
+
sessionId: target.sessionId,
|
|
1797
|
+
targetId: target.id,
|
|
1798
|
+
});
|
|
1799
|
+
return;
|
|
1800
|
+
}
|
|
1801
|
+
if (pendingEntries.length >= MAX_PENDING_CHROMIUM_CONSOLE_ENTRIES) {
|
|
1802
|
+
pendingEntries.shift();
|
|
1803
|
+
pendingDroppedEntryCount += 1;
|
|
1804
|
+
}
|
|
1805
|
+
pendingEntries.push(payload);
|
|
1806
|
+
};
|
|
1807
|
+
try {
|
|
1808
|
+
const connected = await (0, owlCdpClient_1.connectToOwlApplication)(target.debuggingPort, target.applicationUrl, context.targetNonce);
|
|
1809
|
+
connection = connected;
|
|
1810
|
+
if (closing) {
|
|
1811
|
+
connected.close();
|
|
1812
|
+
return;
|
|
1813
|
+
}
|
|
1814
|
+
removeConnectionClose = connected.onClose(error => closeWithError(error));
|
|
1815
|
+
if (setupFailure)
|
|
1816
|
+
throw setupFailure;
|
|
1817
|
+
removeEventListener = connected.onEvent(event => {
|
|
1818
|
+
if (isTerminalChromiumConsoleEvent(event.method)) {
|
|
1819
|
+
closeWithError(new Error('The inspected Chromium target changed or detached.'));
|
|
1820
|
+
return;
|
|
1821
|
+
}
|
|
1822
|
+
const entry = (0, chromiumConsole_1.formatChromiumConsoleEvent)(event);
|
|
1823
|
+
if (entry)
|
|
1824
|
+
sendEntry(entry);
|
|
1825
|
+
});
|
|
1826
|
+
await connected.call('Runtime.enable', {}, CHROMIUM_CONSOLE_COMMAND_TIMEOUT_MS);
|
|
1827
|
+
if (setupFailure)
|
|
1828
|
+
throw setupFailure;
|
|
1829
|
+
await connected.call('Log.enable', {}, CHROMIUM_CONSOLE_COMMAND_TIMEOUT_MS);
|
|
1830
|
+
if (setupFailure)
|
|
1831
|
+
throw setupFailure;
|
|
1832
|
+
if (!(await connected.matchesTarget(target.applicationUrl, context.targetNonce))) {
|
|
1833
|
+
throw new Error('The inspected Chromium target changed while the console stream was connecting.');
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
catch (error) {
|
|
1837
|
+
if (closing)
|
|
1838
|
+
return;
|
|
1839
|
+
streamLifetime.detach();
|
|
1840
|
+
cleanup();
|
|
1841
|
+
throw setupFailure ?? error;
|
|
1842
|
+
}
|
|
1843
|
+
if (request.aborted || request.destroyed || response.destroyed || response.writableEnded) {
|
|
1844
|
+
closeStream();
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
const activeConnection = connection;
|
|
1848
|
+
if (!activeConnection) {
|
|
1849
|
+
closeStream();
|
|
1850
|
+
return;
|
|
1851
|
+
}
|
|
1852
|
+
response.writeHead(200, {
|
|
1853
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
1854
|
+
'Cache-Control': 'no-store, no-transform',
|
|
1855
|
+
Connection: 'keep-alive',
|
|
1856
|
+
});
|
|
1857
|
+
writer = new ConsoleSseWriter(response, error => closeWithError(error));
|
|
1858
|
+
if (setupFailure) {
|
|
1859
|
+
closeWithError(setupFailure);
|
|
1860
|
+
return;
|
|
1861
|
+
}
|
|
1862
|
+
writer.send('ready', {
|
|
1863
|
+
sessionId: target.sessionId,
|
|
1864
|
+
targetId: target.id,
|
|
1865
|
+
time: new Date().toISOString(),
|
|
1866
|
+
});
|
|
1867
|
+
if (pendingDroppedEntryCount > 0) {
|
|
1868
|
+
writer.send('stream-warning', {
|
|
1869
|
+
droppedEntryCount: pendingDroppedEntryCount,
|
|
1870
|
+
message: 'Some buffered Chromium console entries were omitted while the stream connected.',
|
|
1871
|
+
sessionId: target.sessionId,
|
|
1872
|
+
targetId: target.id,
|
|
1873
|
+
});
|
|
1874
|
+
}
|
|
1875
|
+
for (const entry of pendingEntries) {
|
|
1876
|
+
writer.send('console', {
|
|
1877
|
+
...entry,
|
|
1878
|
+
sessionId: target.sessionId,
|
|
1879
|
+
targetId: target.id,
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
if (closing)
|
|
1883
|
+
return;
|
|
1884
|
+
identityTimer = setInterval(() => {
|
|
1885
|
+
if (closing || identityCheckInFlight)
|
|
1886
|
+
return;
|
|
1887
|
+
identityCheckInFlight = true;
|
|
1888
|
+
void activeConnection
|
|
1889
|
+
.matchesTarget(target.applicationUrl, context.targetNonce)
|
|
1890
|
+
.then(matched => {
|
|
1891
|
+
if (!matched) {
|
|
1892
|
+
closeWithError(new Error('The inspected Chromium target identity changed.'));
|
|
1893
|
+
return;
|
|
1894
|
+
}
|
|
1895
|
+
writer?.send('heartbeat', {
|
|
1896
|
+
sessionId: target.sessionId,
|
|
1897
|
+
targetId: target.id,
|
|
1898
|
+
time: new Date().toISOString(),
|
|
1899
|
+
});
|
|
1900
|
+
})
|
|
1901
|
+
.catch(error => closeWithError(error instanceof Error ? error : new Error('Could not revalidate the inspected Chromium target.')))
|
|
1902
|
+
.finally(() => {
|
|
1903
|
+
identityCheckInFlight = false;
|
|
1904
|
+
});
|
|
1905
|
+
}, CHROMIUM_CONSOLE_IDENTITY_INTERVAL_MS);
|
|
1906
|
+
identityTimer.unref();
|
|
1907
|
+
}
|
|
1908
|
+
function broadcastDevEvent(event, payload) {
|
|
1909
|
+
for (const response of devEventClients) {
|
|
1910
|
+
try {
|
|
1911
|
+
sendSse(response, event, payload);
|
|
1912
|
+
}
|
|
1913
|
+
catch {
|
|
1914
|
+
devEventClients.delete(response);
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
function scheduleDevReload(fileName) {
|
|
1919
|
+
if (devReloadTimer)
|
|
1920
|
+
clearTimeout(devReloadTimer);
|
|
1921
|
+
devReloadTimer = setTimeout(() => {
|
|
1922
|
+
devReloadTimer = null;
|
|
1923
|
+
devRevision += 1;
|
|
1924
|
+
broadcastDevEvent('reload', {
|
|
1925
|
+
revision: devRevision,
|
|
1926
|
+
file: fileName,
|
|
1927
|
+
time: new Date().toISOString(),
|
|
1928
|
+
});
|
|
1929
|
+
}, 75);
|
|
1930
|
+
}
|
|
1931
|
+
function streamDevEvents(request, response) {
|
|
1932
|
+
response.writeHead(200, {
|
|
1933
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
1934
|
+
'Cache-Control': 'no-store, no-transform',
|
|
1935
|
+
Connection: 'keep-alive',
|
|
1936
|
+
});
|
|
1937
|
+
response.write('\n');
|
|
1938
|
+
devEventClients.add(response);
|
|
1939
|
+
sendSse(response, 'ready', {
|
|
1940
|
+
revision: devRevision,
|
|
1941
|
+
time: new Date().toISOString(),
|
|
1942
|
+
});
|
|
1943
|
+
const heartbeat = setInterval(() => {
|
|
1944
|
+
try {
|
|
1945
|
+
sendSse(response, 'heartbeat', {
|
|
1946
|
+
revision: devRevision,
|
|
1947
|
+
time: new Date().toISOString(),
|
|
1948
|
+
});
|
|
1949
|
+
}
|
|
1950
|
+
catch {
|
|
1951
|
+
if (!response.writableEnded)
|
|
1952
|
+
response.end();
|
|
1953
|
+
}
|
|
1954
|
+
}, 15_000);
|
|
1955
|
+
registerEventStream(request, response, () => {
|
|
1956
|
+
devEventClients.delete(response);
|
|
1957
|
+
clearInterval(heartbeat);
|
|
1958
|
+
});
|
|
1959
|
+
}
|
|
1960
|
+
function cloneDebuggerActionRecord(record) {
|
|
1961
|
+
if (!record)
|
|
1962
|
+
return null;
|
|
1963
|
+
return {
|
|
1964
|
+
...record,
|
|
1965
|
+
params: { ...record.params },
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
function cloneDebuggerUiState() {
|
|
1969
|
+
return {
|
|
1970
|
+
...debuggerUiState,
|
|
1971
|
+
lastAction: cloneDebuggerActionRecord(debuggerUiState.lastAction),
|
|
1972
|
+
};
|
|
1973
|
+
}
|
|
1974
|
+
function debuggerStatePayload() {
|
|
1975
|
+
return {
|
|
1976
|
+
state: cloneDebuggerUiState(),
|
|
1977
|
+
capabilities: {
|
|
1978
|
+
actions: debuggerActions,
|
|
1979
|
+
},
|
|
1980
|
+
server: {
|
|
1981
|
+
host: activeHost,
|
|
1982
|
+
hotReloadProxyPort: HOT_RELOAD_PROXY_PORT,
|
|
1983
|
+
time: new Date().toISOString(),
|
|
1984
|
+
},
|
|
1985
|
+
};
|
|
1986
|
+
}
|
|
1987
|
+
function broadcastDebuggerEvent(event, payload) {
|
|
1988
|
+
for (const response of debuggerEventClients) {
|
|
1989
|
+
try {
|
|
1990
|
+
sendSse(response, event, payload);
|
|
1991
|
+
}
|
|
1992
|
+
catch {
|
|
1993
|
+
debuggerEventClients.delete(response);
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
function streamDebuggerEvents(request, response) {
|
|
1998
|
+
response.writeHead(200, {
|
|
1999
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
2000
|
+
'Cache-Control': 'no-store, no-transform',
|
|
2001
|
+
Connection: 'keep-alive',
|
|
2002
|
+
});
|
|
2003
|
+
response.write('\n');
|
|
2004
|
+
debuggerEventClients.add(response);
|
|
2005
|
+
sendSse(response, 'ready', debuggerStatePayload());
|
|
2006
|
+
const heartbeat = setInterval(() => {
|
|
2007
|
+
try {
|
|
2008
|
+
sendSse(response, 'heartbeat', debuggerStatePayload());
|
|
2009
|
+
}
|
|
2010
|
+
catch {
|
|
2011
|
+
if (!response.writableEnded)
|
|
2012
|
+
response.end();
|
|
2013
|
+
}
|
|
2014
|
+
}, 15_000);
|
|
2015
|
+
registerEventStream(request, response, () => {
|
|
2016
|
+
debuggerEventClients.delete(response);
|
|
2017
|
+
clearInterval(heartbeat);
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
function applyDebuggerUiAction(action, params, source) {
|
|
2021
|
+
const time = new Date().toISOString();
|
|
2022
|
+
const nextParams = { ...params };
|
|
2023
|
+
switch (action) {
|
|
2024
|
+
case 'selectNode': {
|
|
2025
|
+
const id = readRecordString(nextParams, 'id') ?? readRecordString(nextParams, 'nodeId');
|
|
2026
|
+
if (id !== undefined)
|
|
2027
|
+
debuggerUiState.selectedNodeId = id;
|
|
2028
|
+
break;
|
|
2029
|
+
}
|
|
2030
|
+
case 'selectTarget': {
|
|
2031
|
+
const id = readRecordString(nextParams, 'id') ?? readRecordString(nextParams, 'targetId');
|
|
2032
|
+
if (id !== undefined) {
|
|
2033
|
+
debuggerUiState.selectedTargetId = id;
|
|
2034
|
+
debuggerUiState.followLatestTarget = false;
|
|
2035
|
+
}
|
|
2036
|
+
break;
|
|
2037
|
+
}
|
|
2038
|
+
case 'setActiveTab': {
|
|
2039
|
+
const tab = readRecordString(nextParams, 'tab');
|
|
2040
|
+
if (tab !== undefined)
|
|
2041
|
+
debuggerUiState.activeTab = tab;
|
|
2042
|
+
break;
|
|
2043
|
+
}
|
|
2044
|
+
case 'setActiveSection': {
|
|
2045
|
+
const section = readRecordString(nextParams, 'section');
|
|
2046
|
+
if (section !== undefined) {
|
|
2047
|
+
const normalizedSection = normalizeDebuggerSection(section);
|
|
2048
|
+
nextParams['section'] = normalizedSection;
|
|
2049
|
+
debuggerUiState.activeSection = normalizedSection;
|
|
2050
|
+
}
|
|
2051
|
+
break;
|
|
2052
|
+
}
|
|
2053
|
+
case 'setOverlayMode': {
|
|
2054
|
+
const mode = readRecordString(nextParams, 'mode');
|
|
2055
|
+
if (mode !== undefined) {
|
|
2056
|
+
const normalizedMode = mode === 'views' || mode === 'components' ? 'live' : mode;
|
|
2057
|
+
nextParams['mode'] = normalizedMode;
|
|
2058
|
+
debuggerUiState.overlayMode = normalizedMode;
|
|
2059
|
+
}
|
|
2060
|
+
break;
|
|
2061
|
+
}
|
|
2062
|
+
case 'setAutoRefresh': {
|
|
2063
|
+
const enabled = readRecordBoolean(nextParams, 'enabled');
|
|
2064
|
+
if (enabled !== undefined)
|
|
2065
|
+
debuggerUiState.autoRefresh = enabled;
|
|
2066
|
+
break;
|
|
2067
|
+
}
|
|
2068
|
+
case 'setPort': {
|
|
2069
|
+
const port = readDebuggerPort(nextParams['port'], 'setPort port');
|
|
2070
|
+
debuggerUiState.port = port;
|
|
2071
|
+
break;
|
|
2072
|
+
}
|
|
2073
|
+
case 'attach': {
|
|
2074
|
+
debuggerUiState.followLatestTarget = true;
|
|
2075
|
+
break;
|
|
2076
|
+
}
|
|
2077
|
+
case 'detach': {
|
|
2078
|
+
debuggerUiState.followLatestTarget = false;
|
|
2079
|
+
break;
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
const record = {
|
|
2083
|
+
action,
|
|
2084
|
+
params: nextParams,
|
|
2085
|
+
source,
|
|
2086
|
+
time,
|
|
2087
|
+
};
|
|
2088
|
+
debuggerEventRevision += 1;
|
|
2089
|
+
debuggerUiState.revision = debuggerEventRevision;
|
|
2090
|
+
debuggerUiState.updatedAt = time;
|
|
2091
|
+
debuggerUiState.lastAction = record;
|
|
2092
|
+
return record;
|
|
2093
|
+
}
|
|
2094
|
+
async function handleDebuggerAction(request) {
|
|
2095
|
+
const body = await readJsonBody(request);
|
|
2096
|
+
const action = readDebuggerExactString(body, 'action', 128, false) ?? readDebuggerExactString(body, 'type', 128, false);
|
|
2097
|
+
if (action === undefined) {
|
|
2098
|
+
throw new ApiRequestError(400, 'Debugger action requests require an action.');
|
|
2099
|
+
}
|
|
2100
|
+
if (!debuggerActions.includes(action)) {
|
|
2101
|
+
throw new ApiRequestError(400, `Unknown debugger action '${action}'.`);
|
|
2102
|
+
}
|
|
2103
|
+
const params = readDebuggerBoundedRecord(body, 'params', 64, 128 * 1024);
|
|
2104
|
+
const source = readDebuggerExactString(body, 'source', 128, false) ?? 'agent';
|
|
2105
|
+
const result = await executeDebuggerRuntimeAction(action, params);
|
|
2106
|
+
const record = applyDebuggerUiAction(action, params, source);
|
|
2107
|
+
const payload = {
|
|
2108
|
+
...record,
|
|
2109
|
+
...(result === undefined ? {} : { result }),
|
|
2110
|
+
state: cloneDebuggerUiState(),
|
|
2111
|
+
};
|
|
2112
|
+
broadcastDebuggerEvent('debugger-action', payload);
|
|
2113
|
+
broadcastDebuggerEvent('debugger-state', debuggerStatePayload());
|
|
2114
|
+
return {
|
|
2115
|
+
ok: true,
|
|
2116
|
+
...payload,
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
async function executeDebuggerRuntimeAction(action, params) {
|
|
2120
|
+
if (action === 'refreshDebuggerProviders') {
|
|
2121
|
+
return await inspectDebuggerProviders(readDebuggerTargetSearchParams(params));
|
|
2122
|
+
}
|
|
2123
|
+
if (action === 'refreshDebugSettings') {
|
|
2124
|
+
return await inspectDebugSettings(readDebuggerTargetSearchParams(params), { action: 'list' });
|
|
2125
|
+
}
|
|
2126
|
+
if (action === 'setDebugSetting' || action === 'resetDebugSetting') {
|
|
2127
|
+
const searchParams = readDebuggerTargetSearchParams(params);
|
|
2128
|
+
const groupId = readDebuggerExactString(params, 'groupId', 128);
|
|
2129
|
+
const settingId = readDebuggerExactString(params, 'settingId', 128);
|
|
2130
|
+
return await inspectDebugSettings(searchParams, {
|
|
2131
|
+
action: action === 'setDebugSetting' ? 'set' : 'reset',
|
|
2132
|
+
groupId,
|
|
2133
|
+
settingId,
|
|
2134
|
+
...(action === 'setDebugSetting' ? { value: readDebuggerSettingValue(params['value']) } : {}),
|
|
2135
|
+
});
|
|
2136
|
+
}
|
|
2137
|
+
return undefined;
|
|
2138
|
+
}
|
|
2139
|
+
async function streamRuntimeLogs(request, response, searchParams) {
|
|
2140
|
+
const limit = clampNumber(readNumber(searchParams, 'limit', 120), 1, 1000);
|
|
2141
|
+
const sentKeyLimit = limit * 2;
|
|
2142
|
+
const sent = new Set();
|
|
2143
|
+
let closed = false;
|
|
2144
|
+
let polling = false;
|
|
2145
|
+
let lastLogPath = null;
|
|
2146
|
+
let lastLogInode = null;
|
|
2147
|
+
let lastLogModifiedMs = -1;
|
|
2148
|
+
let lastLogSize = -1;
|
|
2149
|
+
response.writeHead(200, {
|
|
2150
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
2151
|
+
'Cache-Control': 'no-store, no-transform',
|
|
2152
|
+
Connection: 'keep-alive',
|
|
2153
|
+
});
|
|
2154
|
+
response.write('\n');
|
|
2155
|
+
async function readAndSend() {
|
|
2156
|
+
if (closed)
|
|
2157
|
+
return;
|
|
2158
|
+
try {
|
|
2159
|
+
const selected = await selectRuntimeLogFile(searchParams);
|
|
2160
|
+
if (!selected.latest) {
|
|
2161
|
+
sendSse(response, 'meta', { logFile: null });
|
|
2162
|
+
return;
|
|
2163
|
+
}
|
|
2164
|
+
const logFileChanged = selected.latest.path !== lastLogPath || selected.latest.stat.ino !== lastLogInode;
|
|
2165
|
+
const logFileTruncated = !logFileChanged && lastLogSize >= 0 && selected.latest.stat.size < lastLogSize;
|
|
2166
|
+
if (logFileChanged || logFileTruncated) {
|
|
2167
|
+
sent.clear();
|
|
2168
|
+
lastLogPath = selected.latest.path;
|
|
2169
|
+
lastLogInode = selected.latest.stat.ino;
|
|
2170
|
+
lastLogModifiedMs = -1;
|
|
2171
|
+
lastLogSize = -1;
|
|
2172
|
+
sendSse(response, 'meta', {
|
|
2173
|
+
logFile: node_path_1.default.basename(selected.latest.path),
|
|
2174
|
+
size: selected.latest.stat.size,
|
|
2175
|
+
modifiedAt: selected.latest.stat.mtime.toISOString(),
|
|
2176
|
+
});
|
|
2177
|
+
}
|
|
2178
|
+
if (selected.latest.stat.mtimeMs === lastLogModifiedMs && selected.latest.stat.size === lastLogSize) {
|
|
2179
|
+
return;
|
|
2180
|
+
}
|
|
2181
|
+
lastLogModifiedMs = selected.latest.stat.mtimeMs;
|
|
2182
|
+
lastLogSize = selected.latest.stat.size;
|
|
2183
|
+
const tail = await readRuntimeLogTail(selected.latest);
|
|
2184
|
+
const parseLimit = sent.size > 0 ? Number.MAX_SAFE_INTEGER : limit;
|
|
2185
|
+
const records = parseValdiLogRecords(tail.content, parseLimit, tail.startOffset);
|
|
2186
|
+
const nextLogs = [];
|
|
2187
|
+
for (const record of records) {
|
|
2188
|
+
const key = `${selected.latest.stat.ino}:${record.offset}`;
|
|
2189
|
+
if (sent.has(key))
|
|
2190
|
+
continue;
|
|
2191
|
+
sent.add(key);
|
|
2192
|
+
nextLogs.push(record.entry);
|
|
2193
|
+
}
|
|
2194
|
+
while (sent.size > sentKeyLimit) {
|
|
2195
|
+
const oldestKey = sent.values().next().value;
|
|
2196
|
+
if (oldestKey === undefined)
|
|
2197
|
+
break;
|
|
2198
|
+
sent.delete(oldestKey);
|
|
2199
|
+
}
|
|
2200
|
+
if (nextLogs.length > 0)
|
|
2201
|
+
sendSse(response, 'logs', { logs: nextLogs });
|
|
2202
|
+
}
|
|
2203
|
+
catch (error) {
|
|
2204
|
+
try {
|
|
2205
|
+
sendSse(response, 'stream-error', clientErrorPayload(error));
|
|
2206
|
+
}
|
|
2207
|
+
catch {
|
|
2208
|
+
if (!response.writableEnded)
|
|
2209
|
+
response.end();
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
async function poll() {
|
|
2214
|
+
if (closed || polling)
|
|
2215
|
+
return;
|
|
2216
|
+
polling = true;
|
|
2217
|
+
try {
|
|
2218
|
+
await readAndSend();
|
|
2219
|
+
}
|
|
2220
|
+
finally {
|
|
2221
|
+
polling = false;
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
const poller = setInterval(() => {
|
|
2225
|
+
void poll();
|
|
2226
|
+
}, 1000);
|
|
2227
|
+
const heartbeat = setInterval(() => {
|
|
2228
|
+
if (!closed)
|
|
2229
|
+
sendSse(response, 'heartbeat', { time: new Date().toISOString() });
|
|
2230
|
+
}, 15_000);
|
|
2231
|
+
registerEventStream(request, response, () => {
|
|
2232
|
+
closed = true;
|
|
2233
|
+
clearInterval(poller);
|
|
2234
|
+
clearInterval(heartbeat);
|
|
2235
|
+
});
|
|
2236
|
+
await poll();
|
|
2237
|
+
}
|
|
2238
|
+
async function withConnection(port, callback) {
|
|
2239
|
+
const conn = await (0, daemonClient_1.connectToDaemon)(port);
|
|
2240
|
+
try {
|
|
2241
|
+
await conn.configure();
|
|
2242
|
+
return await callback(conn);
|
|
2243
|
+
}
|
|
2244
|
+
finally {
|
|
2245
|
+
conn.close();
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
async function withDaemonEndpointConnection(endpoint, configureTimeoutMs, callback) {
|
|
2249
|
+
const conn = await (0, daemonClient_1.connectToDaemon)(endpoint);
|
|
2250
|
+
try {
|
|
2251
|
+
await conn.configureWithTimeout(configureTimeoutMs);
|
|
2252
|
+
return await callback(conn);
|
|
2253
|
+
}
|
|
2254
|
+
finally {
|
|
2255
|
+
conn.close();
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
async function collectClientContexts(conn, clients, knownClientId, knownContexts) {
|
|
2259
|
+
const clientsWithContexts = [];
|
|
2260
|
+
for (const client of clients) {
|
|
2261
|
+
let contexts = [];
|
|
2262
|
+
let contextError = null;
|
|
2263
|
+
if (client.client_id === knownClientId && knownContexts !== null) {
|
|
2264
|
+
contexts = knownContexts;
|
|
2265
|
+
}
|
|
2266
|
+
else {
|
|
2267
|
+
try {
|
|
2268
|
+
contexts = await conn.listContexts(client.client_id);
|
|
2269
|
+
}
|
|
2270
|
+
catch (error) {
|
|
2271
|
+
contextError = clientErrorPayload(error).error;
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
clientsWithContexts.push({
|
|
2275
|
+
...client,
|
|
2276
|
+
contexts,
|
|
2277
|
+
contextError,
|
|
2278
|
+
});
|
|
2279
|
+
}
|
|
2280
|
+
return clientsWithContexts;
|
|
2281
|
+
}
|
|
2282
|
+
async function inspectPort(port) {
|
|
2283
|
+
try {
|
|
2284
|
+
return await withConnection(port, async (conn) => {
|
|
2285
|
+
const clients = await conn.listConnectedClients();
|
|
2286
|
+
const clientsWithContexts = await collectClientContexts(conn, clients, null, null);
|
|
2287
|
+
return {
|
|
2288
|
+
port,
|
|
2289
|
+
portName: portName(port),
|
|
2290
|
+
connected: true,
|
|
2291
|
+
clients: clientsWithContexts,
|
|
2292
|
+
error: null,
|
|
2293
|
+
};
|
|
2294
|
+
});
|
|
2295
|
+
}
|
|
2296
|
+
catch (error) {
|
|
2297
|
+
return {
|
|
2298
|
+
port,
|
|
2299
|
+
portName: portName(port),
|
|
2300
|
+
connected: false,
|
|
2301
|
+
clients: [],
|
|
2302
|
+
error: clientErrorPayload(error).error,
|
|
2303
|
+
};
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
async function inspectDebuggerEndpoint(endpoint) {
|
|
2307
|
+
try {
|
|
2308
|
+
return await withDaemonEndpointConnection(endpoint, DAEMON_DISCOVERY_CONFIGURE_TIMEOUT_MS, async (conn) => {
|
|
2309
|
+
const clients = await conn.listConnectedClients();
|
|
2310
|
+
if (clients.length > MAX_DISCOVERY_CLIENTS_PER_ENDPOINT) {
|
|
2311
|
+
throw new Error(`Valdi daemon target discovery exceeded ${MAX_DISCOVERY_CLIENTS_PER_ENDPOINT.toString()} clients.`);
|
|
2312
|
+
}
|
|
2313
|
+
const clientsWithContexts = await Promise.all(clients.map(async (client) => {
|
|
2314
|
+
const contexts = await conn.listContextsWithTimeout(client.client_id, DAEMON_DISCOVERY_CONFIGURE_TIMEOUT_MS);
|
|
2315
|
+
if (contexts.length > MAX_DISCOVERY_CONTEXTS_PER_CLIENT) {
|
|
2316
|
+
throw new Error(`Valdi daemon target discovery exceeded ${MAX_DISCOVERY_CONTEXTS_PER_CLIENT.toString()} contexts for one client.`);
|
|
2317
|
+
}
|
|
2318
|
+
return { ...client, contexts, contextError: null };
|
|
2319
|
+
}));
|
|
2320
|
+
return {
|
|
2321
|
+
port: endpoint.port,
|
|
2322
|
+
portName: portName(endpoint.port),
|
|
2323
|
+
connected: true,
|
|
2324
|
+
clients: clientsWithContexts,
|
|
2325
|
+
...(endpoint.deviceId === undefined ? {} : { deviceId: endpoint.deviceId }),
|
|
2326
|
+
error: null,
|
|
2327
|
+
};
|
|
2328
|
+
});
|
|
2329
|
+
}
|
|
2330
|
+
catch (error) {
|
|
2331
|
+
return {
|
|
2332
|
+
port: endpoint.port,
|
|
2333
|
+
portName: portName(endpoint.port),
|
|
2334
|
+
connected: false,
|
|
2335
|
+
clients: [],
|
|
2336
|
+
...(endpoint.deviceId === undefined ? {} : { deviceId: endpoint.deviceId }),
|
|
2337
|
+
error: clientErrorPayload(error).error,
|
|
2338
|
+
};
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
function debuggerDaemonEndpoints(android) {
|
|
2342
|
+
const endpointsByPort = new Map();
|
|
2343
|
+
for (const endpoint of android.endpoints) {
|
|
2344
|
+
const existing = endpointsByPort.get(endpoint.port);
|
|
2345
|
+
if (existing && existing.deviceId !== endpoint.deviceId) {
|
|
2346
|
+
throw new Error('Android debugger discovery returned an ambiguous local daemon port.');
|
|
2347
|
+
}
|
|
2348
|
+
endpointsByPort.set(endpoint.port, {
|
|
2349
|
+
autoForward: false,
|
|
2350
|
+
...(endpoint.deviceId === undefined ? {} : { deviceId: endpoint.deviceId }),
|
|
2351
|
+
port: endpoint.port,
|
|
2352
|
+
});
|
|
2353
|
+
}
|
|
2354
|
+
for (const endpoint of activeDebuggerTargetDiscovery.defaultDaemonEndpoints) {
|
|
2355
|
+
if (endpointsByPort.has(endpoint.port))
|
|
2356
|
+
continue;
|
|
2357
|
+
endpointsByPort.set(endpoint.port, {
|
|
2358
|
+
...endpoint,
|
|
2359
|
+
autoForward: false,
|
|
2360
|
+
});
|
|
2361
|
+
}
|
|
2362
|
+
const endpoints = [...endpointsByPort.values()];
|
|
2363
|
+
if (endpoints.length > MAX_DISCOVERY_DAEMON_ENDPOINTS) {
|
|
2364
|
+
throw new Error(`Debugger discovery exceeded ${MAX_DISCOVERY_DAEMON_ENDPOINTS.toString()} daemon endpoints.`);
|
|
2365
|
+
}
|
|
2366
|
+
return endpoints;
|
|
2367
|
+
}
|
|
2368
|
+
async function inspectDebuggerEndpoints(endpoints) {
|
|
2369
|
+
const results = new Map();
|
|
2370
|
+
let nextIndex = 0;
|
|
2371
|
+
const workerCount = Math.min(MAX_CONCURRENT_DAEMON_DISCOVERIES, endpoints.length);
|
|
2372
|
+
const workers = Array.from({ length: workerCount }, async () => {
|
|
2373
|
+
while (nextIndex < endpoints.length) {
|
|
2374
|
+
const index = nextIndex;
|
|
2375
|
+
nextIndex += 1;
|
|
2376
|
+
const endpoint = endpoints[index];
|
|
2377
|
+
if (!endpoint)
|
|
2378
|
+
throw new Error('Debugger endpoint discovery lost an indexed endpoint.');
|
|
2379
|
+
results.set(index, await inspectDebuggerEndpoint(endpoint));
|
|
2380
|
+
}
|
|
2381
|
+
});
|
|
2382
|
+
await Promise.all(workers);
|
|
2383
|
+
return endpoints.map((_endpoint, index) => {
|
|
2384
|
+
const result = results.get(index);
|
|
2385
|
+
if (!result)
|
|
2386
|
+
throw new Error('Debugger endpoint discovery did not inspect every bounded endpoint.');
|
|
2387
|
+
return result;
|
|
2388
|
+
});
|
|
2389
|
+
}
|
|
2390
|
+
async function discoverDebuggerTargets() {
|
|
2391
|
+
const [android, proxyConnected] = await Promise.all([
|
|
2392
|
+
activeDebuggerTargetDiscovery.discoverAndroidDaemonEndpoints(),
|
|
2393
|
+
activeDebuggerTargetDiscovery.probeDebuggerProxy(HOT_RELOAD_PROXY_PORT),
|
|
2394
|
+
]);
|
|
2395
|
+
const endpoints = debuggerDaemonEndpoints(android);
|
|
2396
|
+
const ports = await inspectDebuggerEndpoints(endpoints);
|
|
2397
|
+
let proxyTargets = [];
|
|
2398
|
+
let proxyError = null;
|
|
2399
|
+
if (proxyConnected) {
|
|
2400
|
+
try {
|
|
2401
|
+
proxyTargets = await activeDebuggerTargetDiscovery.discoverDebuggerProxyTargets(HOT_RELOAD_PROXY_PORT);
|
|
2402
|
+
}
|
|
2403
|
+
catch (error) {
|
|
2404
|
+
proxyError = clientErrorPayload(error).error;
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
const targets = (0, targetRegistry_1.buildDebuggerTargetRegistry)({
|
|
2408
|
+
ports,
|
|
2409
|
+
proxyTargets,
|
|
2410
|
+
webPreviewTargets: activeWebPreviewTarget ? [webPreviewTargetPayload(activeWebPreviewTarget)] : [],
|
|
2411
|
+
});
|
|
2412
|
+
return { android, ports, proxyConnected, proxyError, proxyTargets, targets };
|
|
2413
|
+
}
|
|
2414
|
+
async function inspectStatus(searchParams) {
|
|
2415
|
+
const explicitPort = searchParams.get('port');
|
|
2416
|
+
const ports = explicitPort ? [readNumber(searchParams, 'port', defaultServicePort())] : discoveryServicePorts();
|
|
2417
|
+
const results = [];
|
|
2418
|
+
for (const port of ports) {
|
|
2419
|
+
results.push(await inspectPort(port));
|
|
2420
|
+
}
|
|
2421
|
+
return {
|
|
2422
|
+
ports: results,
|
|
2423
|
+
hotReloadProxy: {
|
|
2424
|
+
port: HOT_RELOAD_PROXY_PORT,
|
|
2425
|
+
connected: await probeTcpPort(HOT_RELOAD_PROXY_PORT, 750),
|
|
2426
|
+
},
|
|
2427
|
+
defaultPort: defaultServicePort(),
|
|
2428
|
+
webPreviewTarget: activeWebPreviewTarget ? legacyWebPreviewTargetPayload(activeWebPreviewTarget) : null,
|
|
2429
|
+
};
|
|
2430
|
+
}
|
|
2431
|
+
async function inspectDebuggerTargets() {
|
|
2432
|
+
const discovery = await discoverDebuggerTargets();
|
|
2433
|
+
const payload = {
|
|
2434
|
+
discovery: {
|
|
2435
|
+
android: { error: discovery.android.error, tunnelCount: discovery.android.endpoints.length },
|
|
2436
|
+
proxy: { error: discovery.proxyError, targetCount: discovery.proxyTargets.length },
|
|
2437
|
+
},
|
|
2438
|
+
targets: discovery.targets,
|
|
2439
|
+
};
|
|
2440
|
+
if (Buffer.byteLength(JSON.stringify(payload), 'utf8') > MAX_DEVTOOLS_TARGETS_RESPONSE_BYTES) {
|
|
2441
|
+
throw new Error(`Valdi DevTools target registry response exceeded ${MAX_DEVTOOLS_TARGETS_RESPONSE_BYTES} bytes.`);
|
|
2442
|
+
}
|
|
2443
|
+
return payload;
|
|
2444
|
+
}
|
|
2445
|
+
async function resolveCurrentDebuggerTarget(targetId) {
|
|
2446
|
+
const discovery = await discoverDebuggerTargets();
|
|
2447
|
+
const matches = discovery.targets.filter(target => target.id === targetId);
|
|
2448
|
+
if (matches.length === 0) {
|
|
2449
|
+
throw new ApiRequestError(404, 'The selected Valdi debugger target is no longer available.');
|
|
2450
|
+
}
|
|
2451
|
+
if (matches.length !== 1) {
|
|
2452
|
+
throw new ApiRequestError(409, 'Valdi debugger target discovery returned an ambiguous target identity.');
|
|
2453
|
+
}
|
|
2454
|
+
const target = matches[0];
|
|
2455
|
+
if (!target)
|
|
2456
|
+
throw new ApiRequestError(404, 'The selected Valdi debugger target is no longer available.');
|
|
2457
|
+
if (target.identityMode !== targetRegistry_1.DebuggerTargetIdentityMode.TargetId ||
|
|
2458
|
+
!target.attachable ||
|
|
2459
|
+
target.transport !== targetRegistry_1.DebuggerTargetTransport.ValdiDaemon) {
|
|
2460
|
+
throw new ApiRequestError(400, 'The selected debugger target cannot be attached by target ID.');
|
|
2461
|
+
}
|
|
2462
|
+
return target;
|
|
2463
|
+
}
|
|
2464
|
+
async function resolveInspectedDebuggerTarget(searchParams) {
|
|
2465
|
+
const targetIdValues = searchParams.getAll('targetId');
|
|
2466
|
+
if (targetIdValues.length > 0) {
|
|
2467
|
+
rejectDebuggerIdentityParameters(searchParams, [
|
|
2468
|
+
'sessionId',
|
|
2469
|
+
'inspectedUrl',
|
|
2470
|
+
'targetNonce',
|
|
2471
|
+
'port',
|
|
2472
|
+
'clientId',
|
|
2473
|
+
'contextId',
|
|
2474
|
+
]);
|
|
2475
|
+
const targetId = readExactDebuggerParameter(searchParams, 'targetId');
|
|
2476
|
+
return { target: await resolveCurrentDebuggerTarget(targetId) };
|
|
2477
|
+
}
|
|
2478
|
+
return resolveInspectedWebPreviewTarget(searchParams);
|
|
2479
|
+
}
|
|
2480
|
+
async function inspectNativeDebuggerSnapshot(target) {
|
|
2481
|
+
if (target.transport !== targetRegistry_1.DebuggerTargetTransport.ValdiDaemon ||
|
|
2482
|
+
target.port === undefined ||
|
|
2483
|
+
target.clientId === undefined ||
|
|
2484
|
+
target.contextId === undefined) {
|
|
2485
|
+
throw new ApiRequestError(400, 'The selected target does not expose a live native Valdi component tree.');
|
|
2486
|
+
}
|
|
2487
|
+
const port = target.port;
|
|
2488
|
+
const clientId = target.clientId;
|
|
2489
|
+
const contextId = target.contextId;
|
|
2490
|
+
const endpoint = {
|
|
2491
|
+
autoForward: false,
|
|
2492
|
+
...(target.deviceId === undefined ? {} : { deviceId: target.deviceId }),
|
|
2493
|
+
port,
|
|
2494
|
+
};
|
|
2495
|
+
return await withDaemonEndpointConnection(endpoint, DAEMON_DISCOVERY_CONFIGURE_TIMEOUT_MS, async (conn) => {
|
|
2496
|
+
const clients = await conn.listConnectedClients();
|
|
2497
|
+
const client = clients.find(candidate => candidate.client_id === clientId);
|
|
2498
|
+
if (!client || client.application_id !== target.applicationId) {
|
|
2499
|
+
throw new ApiRequestError(404, 'The selected Valdi debugger target changed or disconnected.');
|
|
2500
|
+
}
|
|
2501
|
+
const contexts = await conn.listContexts(client.client_id);
|
|
2502
|
+
const context = contexts.find(candidate => candidate.id === contextId);
|
|
2503
|
+
if (!context) {
|
|
2504
|
+
throw new ApiRequestError(404, 'The selected Valdi debugger target changed or disconnected.');
|
|
2505
|
+
}
|
|
2506
|
+
const currentTarget = (0, targetRegistry_1.buildDebuggerTargetRegistry)({
|
|
2507
|
+
ports: [
|
|
2508
|
+
{
|
|
2509
|
+
clients: [{ ...client, contexts: [context], contextError: null }],
|
|
2510
|
+
connected: true,
|
|
2511
|
+
...(target.deviceId === undefined ? {} : { deviceId: target.deviceId }),
|
|
2512
|
+
error: null,
|
|
2513
|
+
port,
|
|
2514
|
+
portName: portName(port),
|
|
2515
|
+
},
|
|
2516
|
+
],
|
|
2517
|
+
proxyTargets: [],
|
|
2518
|
+
webPreviewTargets: [],
|
|
2519
|
+
})[0];
|
|
2520
|
+
if (!currentTarget || currentTarget.id !== target.id) {
|
|
2521
|
+
throw new ApiRequestError(404, 'The selected Valdi debugger target changed or disconnected.');
|
|
2522
|
+
}
|
|
2523
|
+
const tree = await conn.getContextTree(client.client_id, context.id, true);
|
|
2524
|
+
return {
|
|
2525
|
+
contexts: [target],
|
|
2526
|
+
issues: [],
|
|
2527
|
+
logs: [],
|
|
2528
|
+
source: 'valdi-daemon',
|
|
2529
|
+
target: { ...target, state: targetRegistry_1.DebuggerTargetState.Attached },
|
|
2530
|
+
targets: [target],
|
|
2531
|
+
tree: projectDebuggerTreeForJson(tree),
|
|
2532
|
+
};
|
|
2533
|
+
});
|
|
2534
|
+
}
|
|
2535
|
+
async function inspectDevToolsSnapshot(searchParams) {
|
|
2536
|
+
if (searchParams.getAll('targetId').length === 0)
|
|
2537
|
+
return await inspectWebPreviewSnapshot(searchParams);
|
|
2538
|
+
rejectDebuggerIdentityParameters(searchParams, [
|
|
2539
|
+
'sessionId',
|
|
2540
|
+
'inspectedUrl',
|
|
2541
|
+
'targetNonce',
|
|
2542
|
+
'port',
|
|
2543
|
+
'clientId',
|
|
2544
|
+
'contextId',
|
|
2545
|
+
]);
|
|
2546
|
+
const targetId = readExactDebuggerParameter(searchParams, 'targetId');
|
|
2547
|
+
return await inspectNativeDebuggerSnapshot(await resolveCurrentDebuggerTarget(targetId));
|
|
2548
|
+
}
|
|
2549
|
+
async function resolveTarget(searchParams, conn) {
|
|
2550
|
+
const { clients, client } = await resolveClient(searchParams, conn);
|
|
2551
|
+
const contexts = await conn.listContexts(client.client_id);
|
|
2552
|
+
if (contexts.length === 0) {
|
|
2553
|
+
throw new Error(`No Valdi contexts found for client ${client.client_id}.`);
|
|
2554
|
+
}
|
|
2555
|
+
const requestedContextId = searchParams.get('contextId');
|
|
2556
|
+
const lastContext = contexts.at(-1);
|
|
2557
|
+
if (!lastContext) {
|
|
2558
|
+
throw new Error(`No Valdi contexts found for client ${client.client_id}.`);
|
|
2559
|
+
}
|
|
2560
|
+
let context = lastContext;
|
|
2561
|
+
if (requestedContextId !== null) {
|
|
2562
|
+
const requestedContext = contexts.find(candidate => candidate.id === requestedContextId);
|
|
2563
|
+
if (!requestedContext) {
|
|
2564
|
+
throw new Error(`Client ${client.client_id} has no Valdi context with id ${requestedContextId}.`);
|
|
2565
|
+
}
|
|
2566
|
+
context = requestedContext;
|
|
2567
|
+
}
|
|
2568
|
+
return { clients, client, contexts, context };
|
|
2569
|
+
}
|
|
2570
|
+
async function resolveClient(searchParams, conn) {
|
|
2571
|
+
const clients = await conn.listConnectedClients();
|
|
2572
|
+
if (clients.length === 0) {
|
|
2573
|
+
throw new Error('No clients connected to this Valdi daemon.');
|
|
2574
|
+
}
|
|
2575
|
+
const requestedClientId = searchParams.get('clientId');
|
|
2576
|
+
const firstClient = clients[0];
|
|
2577
|
+
if (!firstClient) {
|
|
2578
|
+
throw new Error('No clients connected to this Valdi daemon.');
|
|
2579
|
+
}
|
|
2580
|
+
let client = firstClient;
|
|
2581
|
+
if (requestedClientId !== null) {
|
|
2582
|
+
const requestedClient = clients.find(candidate => candidate.client_id === requestedClientId);
|
|
2583
|
+
if (!requestedClient) {
|
|
2584
|
+
throw new Error(`No connected Valdi client has id ${requestedClientId}.`);
|
|
2585
|
+
}
|
|
2586
|
+
client = requestedClient;
|
|
2587
|
+
}
|
|
2588
|
+
return { clients, client };
|
|
2589
|
+
}
|
|
2590
|
+
function createDaemonTargetPayload(port, client, context) {
|
|
2591
|
+
return {
|
|
2592
|
+
id: `${port}:${client.client_id}:${context.id}`,
|
|
2593
|
+
name: context.rootComponentName || client.application_id || `Client ${client.client_id}`,
|
|
2594
|
+
platform: client.platform || portName(port),
|
|
2595
|
+
transport: `daemon:${port}`,
|
|
2596
|
+
state: 'attached',
|
|
2597
|
+
proxyPort: port,
|
|
2598
|
+
port,
|
|
2599
|
+
clientId: client.client_id,
|
|
2600
|
+
contextId: context.id,
|
|
2601
|
+
applicationId: client.application_id,
|
|
2602
|
+
};
|
|
2603
|
+
}
|
|
2604
|
+
async function sendTargetCustomRequest(searchParams, identifier, data, timeoutMs) {
|
|
2605
|
+
const validatedSearchParams = validateDebuggerSearchParams(searchParams);
|
|
2606
|
+
const port = Number(validatedSearchParams.get('port'));
|
|
2607
|
+
try {
|
|
2608
|
+
return await withConnection(port, async (conn) => {
|
|
2609
|
+
const { client, context } = await resolveTarget(validatedSearchParams, conn);
|
|
2610
|
+
const target = createDaemonTargetPayload(port, client, context);
|
|
2611
|
+
const customBody = await conn.customRequest(client.client_id, identifier, { ...data, contextId: context.id }, timeoutMs);
|
|
2612
|
+
const handled = customBody.handled;
|
|
2613
|
+
return {
|
|
2614
|
+
handled,
|
|
2615
|
+
identifier,
|
|
2616
|
+
status: handled ? 'handled' : 'unsupported',
|
|
2617
|
+
target,
|
|
2618
|
+
data: customBody.data ?? {},
|
|
2619
|
+
error: null,
|
|
2620
|
+
message: handled ? null : `The target runtime did not handle ${identifier}.`,
|
|
2621
|
+
};
|
|
2622
|
+
});
|
|
2623
|
+
}
|
|
2624
|
+
catch (error) {
|
|
2625
|
+
const payload = clientErrorPayload(error);
|
|
2626
|
+
return {
|
|
2627
|
+
handled: false,
|
|
2628
|
+
identifier,
|
|
2629
|
+
status: error instanceof daemonClient_1.DaemonProtocolError ? 'protocol-error' : 'unavailable',
|
|
2630
|
+
target: null,
|
|
2631
|
+
data: {},
|
|
2632
|
+
error: payload.error,
|
|
2633
|
+
message: payload.error,
|
|
2634
|
+
};
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
async function inspectDebuggerProviders(searchParams) {
|
|
2638
|
+
return await sendTargetCustomRequest(searchParams, DEBUGGER_PROVIDERS_IDENTIFIER, { action: 'list' }, 5000);
|
|
2639
|
+
}
|
|
2640
|
+
async function requestDebuggerProvider(request, searchParams) {
|
|
2641
|
+
if (request.method !== 'POST')
|
|
2642
|
+
throw new ApiRequestError(405, 'Debugger provider requests require POST.');
|
|
2643
|
+
const body = await readJsonBody(request);
|
|
2644
|
+
const providerId = readDebuggerExactString(body, 'providerId', 128);
|
|
2645
|
+
const action = readDebuggerExactString(body, 'action', 128);
|
|
2646
|
+
const params = readDebuggerBoundedRecord(body, 'params', 32, 64 * 1024);
|
|
2647
|
+
return await sendTargetCustomRequest(searchParams, DEBUGGER_PROVIDERS_IDENTIFIER, {
|
|
2648
|
+
action: 'request',
|
|
2649
|
+
providerId,
|
|
2650
|
+
request: { ...params, action },
|
|
2651
|
+
}, 10_000);
|
|
2652
|
+
}
|
|
2653
|
+
async function inspectDebugSettings(searchParams, data) {
|
|
2654
|
+
return await sendTargetCustomRequest(searchParams, DEBUG_SETTINGS_IDENTIFIER, data, 5000);
|
|
2655
|
+
}
|
|
2656
|
+
async function handleDebugSettings(request, searchParams) {
|
|
2657
|
+
if (request.method === 'GET')
|
|
2658
|
+
return await inspectDebugSettings(searchParams, { action: 'list' });
|
|
2659
|
+
if (request.method !== 'POST')
|
|
2660
|
+
throw new ApiRequestError(405, 'Debug settings support GET and POST only.');
|
|
2661
|
+
const body = await readJsonBody(request);
|
|
2662
|
+
const action = readDebuggerExactString(body, 'action', 16);
|
|
2663
|
+
if (action !== 'set' && action !== 'reset') {
|
|
2664
|
+
throw new ApiRequestError(400, "Debug settings action must be 'set' or 'reset'.");
|
|
2665
|
+
}
|
|
2666
|
+
const groupId = readDebuggerExactString(body, 'groupId', 128);
|
|
2667
|
+
const settingId = readDebuggerExactString(body, 'settingId', 128);
|
|
2668
|
+
return await inspectDebugSettings(searchParams, {
|
|
2669
|
+
action,
|
|
2670
|
+
groupId,
|
|
2671
|
+
settingId,
|
|
2672
|
+
...(action === 'set' ? { value: readDebuggerSettingValue(body['value']) } : {}),
|
|
2673
|
+
});
|
|
2674
|
+
}
|
|
2675
|
+
function flattenTargets(port, clients, selectedClientId, selectedContextId) {
|
|
2676
|
+
const targets = [];
|
|
2677
|
+
for (const client of clients) {
|
|
2678
|
+
for (const context of client.contexts || []) {
|
|
2679
|
+
const selected = client.client_id === selectedClientId && context.id === selectedContextId;
|
|
2680
|
+
targets.push({
|
|
2681
|
+
id: `${port}:${client.client_id}:${context.id}`,
|
|
2682
|
+
name: context.rootComponentName || client.application_id || `Client ${client.client_id}`,
|
|
2683
|
+
platform: client.platform || portName(port),
|
|
2684
|
+
state: selected ? 'attached' : 'available',
|
|
2685
|
+
transport: `daemon:${port}`,
|
|
2686
|
+
port,
|
|
2687
|
+
clientId: client.client_id,
|
|
2688
|
+
contextId: context.id,
|
|
2689
|
+
applicationId: client.application_id,
|
|
2690
|
+
});
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
return targets;
|
|
2694
|
+
}
|
|
2695
|
+
async function inspectSnapshot(searchParams) {
|
|
2696
|
+
const port = readNumber(searchParams, 'port', defaultServicePort());
|
|
2697
|
+
return await withConnection(port, async (conn) => {
|
|
2698
|
+
const { clients, client, contexts, context } = await resolveTarget(searchParams, conn);
|
|
2699
|
+
const tree = await conn.getContextTree(client.client_id, context.id, true);
|
|
2700
|
+
const clientsWithContexts = await collectClientContexts(conn, clients, client.client_id, contexts);
|
|
2701
|
+
const targets = flattenTargets(port, clientsWithContexts, client.client_id, context.id);
|
|
2702
|
+
return {
|
|
2703
|
+
source: 'valdi-daemon',
|
|
2704
|
+
target: {
|
|
2705
|
+
id: `${port}:${client.client_id}:${context.id}`,
|
|
2706
|
+
name: context.rootComponentName || client.application_id || `Client ${client.client_id}`,
|
|
2707
|
+
platform: client.platform || portName(port),
|
|
2708
|
+
transport: `daemon:${port}`,
|
|
2709
|
+
state: 'attached',
|
|
2710
|
+
proxyPort: port,
|
|
2711
|
+
clientId: client.client_id,
|
|
2712
|
+
contextId: context.id,
|
|
2713
|
+
applicationId: client.application_id,
|
|
2714
|
+
},
|
|
2715
|
+
targets,
|
|
2716
|
+
contexts: targets,
|
|
2717
|
+
tree: projectDebuggerTreeForJson(tree),
|
|
2718
|
+
issues: [],
|
|
2719
|
+
logs: [
|
|
2720
|
+
{
|
|
2721
|
+
time: new Date().toTimeString().slice(0, 8),
|
|
2722
|
+
level: 'info',
|
|
2723
|
+
source: 'daemon',
|
|
2724
|
+
message: `Fetched ${context.rootComponentName || context.id} from Valdi daemon port ${port}.`,
|
|
2725
|
+
},
|
|
2726
|
+
],
|
|
2727
|
+
};
|
|
2728
|
+
});
|
|
2729
|
+
}
|
|
2730
|
+
async function inspectElementSnapshot(searchParams) {
|
|
2731
|
+
const port = readNumber(searchParams, 'port', defaultServicePort());
|
|
2732
|
+
const elementId = searchParams.get('elementId');
|
|
2733
|
+
if (!elementId) {
|
|
2734
|
+
throw new Error('Missing required elementId query parameter.');
|
|
2735
|
+
}
|
|
2736
|
+
return await withConnection(port, async (conn) => {
|
|
2737
|
+
const { client, context } = await resolveTarget(searchParams, conn);
|
|
2738
|
+
const base64 = await conn.takeSnapshot(client.client_id, elementId, context.id);
|
|
2739
|
+
if (!isValidSnapshotBase64(base64)) {
|
|
2740
|
+
throw new Error('The target returned an invalid base64 element snapshot.');
|
|
2741
|
+
}
|
|
2742
|
+
return {
|
|
2743
|
+
image: `data:image/png;base64,${base64}`,
|
|
2744
|
+
elementId,
|
|
2745
|
+
port,
|
|
2746
|
+
clientId: client.client_id,
|
|
2747
|
+
contextId: context.id,
|
|
2748
|
+
};
|
|
2749
|
+
});
|
|
2750
|
+
}
|
|
2751
|
+
async function inspectHeap(request, searchParams) {
|
|
2752
|
+
if (request.method !== 'POST') {
|
|
2753
|
+
throw new Error('Heap inspection requires POST.');
|
|
2754
|
+
}
|
|
2755
|
+
const body = await readJsonBody(request);
|
|
2756
|
+
const port = readNumber(searchParams, 'port', defaultServicePort());
|
|
2757
|
+
const performGC = body['performGC'] === true;
|
|
2758
|
+
return await withConnection(port, async (conn) => {
|
|
2759
|
+
const { client } = await resolveTarget(searchParams, conn);
|
|
2760
|
+
const heap = await conn.dumpHeap(client.client_id, performGC);
|
|
2761
|
+
return {
|
|
2762
|
+
port,
|
|
2763
|
+
clientId: client.client_id,
|
|
2764
|
+
heap,
|
|
2765
|
+
};
|
|
2766
|
+
});
|
|
2767
|
+
}
|
|
2768
|
+
async function resolvePerformanceTraceTarget(searchParams) {
|
|
2769
|
+
const port = readNumber(searchParams, 'port', daemonClient_1.STANDALONE_PORT);
|
|
2770
|
+
return await withConnection(port, async (conn) => {
|
|
2771
|
+
const { client, context } = await resolveTarget(searchParams, conn);
|
|
2772
|
+
const resolvedSearchParams = new URLSearchParams(searchParams);
|
|
2773
|
+
resolvedSearchParams.set('port', String(port));
|
|
2774
|
+
resolvedSearchParams.set('clientId', client.client_id);
|
|
2775
|
+
resolvedSearchParams.set('contextId', context.id);
|
|
2776
|
+
return {
|
|
2777
|
+
key: `${port}\0${client.client_id}`,
|
|
2778
|
+
searchParams: resolvedSearchParams,
|
|
2779
|
+
};
|
|
2780
|
+
});
|
|
2781
|
+
}
|
|
2782
|
+
async function sendPerformanceTraceMessage(searchParams, action, data) {
|
|
2783
|
+
const port = readNumber(searchParams, 'port', daemonClient_1.STANDALONE_PORT);
|
|
2784
|
+
return await withConnection(port, async (conn) => {
|
|
2785
|
+
const { client, context } = await resolveTarget(searchParams, conn);
|
|
2786
|
+
let result;
|
|
2787
|
+
if (action === PerformanceTraceAction.Status) {
|
|
2788
|
+
result = await conn.performanceTraceStatus(client.client_id, { contextId: context.id }, TRACE_DAEMON_TIMEOUT_MS);
|
|
2789
|
+
}
|
|
2790
|
+
else if (action === PerformanceTraceAction.Start) {
|
|
2791
|
+
const rendererTracing = data['rendererTracing'];
|
|
2792
|
+
if (typeof rendererTracing !== 'boolean') {
|
|
2793
|
+
throw new TypeError('Performance trace start requires a rendererTracing boolean.');
|
|
2794
|
+
}
|
|
2795
|
+
result = await conn.performanceTraceStart(client.client_id, {
|
|
2796
|
+
contextId: context.id,
|
|
2797
|
+
rendererTracing,
|
|
2798
|
+
}, TRACE_DAEMON_TIMEOUT_MS);
|
|
2799
|
+
}
|
|
2800
|
+
else {
|
|
2801
|
+
result = await conn.performanceTraceStop(client.client_id, { contextId: context.id }, TRACE_DAEMON_TIMEOUT_MS);
|
|
2802
|
+
}
|
|
2803
|
+
assertPerformanceTraceContext(action, result, context.id);
|
|
2804
|
+
return decorateTraceResult(result, createDaemonTargetPayload(port, client, context));
|
|
2805
|
+
});
|
|
2806
|
+
}
|
|
2807
|
+
function assertPerformanceTraceContext(action, result, expectedContextId) {
|
|
2808
|
+
if (action !== PerformanceTraceAction.Status && result['contextId'] !== expectedContextId) {
|
|
2809
|
+
throw new Error(`The Valdi runtime returned trace data for context ${String(result['contextId'])}, expected ${expectedContextId}.`);
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
async function inspectPerformanceTraceStatus(request, searchParams) {
|
|
2813
|
+
if (request.method !== 'GET') {
|
|
2814
|
+
throw new ApiRequestError(405, 'Performance trace status requires GET.');
|
|
2815
|
+
}
|
|
2816
|
+
return await sendPerformanceTraceMessage(searchParams, PerformanceTraceAction.Status, {});
|
|
2817
|
+
}
|
|
2818
|
+
async function startPerformanceTrace(request, searchParams) {
|
|
2819
|
+
if (request.method !== 'POST') {
|
|
2820
|
+
throw new ApiRequestError(405, 'Performance trace start requires POST.');
|
|
2821
|
+
}
|
|
2822
|
+
const body = await readJsonBody(request);
|
|
2823
|
+
const rendererTracing = readRendererTracing(body);
|
|
2824
|
+
const target = await resolvePerformanceTraceTarget(searchParams);
|
|
2825
|
+
return await performanceTraceCoordinator.runTransition(target.key, async () => {
|
|
2826
|
+
return await sendPerformanceTraceMessage(target.searchParams, PerformanceTraceAction.Start, {
|
|
2827
|
+
rendererTracing,
|
|
2828
|
+
});
|
|
2829
|
+
});
|
|
2830
|
+
}
|
|
2831
|
+
async function stopPerformanceTrace(request, searchParams) {
|
|
2832
|
+
if (request.method !== 'POST') {
|
|
2833
|
+
throw new ApiRequestError(405, 'Performance trace stop requires POST.');
|
|
2834
|
+
}
|
|
2835
|
+
const target = await resolvePerformanceTraceTarget(searchParams);
|
|
2836
|
+
return await performanceTraceCoordinator.stop(target.key, async () => await sendPerformanceTraceMessage(target.searchParams, PerformanceTraceAction.Stop, {}));
|
|
2837
|
+
}
|
|
2838
|
+
async function capturePerformanceTrace(request, searchParams) {
|
|
2839
|
+
if (request.method !== 'POST') {
|
|
2840
|
+
throw new ApiRequestError(405, 'Performance trace capture requires POST.');
|
|
2841
|
+
}
|
|
2842
|
+
const body = await readJsonBody(request);
|
|
2843
|
+
const options = {
|
|
2844
|
+
durationMs: normalizeTraceCaptureDurationMs(body),
|
|
2845
|
+
rendererTracing: readRendererTracing(body),
|
|
2846
|
+
};
|
|
2847
|
+
const target = await resolvePerformanceTraceTarget(searchParams);
|
|
2848
|
+
return await performanceTraceCoordinator.capture(target.key, options, {
|
|
2849
|
+
send: async (action, data) => await sendPerformanceTraceMessage(target.searchParams, action, data),
|
|
2850
|
+
wait: delay,
|
|
2851
|
+
});
|
|
2852
|
+
}
|
|
2853
|
+
async function runPerformanceTraceCapture(options, dependencies) {
|
|
2854
|
+
const status = await dependencies.send(PerformanceTraceAction.Status, {});
|
|
2855
|
+
if (status['tracingSupported'] !== true) {
|
|
2856
|
+
throw new Error('This Valdi runtime does not support renderer trace capture.');
|
|
2857
|
+
}
|
|
2858
|
+
if (status['recording'] || status['completedRecordingAvailable']) {
|
|
2859
|
+
const contextId = status['contextId'] ?? status['completedContextId'];
|
|
2860
|
+
const contextSuffix = typeof contextId === 'string' ? ` for context ${contextId}` : '';
|
|
2861
|
+
throw new Error(`A renderer trace recording is already active or waiting to be retrieved${contextSuffix}. Stop it before one-shot capture.`);
|
|
2862
|
+
}
|
|
2863
|
+
await dependencies.send(PerformanceTraceAction.Start, { rendererTracing: options.rendererTracing });
|
|
2864
|
+
try {
|
|
2865
|
+
await dependencies.wait(options.durationMs);
|
|
2866
|
+
}
|
|
2867
|
+
catch (waitError) {
|
|
2868
|
+
try {
|
|
2869
|
+
await dependencies.send(PerformanceTraceAction.Stop, {});
|
|
2870
|
+
}
|
|
2871
|
+
catch (cleanupError) {
|
|
2872
|
+
throw new Error(`${errorPayload(waitError).error} Best-effort renderer trace cleanup also failed: ${errorPayload(cleanupError).error}`);
|
|
2873
|
+
}
|
|
2874
|
+
throw waitError;
|
|
2875
|
+
}
|
|
2876
|
+
try {
|
|
2877
|
+
return await dependencies.send(PerformanceTraceAction.Stop, {});
|
|
2878
|
+
}
|
|
2879
|
+
catch (stopError) {
|
|
2880
|
+
try {
|
|
2881
|
+
return await dependencies.send(PerformanceTraceAction.Stop, {});
|
|
2882
|
+
}
|
|
2883
|
+
catch (cleanupError) {
|
|
2884
|
+
throw new Error(`${errorPayload(stopError).error} Best-effort renderer trace cleanup also failed: ${errorPayload(cleanupError).error}`);
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
}
|
|
2888
|
+
function decorateTraceResult(result, captureTarget) {
|
|
2889
|
+
const traces = readRecordedTraces(result['traces']);
|
|
2890
|
+
const receivedTraceCount = Array.isArray(result['traces']) ? result['traces'].length : 0;
|
|
2891
|
+
const runtimeDroppedTraceCount = typeof result['droppedTraceEventCount'] === 'number' &&
|
|
2892
|
+
Number.isSafeInteger(result['droppedTraceEventCount']) &&
|
|
2893
|
+
result['droppedTraceEventCount'] >= 0
|
|
2894
|
+
? Math.max(0, result['droppedTraceEventCount'])
|
|
2895
|
+
: 0;
|
|
2896
|
+
const localDroppedTraceCount = Math.max(0, receivedTraceCount - traces.length);
|
|
2897
|
+
const initialDroppedTraceEventCount = saturatingAdd(runtimeDroppedTraceCount, localDroppedTraceCount);
|
|
2898
|
+
const boundedCaptureTarget = {};
|
|
2899
|
+
for (const key of TRACE_CAPTURE_TARGET_STRING_KEYS) {
|
|
2900
|
+
const value = captureTarget[key];
|
|
2901
|
+
if (typeof value === 'string') {
|
|
2902
|
+
boundedCaptureTarget[key] = truncateStringForJson(value, MAX_TRACE_HTTP_STRING_BYTES);
|
|
2903
|
+
}
|
|
2904
|
+
}
|
|
2905
|
+
if (typeof captureTarget['port'] === 'number' && Number.isFinite(captureTarget['port'])) {
|
|
2906
|
+
boundedCaptureTarget['port'] = captureTarget['port'];
|
|
2907
|
+
}
|
|
2908
|
+
const boundedContextId = typeof result['contextId'] === 'string'
|
|
2909
|
+
? truncateStringForJson(result['contextId'], MAX_TRACE_HTTP_STRING_BYTES)
|
|
2910
|
+
: undefined;
|
|
2911
|
+
const boundedCompletedContextId = typeof result['completedContextId'] === 'string'
|
|
2912
|
+
? truncateStringForJson(result['completedContextId'], MAX_TRACE_HTTP_STRING_BYTES)
|
|
2913
|
+
: undefined;
|
|
2914
|
+
const boundedCompletionError = typeof result['completionError'] === 'string'
|
|
2915
|
+
? truncateStringForJson(result['completionError'], MAX_TRACE_HTTP_STRING_BYTES)
|
|
2916
|
+
: undefined;
|
|
2917
|
+
const browserMetrics = readBrowserTraceMetrics(result['browserMetrics']);
|
|
2918
|
+
const webPreviewTrace = result['webPreviewTrace'] === true;
|
|
2919
|
+
const buildResult = (includedTraceCount) => {
|
|
2920
|
+
const includedTraces = traces.slice(0, includedTraceCount);
|
|
2921
|
+
const droppedTraceEventCount = saturatingAdd(initialDroppedTraceEventCount, traces.length - includedTraceCount);
|
|
2922
|
+
const perfettoMetadata = buildPerfettoCaptureMetadata(boundedCaptureTarget, droppedTraceEventCount);
|
|
2923
|
+
return {
|
|
2924
|
+
recording: result['recording'] === true,
|
|
2925
|
+
contextId: boundedContextId,
|
|
2926
|
+
completedRecordingAvailable: result['completedRecordingAvailable'] === true,
|
|
2927
|
+
completedContextId: boundedCompletedContextId,
|
|
2928
|
+
completionError: boundedCompletionError,
|
|
2929
|
+
rendererTracingEnabled: result['rendererTracingEnabled'] === true,
|
|
2930
|
+
tracingSupported: result['tracingSupported'] === true,
|
|
2931
|
+
startedAtEpochMs: typeof result['startedAtEpochMs'] === 'number' ? result['startedAtEpochMs'] : undefined,
|
|
2932
|
+
elapsedMs: typeof result['elapsedMs'] === 'number' ? result['elapsedMs'] : undefined,
|
|
2933
|
+
timedOut: result['timedOut'] === true,
|
|
2934
|
+
traces: includedTraces,
|
|
2935
|
+
captureScope: PROCESS_WIDE_CAPTURE_SCOPE,
|
|
2936
|
+
captureTarget: boundedCaptureTarget,
|
|
2937
|
+
traceCount: includedTraces.length,
|
|
2938
|
+
droppedTraceEventCount,
|
|
2939
|
+
traceEventLimitReached: droppedTraceEventCount > 0,
|
|
2940
|
+
summary: summarizeTraces(includedTraces),
|
|
2941
|
+
perfettoMetadata,
|
|
2942
|
+
...(webPreviewTrace
|
|
2943
|
+
? {
|
|
2944
|
+
browserMetrics,
|
|
2945
|
+
browserSummary: summarizeBrowserTraces(includedTraces),
|
|
2946
|
+
webPreviewTrace: true,
|
|
2947
|
+
}
|
|
2948
|
+
: {}),
|
|
2949
|
+
};
|
|
2950
|
+
};
|
|
2951
|
+
let minimumTraceCount = 0;
|
|
2952
|
+
let maximumTraceCount = traces.length;
|
|
2953
|
+
let boundedResult = buildResult(0);
|
|
2954
|
+
if (Buffer.byteLength(JSON.stringify(boundedResult), 'utf8') > exports.MAX_TRACE_HTTP_RESPONSE_BYTES) {
|
|
2955
|
+
throw new Error('Valdi performance trace response metadata exceeds the HTTP size limit.');
|
|
2956
|
+
}
|
|
2957
|
+
while (minimumTraceCount <= maximumTraceCount) {
|
|
2958
|
+
const candidateTraceCount = Math.floor((minimumTraceCount + maximumTraceCount) / 2);
|
|
2959
|
+
const candidate = buildResult(candidateTraceCount);
|
|
2960
|
+
if (Buffer.byteLength(JSON.stringify(candidate), 'utf8') <= exports.MAX_TRACE_HTTP_RESPONSE_BYTES) {
|
|
2961
|
+
boundedResult = candidate;
|
|
2962
|
+
minimumTraceCount = candidateTraceCount + 1;
|
|
2963
|
+
}
|
|
2964
|
+
else {
|
|
2965
|
+
maximumTraceCount = candidateTraceCount - 1;
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
2968
|
+
return boundedResult;
|
|
2969
|
+
}
|
|
2970
|
+
function readBrowserTraceMetrics(value) {
|
|
2971
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
2972
|
+
return {};
|
|
2973
|
+
const record = value;
|
|
2974
|
+
const metrics = {};
|
|
2975
|
+
for (const name of ['TaskDurationMs', 'ScriptDurationMs', 'LayoutDurationMs', 'LayoutCount', 'RecalcStyleCount']) {
|
|
2976
|
+
const candidate = record[name];
|
|
2977
|
+
if (typeof candidate === 'number' && Number.isFinite(candidate) && candidate >= 0) {
|
|
2978
|
+
metrics[name] = candidate;
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
return metrics;
|
|
2982
|
+
}
|
|
2983
|
+
function summarizeBrowserTraces(traces) {
|
|
2984
|
+
let browserEventCount = 0;
|
|
2985
|
+
let frameCount = 0;
|
|
2986
|
+
let longTaskCount = 0;
|
|
2987
|
+
let longestTaskMs = 0;
|
|
2988
|
+
let rendererEventCount = 0;
|
|
2989
|
+
for (const trace of traces) {
|
|
2990
|
+
if (trace.trace.startsWith('Valdi.'))
|
|
2991
|
+
rendererEventCount++;
|
|
2992
|
+
if (!trace.trace.startsWith('Browser.'))
|
|
2993
|
+
continue;
|
|
2994
|
+
browserEventCount++;
|
|
2995
|
+
if (trace.trace.startsWith('Browser.Frames.'))
|
|
2996
|
+
frameCount++;
|
|
2997
|
+
if (trace.trace === 'Browser.MainThread.Task') {
|
|
2998
|
+
const durationMs = Math.max(0, trace.endMicros - trace.startMicros) / 1000;
|
|
2999
|
+
if (durationMs >= 50)
|
|
3000
|
+
longTaskCount++;
|
|
3001
|
+
longestTaskMs = Math.max(longestTaskMs, durationMs);
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
return { browserEventCount, frameCount, longTaskCount, longestTaskMs, rendererEventCount };
|
|
3005
|
+
}
|
|
3006
|
+
function saturatingAdd(left, right) {
|
|
3007
|
+
return left >= Number.MAX_SAFE_INTEGER - right ? Number.MAX_SAFE_INTEGER : left + right;
|
|
3008
|
+
}
|
|
3009
|
+
function readRecordedTraces(value) {
|
|
3010
|
+
if (!Array.isArray(value))
|
|
3011
|
+
return [];
|
|
3012
|
+
const values = value;
|
|
3013
|
+
const traces = [];
|
|
3014
|
+
const inputCount = Math.min(values.length, exports.MAX_TRACE_EVENT_COUNT);
|
|
3015
|
+
for (let index = 0; index < inputCount; index++) {
|
|
3016
|
+
const item = values[index];
|
|
3017
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item))
|
|
3018
|
+
continue;
|
|
3019
|
+
const candidate = item;
|
|
3020
|
+
const trace = candidate['trace'];
|
|
3021
|
+
const startMicros = candidate['startMicros'];
|
|
3022
|
+
const endMicros = candidate['endMicros'];
|
|
3023
|
+
const threadId = candidate['threadId'];
|
|
3024
|
+
if (typeof trace !== 'string' ||
|
|
3025
|
+
trace.length === 0 ||
|
|
3026
|
+
Buffer.byteLength(trace, 'utf8') > MAX_TRACE_NAME_BYTES ||
|
|
3027
|
+
typeof startMicros !== 'number' ||
|
|
3028
|
+
!Number.isSafeInteger(startMicros) ||
|
|
3029
|
+
startMicros < 0 ||
|
|
3030
|
+
typeof endMicros !== 'number' ||
|
|
3031
|
+
!Number.isSafeInteger(endMicros) ||
|
|
3032
|
+
endMicros < startMicros ||
|
|
3033
|
+
typeof threadId !== 'number' ||
|
|
3034
|
+
!Number.isSafeInteger(threadId) ||
|
|
3035
|
+
threadId < 0) {
|
|
3036
|
+
continue;
|
|
3037
|
+
}
|
|
3038
|
+
const recordedTrace = {
|
|
3039
|
+
trace,
|
|
3040
|
+
startMicros,
|
|
3041
|
+
endMicros,
|
|
3042
|
+
threadId,
|
|
3043
|
+
...(candidate['type'] === 1 ? { type: 1 } : {}),
|
|
3044
|
+
};
|
|
3045
|
+
traces.push(recordedTrace);
|
|
3046
|
+
}
|
|
3047
|
+
return traces;
|
|
3048
|
+
}
|
|
3049
|
+
function summarizeTraces(traces) {
|
|
3050
|
+
let durationTraceCount = 0;
|
|
3051
|
+
let instantTraceCount = 0;
|
|
3052
|
+
const componentDurations = new Map();
|
|
3053
|
+
const viewModelTriggers = new Map();
|
|
3054
|
+
for (const trace of traces) {
|
|
3055
|
+
if (trace.type === 1 || isRendererViewModelChangeTrace(trace.trace)) {
|
|
3056
|
+
instantTraceCount += 1;
|
|
3057
|
+
}
|
|
3058
|
+
else {
|
|
3059
|
+
durationTraceCount += 1;
|
|
3060
|
+
}
|
|
3061
|
+
const durationMicros = Math.max(0, trace.endMicros - trace.startMicros);
|
|
3062
|
+
const renderMatch = trace.trace.match(/(?:^|\.)Renderer\.onRender\.([^.]+)$/);
|
|
3063
|
+
if (renderMatch?.[1]) {
|
|
3064
|
+
const componentName = renderMatch[1];
|
|
3065
|
+
const componentSummary = componentDurations.get(componentName) ?? { count: 0, durationMicros: 0 };
|
|
3066
|
+
componentSummary.count += 1;
|
|
3067
|
+
componentSummary.durationMicros += durationMicros;
|
|
3068
|
+
componentDurations.set(componentName, componentSummary);
|
|
3069
|
+
}
|
|
3070
|
+
const triggerMatch = trace.trace.match(/(?:^|\.)Renderer\.viewModelChange\.([^.]+)\.(.+)$/);
|
|
3071
|
+
if (triggerMatch?.[1] && triggerMatch[2]) {
|
|
3072
|
+
const trigger = `${triggerMatch[1]}.${triggerMatch[2]}`;
|
|
3073
|
+
viewModelTriggers.set(trigger, (viewModelTriggers.get(trigger) ?? 0) + 1);
|
|
3074
|
+
}
|
|
3075
|
+
}
|
|
3076
|
+
return {
|
|
3077
|
+
captureScope: PROCESS_WIDE_CAPTURE_SCOPE,
|
|
3078
|
+
traceCount: traces.length,
|
|
3079
|
+
durationTraceCount,
|
|
3080
|
+
instantTraceCount,
|
|
3081
|
+
topComponents: Array.from(componentDurations.entries())
|
|
3082
|
+
.map(([name, value]) => ({
|
|
3083
|
+
name,
|
|
3084
|
+
count: value.count,
|
|
3085
|
+
durationMs: value.durationMicros / 1000,
|
|
3086
|
+
}))
|
|
3087
|
+
.sort((left, right) => right.durationMs - left.durationMs)
|
|
3088
|
+
.slice(0, 12),
|
|
3089
|
+
topViewModelTriggers: Array.from(viewModelTriggers.entries())
|
|
3090
|
+
.map(([name, count]) => ({ name, count }))
|
|
3091
|
+
.sort((left, right) => right.count - left.count)
|
|
3092
|
+
.slice(0, 12),
|
|
3093
|
+
};
|
|
3094
|
+
}
|
|
3095
|
+
function isRendererViewModelChangeTrace(traceName) {
|
|
3096
|
+
return /(?:^|\.)Renderer\.viewModelChange\.[^.]+\..+$/.test(traceName);
|
|
3097
|
+
}
|
|
3098
|
+
function buildPerfettoTracePayload(traces, captureTarget, droppedTraceEventCount) {
|
|
3099
|
+
const minStartMicros = traces.reduce((minimum, trace) => Math.min(minimum, trace.startMicros), traces[0]?.startMicros ?? 0);
|
|
3100
|
+
const threadIds = Array.from(new Set(traces.map(trace => trace.threadId)))
|
|
3101
|
+
.sort((left, right) => left - right)
|
|
3102
|
+
.slice(0, MAX_TRACE_THREAD_METADATA_COUNT);
|
|
3103
|
+
const traceEvents = [
|
|
3104
|
+
{
|
|
3105
|
+
name: 'process_name',
|
|
3106
|
+
ph: 'M',
|
|
3107
|
+
pid: PERFETTO_PROCESS_ID,
|
|
3108
|
+
args: { name: PERFETTO_PROCESS_NAME },
|
|
3109
|
+
},
|
|
3110
|
+
];
|
|
3111
|
+
for (const threadId of threadIds) {
|
|
3112
|
+
traceEvents.push({
|
|
3113
|
+
name: 'thread_name',
|
|
3114
|
+
ph: 'M',
|
|
3115
|
+
pid: PERFETTO_PROCESS_ID,
|
|
3116
|
+
tid: threadId,
|
|
3117
|
+
args: { name: `Valdi thread ${threadId}` },
|
|
3118
|
+
});
|
|
3119
|
+
}
|
|
3120
|
+
for (const trace of traces) {
|
|
3121
|
+
const isInstant = trace.type === 1 || isRendererViewModelChangeTrace(trace.trace);
|
|
3122
|
+
const event = {
|
|
3123
|
+
name: trace.trace,
|
|
3124
|
+
cat: PERFETTO_TRACE_CATEGORY,
|
|
3125
|
+
ph: isInstant ? 'i' : 'X',
|
|
3126
|
+
pid: PERFETTO_PROCESS_ID,
|
|
3127
|
+
tid: trace.threadId,
|
|
3128
|
+
ts: trace.startMicros - minStartMicros,
|
|
3129
|
+
};
|
|
3130
|
+
if (isInstant) {
|
|
3131
|
+
event.s = 't';
|
|
3132
|
+
}
|
|
3133
|
+
else {
|
|
3134
|
+
event.dur = Math.max(0, trace.endMicros - trace.startMicros);
|
|
3135
|
+
}
|
|
3136
|
+
traceEvents.push(event);
|
|
3137
|
+
}
|
|
3138
|
+
return {
|
|
3139
|
+
displayTimeUnit: 'ms',
|
|
3140
|
+
metadata: buildPerfettoCaptureMetadata(captureTarget, droppedTraceEventCount),
|
|
3141
|
+
traceEvents,
|
|
3142
|
+
};
|
|
3143
|
+
}
|
|
3144
|
+
function buildPerfettoCaptureMetadata(captureTarget, droppedTraceEventCount) {
|
|
3145
|
+
return {
|
|
3146
|
+
captureScope: PROCESS_WIDE_CAPTURE_SCOPE,
|
|
3147
|
+
captureTargetContextId: captureTarget['contextId'],
|
|
3148
|
+
captureTargetName: captureTarget['name'],
|
|
3149
|
+
droppedTraceEventCount,
|
|
3150
|
+
};
|
|
3151
|
+
}
|
|
3152
|
+
async function dispatchInput(request, searchParams) {
|
|
3153
|
+
if (request.method !== 'POST') {
|
|
3154
|
+
throw new ApiRequestError(405, 'Input dispatch requires POST.');
|
|
3155
|
+
}
|
|
3156
|
+
const body = await readJsonBody(request);
|
|
3157
|
+
const validationError = (0, inputClient_1.validateDebuggerInputRequest)(body);
|
|
3158
|
+
if (validationError) {
|
|
3159
|
+
throw new ApiRequestError(400, validationError);
|
|
3160
|
+
}
|
|
3161
|
+
const inputType = body['type'];
|
|
3162
|
+
const portValue = searchParams.get('port');
|
|
3163
|
+
if (portValue !== null && !/^\d+$/.test(portValue)) {
|
|
3164
|
+
throw new ApiRequestError(400, 'Input port must be an integer between 1 and 65535.');
|
|
3165
|
+
}
|
|
3166
|
+
const port = portValue === null ? daemonClient_1.STANDALONE_PORT : Number(portValue);
|
|
3167
|
+
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
|
|
3168
|
+
throw new ApiRequestError(400, 'Input port must be an integer between 1 and 65535.');
|
|
3169
|
+
}
|
|
3170
|
+
return await withConnection(port, async (conn) => {
|
|
3171
|
+
const target = inputType === inputClient_1.DebuggerInputType.Capabilities
|
|
3172
|
+
? { ...(await resolveClient(searchParams, conn)), context: undefined }
|
|
3173
|
+
: await resolveTarget(searchParams, conn);
|
|
3174
|
+
const { client, context } = target;
|
|
3175
|
+
const elementLabel = body['elementId'] === undefined ? 'none' : String(body['elementId']);
|
|
3176
|
+
console.log(`[input] dispatch type=${inputType} element=${elementLabel} client=${client.client_id} context=${context?.id ?? 'none'}`);
|
|
3177
|
+
const result = await (0, inputClient_1.sendDebuggerInput)(conn, client.client_id, {
|
|
3178
|
+
...body,
|
|
3179
|
+
...(context ? { contextId: context.id } : {}),
|
|
3180
|
+
});
|
|
3181
|
+
console.log(`[input] result handled=${String(Boolean(result['handled']))} element=${String(result['elementId'] ?? 'none')} action=${String(result['action'] ?? 'none')}`);
|
|
3182
|
+
return {
|
|
3183
|
+
port,
|
|
3184
|
+
clientId: client.client_id,
|
|
3185
|
+
contextId: context?.id,
|
|
3186
|
+
input: result,
|
|
3187
|
+
};
|
|
3188
|
+
});
|
|
3189
|
+
}
|
|
3190
|
+
async function inspectProfileContexts(searchParams) {
|
|
3191
|
+
const port = readNumber(searchParams, 'hermesPort', hermesClient_1.HERMES_PORT);
|
|
3192
|
+
const contexts = await (0, hermesClient_1.listHermesDevices)(port);
|
|
3193
|
+
return {
|
|
3194
|
+
port,
|
|
3195
|
+
contexts,
|
|
3196
|
+
active: profileStatusPayload(),
|
|
3197
|
+
};
|
|
3198
|
+
}
|
|
3199
|
+
async function startCpuProfile(request, searchParams) {
|
|
3200
|
+
if (request.method !== 'POST') {
|
|
3201
|
+
throw new Error('CPU profile start requires POST.');
|
|
3202
|
+
}
|
|
3203
|
+
assertNoActiveProfile();
|
|
3204
|
+
return await runProfileTransition(async () => {
|
|
3205
|
+
assertNoActiveProfile();
|
|
3206
|
+
const body = await readJsonBody(request);
|
|
3207
|
+
activeProfileSession = await createProfileSession(searchParams, body);
|
|
3208
|
+
return profileStatusPayload();
|
|
3209
|
+
});
|
|
3210
|
+
}
|
|
3211
|
+
async function stopCpuProfile(request) {
|
|
3212
|
+
if (request.method !== 'POST') {
|
|
3213
|
+
throw new Error('CPU profile stop requires POST.');
|
|
3214
|
+
}
|
|
3215
|
+
const capture = activeProfileCapture;
|
|
3216
|
+
if (capture)
|
|
3217
|
+
return await capture.stop();
|
|
3218
|
+
return await runProfileTransition(stopActiveProfileSession);
|
|
3219
|
+
}
|
|
3220
|
+
async function captureCpuProfile(request, searchParams) {
|
|
3221
|
+
if (request.method !== 'POST') {
|
|
3222
|
+
throw new Error('CPU profile capture requires POST.');
|
|
3223
|
+
}
|
|
3224
|
+
assertNoActiveProfile();
|
|
3225
|
+
const durationMs = await runProfileTransition(async () => {
|
|
3226
|
+
assertNoActiveProfile();
|
|
3227
|
+
const body = await readJsonBody(request);
|
|
3228
|
+
const requestedDurationMs = clampNumber(readBodyNumber(body, 'durationMs', 5000), 100, 60_000);
|
|
3229
|
+
activeProfileSession = await createProfileSession(searchParams, body);
|
|
3230
|
+
return requestedDurationMs;
|
|
3231
|
+
});
|
|
3232
|
+
let capture;
|
|
3233
|
+
capture = createInterruptibleOperation(durationMs, async () => {
|
|
3234
|
+
try {
|
|
3235
|
+
return await runProfileTransition(stopActiveProfileSession);
|
|
3236
|
+
}
|
|
3237
|
+
finally {
|
|
3238
|
+
if (activeProfileCapture === capture)
|
|
3239
|
+
activeProfileCapture = null;
|
|
3240
|
+
}
|
|
3241
|
+
});
|
|
3242
|
+
activeProfileCapture = capture;
|
|
3243
|
+
if (debuggerServerClosing)
|
|
3244
|
+
void capture.stop();
|
|
3245
|
+
try {
|
|
3246
|
+
return await capture.result;
|
|
3247
|
+
}
|
|
3248
|
+
finally {
|
|
3249
|
+
if (activeProfileCapture === capture)
|
|
3250
|
+
activeProfileCapture = null;
|
|
3251
|
+
}
|
|
3252
|
+
}
|
|
3253
|
+
async function runProfileTransition(transition) {
|
|
3254
|
+
if (profileTransitionInProgress) {
|
|
3255
|
+
throw new Error('Another CPU profile transition is already in progress.');
|
|
3256
|
+
}
|
|
3257
|
+
profileTransitionInProgress = true;
|
|
3258
|
+
try {
|
|
3259
|
+
return await transition();
|
|
3260
|
+
}
|
|
3261
|
+
finally {
|
|
3262
|
+
profileTransitionInProgress = false;
|
|
3263
|
+
}
|
|
3264
|
+
}
|
|
3265
|
+
function assertNoActiveProfile() {
|
|
3266
|
+
if (activeProfileSession) {
|
|
3267
|
+
throw new Error(`CPU profiling is already active for context ${activeProfileSession.contextId}.`);
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
async function createProfileSession(searchParams, body) {
|
|
3271
|
+
const port = readBodyNumber(body, 'port', readNumber(searchParams, 'hermesPort', hermesClient_1.HERMES_PORT));
|
|
3272
|
+
const contexts = await (0, hermesClient_1.listHermesDevices)(port);
|
|
3273
|
+
if (contexts.length === 0) {
|
|
3274
|
+
throw new Error('No debuggable Hermes JS contexts found.');
|
|
3275
|
+
}
|
|
3276
|
+
const requestedContextId = readBodyString(body, 'contextId') ?? readBodyString(body, 'context');
|
|
3277
|
+
const firstContext = contexts[0];
|
|
3278
|
+
if (!firstContext) {
|
|
3279
|
+
throw new Error('No debuggable Hermes JS contexts found.');
|
|
3280
|
+
}
|
|
3281
|
+
const context = requestedContextId === undefined ? firstContext : contexts.find(candidate => candidate.id === requestedContextId);
|
|
3282
|
+
if (!context) {
|
|
3283
|
+
throw new Error(`Hermes context ${String(requestedContextId)} was not found.`);
|
|
3284
|
+
}
|
|
3285
|
+
const conn = await hermesClient_1.HermesConnection.connect(port, context.id);
|
|
3286
|
+
try {
|
|
3287
|
+
await conn.startProfiling();
|
|
3288
|
+
}
|
|
3289
|
+
catch (error) {
|
|
3290
|
+
conn.close();
|
|
3291
|
+
throw error;
|
|
3292
|
+
}
|
|
3293
|
+
return {
|
|
3294
|
+
conn,
|
|
3295
|
+
port,
|
|
3296
|
+
contextId: context.id,
|
|
3297
|
+
contextTitle: context.title,
|
|
3298
|
+
startedAtMs: Date.now(),
|
|
3299
|
+
startedAtEpochMs: Date.now(),
|
|
3300
|
+
};
|
|
3301
|
+
}
|
|
3302
|
+
async function stopActiveProfileSession() {
|
|
3303
|
+
const session = activeProfileSession;
|
|
3304
|
+
if (!session) {
|
|
3305
|
+
throw new Error('No CPU profile recording is active.');
|
|
3306
|
+
}
|
|
3307
|
+
activeProfileSession = null;
|
|
3308
|
+
try {
|
|
3309
|
+
const profile = await session.conn.stopProfiling();
|
|
3310
|
+
return {
|
|
3311
|
+
profiling: false,
|
|
3312
|
+
port: session.port,
|
|
3313
|
+
contextId: session.contextId,
|
|
3314
|
+
contextTitle: session.contextTitle,
|
|
3315
|
+
startedAtEpochMs: session.startedAtEpochMs,
|
|
3316
|
+
elapsedMs: Date.now() - session.startedAtMs,
|
|
3317
|
+
profile,
|
|
3318
|
+
summary: summarizeCpuProfile(profile),
|
|
3319
|
+
};
|
|
3320
|
+
}
|
|
3321
|
+
finally {
|
|
3322
|
+
session.conn.close();
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
function profileStatusPayload() {
|
|
3326
|
+
if (!activeProfileSession) {
|
|
3327
|
+
return {
|
|
3328
|
+
profiling: false,
|
|
3329
|
+
};
|
|
3330
|
+
}
|
|
3331
|
+
return {
|
|
3332
|
+
profiling: true,
|
|
3333
|
+
port: activeProfileSession.port,
|
|
3334
|
+
contextId: activeProfileSession.contextId,
|
|
3335
|
+
contextTitle: activeProfileSession.contextTitle,
|
|
3336
|
+
startedAtEpochMs: activeProfileSession.startedAtEpochMs,
|
|
3337
|
+
elapsedMs: Date.now() - activeProfileSession.startedAtMs,
|
|
3338
|
+
};
|
|
3339
|
+
}
|
|
3340
|
+
function summarizeCpuProfile(profile) {
|
|
3341
|
+
const samples = profile.samples ?? [];
|
|
3342
|
+
const sampleCountByNodeId = new Map();
|
|
3343
|
+
for (const sample of samples) {
|
|
3344
|
+
sampleCountByNodeId.set(sample, (sampleCountByNodeId.get(sample) ?? 0) + 1);
|
|
3345
|
+
}
|
|
3346
|
+
const topFunctions = profile.nodes
|
|
3347
|
+
.map(node => ({
|
|
3348
|
+
name: node.callFrame.functionName || '(anonymous)',
|
|
3349
|
+
lineNumber: node.callFrame.lineNumber,
|
|
3350
|
+
sampleCount: sampleCountByNodeId.get(node.id) ?? node.hitCount ?? 0,
|
|
3351
|
+
}))
|
|
3352
|
+
.filter(node => node.sampleCount > 0)
|
|
3353
|
+
.sort((left, right) => right.sampleCount - left.sampleCount)
|
|
3354
|
+
.slice(0, 12);
|
|
3355
|
+
return {
|
|
3356
|
+
nodeCount: profile.nodes.length,
|
|
3357
|
+
sampleCount: samples.length,
|
|
3358
|
+
durationMs: (profile.endTime - profile.startTime) / 1000,
|
|
3359
|
+
topFunctions,
|
|
3360
|
+
};
|
|
3361
|
+
}
|
|
3362
|
+
async function handleApi(request, response, url) {
|
|
3363
|
+
try {
|
|
3364
|
+
if (url.pathname === '/api/dev-events') {
|
|
3365
|
+
streamDevEvents(request, response);
|
|
3366
|
+
return;
|
|
3367
|
+
}
|
|
3368
|
+
if (url.pathname === '/api/debugger/events') {
|
|
3369
|
+
streamDebuggerEvents(request, response);
|
|
3370
|
+
return;
|
|
3371
|
+
}
|
|
3372
|
+
if (url.pathname === '/api/debugger/state') {
|
|
3373
|
+
sendJson(response, 200, debuggerStatePayload());
|
|
3374
|
+
return;
|
|
3375
|
+
}
|
|
3376
|
+
if (url.pathname === '/api/debugger/actions') {
|
|
3377
|
+
if (request.method !== 'POST') {
|
|
3378
|
+
sendJson(response, 405, { error: 'Debugger actions require POST.' });
|
|
3379
|
+
return;
|
|
3380
|
+
}
|
|
3381
|
+
sendJson(response, 200, await handleDebuggerAction(request));
|
|
3382
|
+
return;
|
|
3383
|
+
}
|
|
3384
|
+
if (url.pathname === '/api/runtime-logs/stream') {
|
|
3385
|
+
await streamRuntimeLogs(request, response, url.searchParams);
|
|
3386
|
+
return;
|
|
3387
|
+
}
|
|
3388
|
+
if (url.pathname === '/api/status') {
|
|
3389
|
+
sendJson(response, 200, await inspectStatus(url.searchParams));
|
|
3390
|
+
return;
|
|
3391
|
+
}
|
|
3392
|
+
if (url.pathname === '/api/devtools/targets') {
|
|
3393
|
+
if (request.method !== 'GET') {
|
|
3394
|
+
sendJson(response, 405, { error: 'Valdi DevTools target discovery requires GET.' });
|
|
3395
|
+
return;
|
|
3396
|
+
}
|
|
3397
|
+
sendJson(response, 200, await inspectDebuggerTargets());
|
|
3398
|
+
return;
|
|
3399
|
+
}
|
|
3400
|
+
if (url.pathname === '/api/devtools/target') {
|
|
3401
|
+
if (request.method !== 'GET') {
|
|
3402
|
+
sendJson(response, 405, { error: 'Valdi DevTools target discovery requires GET.' });
|
|
3403
|
+
return;
|
|
3404
|
+
}
|
|
3405
|
+
sendJson(response, 200, await resolveInspectedDebuggerTarget(url.searchParams));
|
|
3406
|
+
return;
|
|
3407
|
+
}
|
|
3408
|
+
if (url.pathname === '/api/devtools/snapshot') {
|
|
3409
|
+
if (request.method !== 'GET') {
|
|
3410
|
+
sendJson(response, 405, { error: 'Valdi DevTools snapshots require GET.' });
|
|
3411
|
+
return;
|
|
3412
|
+
}
|
|
3413
|
+
sendJson(response, 200, await inspectDevToolsSnapshot(url.searchParams));
|
|
3414
|
+
return;
|
|
3415
|
+
}
|
|
3416
|
+
if (url.pathname === '/api/devtools/performance/snapshot') {
|
|
3417
|
+
sendJson(response, 200, await inspectWebPreviewPerformanceSnapshot(request, url.searchParams));
|
|
3418
|
+
return;
|
|
3419
|
+
}
|
|
3420
|
+
if (url.pathname === '/api/devtools/performance/trace/status') {
|
|
3421
|
+
sendTraceJson(response, 200, await inspectWebPreviewPerformanceTraceStatus(request, url.searchParams));
|
|
3422
|
+
return;
|
|
3423
|
+
}
|
|
3424
|
+
if (url.pathname === '/api/devtools/performance/trace/start') {
|
|
3425
|
+
sendTraceJson(response, 200, await startWebPreviewPerformanceTrace(request, url.searchParams));
|
|
3426
|
+
return;
|
|
3427
|
+
}
|
|
3428
|
+
if (url.pathname === '/api/devtools/performance/trace/stop') {
|
|
3429
|
+
sendTraceJson(response, 200, await stopWebPreviewPerformanceTrace(request, url.searchParams));
|
|
3430
|
+
return;
|
|
3431
|
+
}
|
|
3432
|
+
if (url.pathname === '/api/devtools/performance/trace/capture') {
|
|
3433
|
+
sendTraceJson(response, 200, await captureWebPreviewPerformanceTrace(request, url.searchParams));
|
|
3434
|
+
return;
|
|
3435
|
+
}
|
|
3436
|
+
if (url.pathname === '/api/devtools/performance/trace/enable') {
|
|
3437
|
+
sendJson(response, 200, await enableWebPreviewPerformanceTracing(request, url.searchParams));
|
|
3438
|
+
return;
|
|
3439
|
+
}
|
|
3440
|
+
if (url.pathname === '/api/devtools/console/stream') {
|
|
3441
|
+
if (request.method !== 'GET') {
|
|
3442
|
+
sendJson(response, 405, { error: 'Valdi DevTools console streaming requires GET.' });
|
|
3443
|
+
return;
|
|
3444
|
+
}
|
|
3445
|
+
await streamWebPreviewConsole(request, response, url.searchParams);
|
|
3446
|
+
return;
|
|
3447
|
+
}
|
|
3448
|
+
if (url.pathname === '/api/devtools/component-property') {
|
|
3449
|
+
sendJson(response, 200, await editWebPreviewComponentProperty(request, url.searchParams));
|
|
3450
|
+
return;
|
|
3451
|
+
}
|
|
3452
|
+
if (url.pathname === '/api/devtools/evaluate' || url.pathname === '/api/devtools/highlight') {
|
|
3453
|
+
if (request.method !== 'POST') {
|
|
3454
|
+
sendJson(response, 405, { error: 'Valdi DevTools runtime actions require POST.' });
|
|
3455
|
+
return;
|
|
3456
|
+
}
|
|
3457
|
+
const body = await readJsonBody(request);
|
|
3458
|
+
const result = url.pathname.endsWith('/evaluate')
|
|
3459
|
+
? await evaluateWebPreviewConsole(body)
|
|
3460
|
+
: await highlightWebPreviewNode(body);
|
|
3461
|
+
sendJson(response, 200, result);
|
|
3462
|
+
return;
|
|
3463
|
+
}
|
|
3464
|
+
if (url.pathname === '/api/snapshot') {
|
|
3465
|
+
sendJson(response, 200, await inspectSnapshot(url.searchParams));
|
|
3466
|
+
return;
|
|
3467
|
+
}
|
|
3468
|
+
if (url.pathname === '/api/element-snapshot') {
|
|
3469
|
+
sendJson(response, 200, await inspectElementSnapshot(url.searchParams));
|
|
3470
|
+
return;
|
|
3471
|
+
}
|
|
3472
|
+
if (url.pathname === '/api/heap') {
|
|
3473
|
+
sendJson(response, 200, await inspectHeap(request, url.searchParams));
|
|
3474
|
+
return;
|
|
3475
|
+
}
|
|
3476
|
+
if (url.pathname === '/api/input') {
|
|
3477
|
+
sendJson(response, 200, await dispatchInput(request, url.searchParams));
|
|
3478
|
+
return;
|
|
3479
|
+
}
|
|
3480
|
+
if (url.pathname === '/api/performance/trace/status') {
|
|
3481
|
+
sendTraceJson(response, 200, await inspectPerformanceTraceStatus(request, url.searchParams));
|
|
3482
|
+
return;
|
|
3483
|
+
}
|
|
3484
|
+
if (url.pathname === '/api/performance/trace/start') {
|
|
3485
|
+
sendTraceJson(response, 200, await startPerformanceTrace(request, url.searchParams));
|
|
3486
|
+
return;
|
|
3487
|
+
}
|
|
3488
|
+
if (url.pathname === '/api/performance/trace/stop') {
|
|
3489
|
+
sendTraceJson(response, 200, await stopPerformanceTrace(request, url.searchParams));
|
|
3490
|
+
return;
|
|
3491
|
+
}
|
|
3492
|
+
if (url.pathname === '/api/performance/trace/capture') {
|
|
3493
|
+
sendTraceJson(response, 200, await capturePerformanceTrace(request, url.searchParams));
|
|
3494
|
+
return;
|
|
3495
|
+
}
|
|
3496
|
+
if (url.pathname === '/api/debugger/providers') {
|
|
3497
|
+
if (request.method !== 'GET')
|
|
3498
|
+
throw new ApiRequestError(405, 'Debugger provider discovery requires GET.');
|
|
3499
|
+
sendJson(response, 200, await inspectDebuggerProviders(url.searchParams));
|
|
3500
|
+
return;
|
|
3501
|
+
}
|
|
3502
|
+
if (url.pathname === '/api/debugger/providers/request') {
|
|
3503
|
+
sendJson(response, 200, await requestDebuggerProvider(request, url.searchParams));
|
|
3504
|
+
return;
|
|
3505
|
+
}
|
|
3506
|
+
if (url.pathname === '/api/debugger/settings') {
|
|
3507
|
+
sendJson(response, 200, await handleDebugSettings(request, url.searchParams));
|
|
3508
|
+
return;
|
|
3509
|
+
}
|
|
3510
|
+
if (url.pathname === '/api/performance/profile/status') {
|
|
3511
|
+
sendJson(response, 200, profileStatusPayload());
|
|
3512
|
+
return;
|
|
3513
|
+
}
|
|
3514
|
+
if (url.pathname === '/api/performance/profile/contexts') {
|
|
3515
|
+
sendJson(response, 200, await inspectProfileContexts(url.searchParams));
|
|
3516
|
+
return;
|
|
3517
|
+
}
|
|
3518
|
+
if (url.pathname === '/api/performance/profile/start') {
|
|
3519
|
+
sendJson(response, 200, await startCpuProfile(request, url.searchParams));
|
|
3520
|
+
return;
|
|
3521
|
+
}
|
|
3522
|
+
if (url.pathname === '/api/performance/profile/stop') {
|
|
3523
|
+
sendJson(response, 200, await stopCpuProfile(request));
|
|
3524
|
+
return;
|
|
3525
|
+
}
|
|
3526
|
+
if (url.pathname === '/api/performance/profile/capture') {
|
|
3527
|
+
sendJson(response, 200, await captureCpuProfile(request, url.searchParams));
|
|
3528
|
+
return;
|
|
3529
|
+
}
|
|
3530
|
+
if (url.pathname === '/api/runtime-logs') {
|
|
3531
|
+
sendJson(response, 200, await inspectRuntimeLogs(url.searchParams));
|
|
3532
|
+
return;
|
|
3533
|
+
}
|
|
3534
|
+
sendJson(response, 404, { error: `Unknown API route ${url.pathname}` });
|
|
3535
|
+
}
|
|
3536
|
+
catch (error) {
|
|
3537
|
+
const status = error instanceof ApiRequestError ? error.statusCode : 500;
|
|
3538
|
+
const payload = clientErrorPayload(error);
|
|
3539
|
+
if (url.pathname.startsWith('/api/performance/trace/') ||
|
|
3540
|
+
url.pathname.startsWith('/api/devtools/performance/trace/')) {
|
|
3541
|
+
sendTraceJson(response, status, payload);
|
|
3542
|
+
}
|
|
3543
|
+
else {
|
|
3544
|
+
sendJson(response, status, payload);
|
|
3545
|
+
}
|
|
3546
|
+
}
|
|
3547
|
+
}
|
|
3548
|
+
function injectApiTokenBootstrap(html, apiToken) {
|
|
3549
|
+
const bootstrap = `<meta name="${API_TOKEN_META_NAME}" content="${apiToken}">`;
|
|
3550
|
+
const headEnd = html.indexOf('</head>');
|
|
3551
|
+
if (headEnd !== -1)
|
|
3552
|
+
return `${html.slice(0, headEnd)}${bootstrap}${html.slice(headEnd)}`;
|
|
3553
|
+
const doctypeEnd = html.toLowerCase().startsWith('<!doctype html>') ? html.indexOf('>') + 1 : 0;
|
|
3554
|
+
return `${html.slice(0, doctypeEnd)}${bootstrap}${html.slice(doctypeEnd)}`;
|
|
3555
|
+
}
|
|
3556
|
+
async function serveStatic(_request, response, url, apiToken) {
|
|
3557
|
+
let requestedPath;
|
|
3558
|
+
try {
|
|
3559
|
+
requestedPath = decodeURIComponent(url.pathname === '/' ? '/index.html' : url.pathname);
|
|
3560
|
+
}
|
|
3561
|
+
catch {
|
|
3562
|
+
response.writeHead(400);
|
|
3563
|
+
response.end('Invalid URL encoding');
|
|
3564
|
+
return;
|
|
3565
|
+
}
|
|
3566
|
+
const resolvedPath = node_path_1.default.resolve(assetRoot, requestedPath.replace(/^\/+/, ''));
|
|
3567
|
+
const relativePath = node_path_1.default.relative(assetRoot, resolvedPath);
|
|
3568
|
+
if (relativePath === '..' || relativePath.startsWith(`..${node_path_1.default.sep}`) || node_path_1.default.isAbsolute(relativePath)) {
|
|
3569
|
+
response.writeHead(403);
|
|
3570
|
+
response.end('Forbidden');
|
|
3571
|
+
return;
|
|
3572
|
+
}
|
|
3573
|
+
try {
|
|
3574
|
+
const data = await promises_1.default.readFile(resolvedPath);
|
|
3575
|
+
const ext = node_path_1.default.extname(resolvedPath);
|
|
3576
|
+
const isDevToolsPanel = requestedPath === '/devtools-panel.html';
|
|
3577
|
+
const responseData = ext === '.html' ? injectApiTokenBootstrap(data.toString('utf8'), apiToken) : data;
|
|
3578
|
+
const headers = {
|
|
3579
|
+
'Content-Type': MIME_TYPES[ext] ?? 'application/octet-stream',
|
|
3580
|
+
'Cache-Control': 'no-store',
|
|
3581
|
+
'Content-Security-Policy': `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-src 'none'; object-src 'none'; base-uri 'none'; frame-ancestors ${isDevToolsPanel ? 'chrome-extension://*' : "'none'"}`,
|
|
3582
|
+
'X-Content-Type-Options': 'nosniff',
|
|
3583
|
+
'Referrer-Policy': 'no-referrer',
|
|
3584
|
+
};
|
|
3585
|
+
if (!isDevToolsPanel)
|
|
3586
|
+
headers['X-Frame-Options'] = 'DENY';
|
|
3587
|
+
response.writeHead(200, headers);
|
|
3588
|
+
response.end(responseData);
|
|
3589
|
+
}
|
|
3590
|
+
catch {
|
|
3591
|
+
response.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
3592
|
+
response.end(`Not found: ${url.pathname}`);
|
|
3593
|
+
}
|
|
3594
|
+
}
|
|
3595
|
+
function createDebuggerHttpServer(host, port, apiToken) {
|
|
3596
|
+
return node_http_1.default.createServer(async (request, response) => {
|
|
3597
|
+
const url = new URL(request.url || '/', `http://${hostForUrl(host)}:${port}`);
|
|
3598
|
+
const apiFetchSiteAllowed = !url.pathname.startsWith('/api/') || isAllowedApiFetchSite(request.headers['sec-fetch-site']);
|
|
3599
|
+
if (!isAllowedRequestHost(request.headers.host, port) ||
|
|
3600
|
+
!isAllowedRequestOrigin(request.headers.origin, request.headers.host, port) ||
|
|
3601
|
+
!apiFetchSiteAllowed) {
|
|
3602
|
+
response.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
3603
|
+
response.end('Forbidden');
|
|
3604
|
+
return;
|
|
3605
|
+
}
|
|
3606
|
+
if (url.pathname.startsWith('/api/')) {
|
|
3607
|
+
if (!hasValidApiToken(request, url, apiToken)) {
|
|
3608
|
+
sendJson(response, 401, { error: 'Debugger API authentication is required.' });
|
|
3609
|
+
return;
|
|
3610
|
+
}
|
|
3611
|
+
if (url.pathname.startsWith('/api/devtools/') && request.method === 'POST') {
|
|
3612
|
+
const contentType = request.headers['content-type']?.split(';')[0]?.trim().toLowerCase();
|
|
3613
|
+
if (contentType !== 'application/json') {
|
|
3614
|
+
sendJson(response, 415, { error: 'Valdi DevTools actions require an application/json request.' });
|
|
3615
|
+
return;
|
|
3616
|
+
}
|
|
3617
|
+
}
|
|
3618
|
+
await handleApi(request, response, url);
|
|
3619
|
+
return;
|
|
3620
|
+
}
|
|
3621
|
+
await serveStatic(request, response, url, apiToken);
|
|
3622
|
+
});
|
|
3623
|
+
}
|
|
3624
|
+
function listen(server, host, port) {
|
|
3625
|
+
return new Promise((resolve, reject) => {
|
|
3626
|
+
const onError = (error) => {
|
|
3627
|
+
server.off('listening', onListening);
|
|
3628
|
+
reject(error);
|
|
3629
|
+
};
|
|
3630
|
+
const onListening = () => {
|
|
3631
|
+
server.off('error', onError);
|
|
3632
|
+
resolve();
|
|
3633
|
+
};
|
|
3634
|
+
server.once('error', onError);
|
|
3635
|
+
server.once('listening', onListening);
|
|
3636
|
+
server.listen(port, host);
|
|
3637
|
+
});
|
|
3638
|
+
}
|
|
3639
|
+
async function watchDebuggerAssets(root) {
|
|
3640
|
+
let fileNames = [];
|
|
3641
|
+
try {
|
|
3642
|
+
const entries = await promises_1.default.readdir(root, { withFileTypes: true });
|
|
3643
|
+
fileNames = entries
|
|
3644
|
+
.filter(entry => entry.isFile() && /\.(?:html|css|js)$/.test(entry.name))
|
|
3645
|
+
.map(entry => entry.name)
|
|
3646
|
+
.sort();
|
|
3647
|
+
}
|
|
3648
|
+
catch (error) {
|
|
3649
|
+
console.warn(`Could not list debugger assets in ${root}: ${errorPayload(error).error}`);
|
|
3650
|
+
}
|
|
3651
|
+
if (!fileNames.includes('index.html'))
|
|
3652
|
+
fileNames.push('index.html');
|
|
3653
|
+
for (const fileName of fileNames) {
|
|
3654
|
+
const watchedPath = node_path_1.default.join(root, fileName);
|
|
3655
|
+
try {
|
|
3656
|
+
const watcher = (0, node_fs_1.watch)(watchedPath, { persistent: false }, () => {
|
|
3657
|
+
scheduleDevReload(fileName);
|
|
3658
|
+
});
|
|
3659
|
+
assetWatchers.add(watcher);
|
|
3660
|
+
watcher.once('close', () => assetWatchers.delete(watcher));
|
|
3661
|
+
}
|
|
3662
|
+
catch (error) {
|
|
3663
|
+
console.warn(`Could not watch ${watchedPath}: ${errorPayload(error).error}`);
|
|
3664
|
+
}
|
|
3665
|
+
}
|
|
3666
|
+
}
|
|
3667
|
+
function closeAssetWatchers() {
|
|
3668
|
+
for (const watcher of Array.from(assetWatchers)) {
|
|
3669
|
+
watcher.close();
|
|
3670
|
+
}
|
|
3671
|
+
assetWatchers.clear();
|
|
3672
|
+
}
|
|
3673
|
+
async function closeHttpServer(server) {
|
|
3674
|
+
await new Promise((resolve, reject) => {
|
|
3675
|
+
server.close(error => (error ? reject(error) : resolve()));
|
|
3676
|
+
});
|
|
3677
|
+
}
|
|
3678
|
+
async function closeDebuggerServer(server) {
|
|
3679
|
+
debuggerServerClosing = true;
|
|
3680
|
+
try {
|
|
3681
|
+
for (const closeStream of Array.from(eventStreamClosers)) {
|
|
3682
|
+
closeStream();
|
|
3683
|
+
}
|
|
3684
|
+
closeAssetWatchers();
|
|
3685
|
+
if (devReloadTimer) {
|
|
3686
|
+
clearTimeout(devReloadTimer);
|
|
3687
|
+
devReloadTimer = null;
|
|
3688
|
+
}
|
|
3689
|
+
if (activeProfileCapture) {
|
|
3690
|
+
try {
|
|
3691
|
+
await activeProfileCapture.stop();
|
|
3692
|
+
}
|
|
3693
|
+
catch (error) {
|
|
3694
|
+
console.warn(`Could not stop the active Hermes capture during shutdown: ${errorPayload(error).error}`);
|
|
3695
|
+
}
|
|
3696
|
+
}
|
|
3697
|
+
await closeHttpServer(server);
|
|
3698
|
+
try {
|
|
3699
|
+
await webPreviewPerformanceController.close();
|
|
3700
|
+
}
|
|
3701
|
+
catch (error) {
|
|
3702
|
+
console.warn(`Could not stop the active web preview trace during shutdown: ${errorPayload(error).error}`);
|
|
3703
|
+
}
|
|
3704
|
+
if (activeProfileSession) {
|
|
3705
|
+
try {
|
|
3706
|
+
await stopActiveProfileSession();
|
|
3707
|
+
}
|
|
3708
|
+
catch (error) {
|
|
3709
|
+
console.warn(`Could not stop the active Hermes profile during shutdown: ${errorPayload(error).error}`);
|
|
3710
|
+
}
|
|
3711
|
+
}
|
|
3712
|
+
}
|
|
3713
|
+
finally {
|
|
3714
|
+
activeHost = DEFAULT_HOST;
|
|
3715
|
+
assetRoot = getDefaultAssetRoot();
|
|
3716
|
+
activeLogsDirectory = null;
|
|
3717
|
+
activeServicePort = undefined;
|
|
3718
|
+
activeProfileSession = null;
|
|
3719
|
+
activeProfileCapture = null;
|
|
3720
|
+
profileTransitionInProgress = false;
|
|
3721
|
+
devEventClients.clear();
|
|
3722
|
+
debuggerEventClients.clear();
|
|
3723
|
+
eventStreamClosers.clear();
|
|
3724
|
+
devRevision = 0;
|
|
3725
|
+
debuggerEventRevision = 0;
|
|
3726
|
+
debuggerUiState = createDebuggerUiState(daemonClient_1.STANDALONE_PORT);
|
|
3727
|
+
activeWebPreviewTarget = null;
|
|
3728
|
+
activeDebuggerTargetDiscovery = DEFAULT_DEBUGGER_TARGET_DISCOVERY;
|
|
3729
|
+
debuggerServerClosing = false;
|
|
3730
|
+
debuggerServerLifecycleActive = false;
|
|
3731
|
+
}
|
|
3732
|
+
}
|
|
3733
|
+
async function startDebuggerServer(options) {
|
|
3734
|
+
if (debuggerServerLifecycleActive) {
|
|
3735
|
+
throw new Error('A debugger server is already starting or running in this process.');
|
|
3736
|
+
}
|
|
3737
|
+
debuggerServerLifecycleActive = true;
|
|
3738
|
+
const previousWebPreviewTarget = activeWebPreviewTarget;
|
|
3739
|
+
const previousDebuggerTargetDiscovery = activeDebuggerTargetDiscovery;
|
|
3740
|
+
try {
|
|
3741
|
+
const host = options.host ?? DEFAULT_HOST;
|
|
3742
|
+
if (!(0, loopbackHost_1.isLoopbackHost)(host)) {
|
|
3743
|
+
throw new Error(`The debugger server only binds to loopback hosts; received '${host}'.`);
|
|
3744
|
+
}
|
|
3745
|
+
const preferredPort = options.port ?? resolveDebuggerUiPort();
|
|
3746
|
+
if (!Number.isInteger(preferredPort) || preferredPort < 1 || preferredPort > 65_535) {
|
|
3747
|
+
throw new Error(`Debugger port must be an integer between 1 and 65535; received '${String(preferredPort)}'.`);
|
|
3748
|
+
}
|
|
3749
|
+
const servicePort = resolveDebuggerServicePort();
|
|
3750
|
+
const strictPort = Boolean(options.strictPort);
|
|
3751
|
+
const maxAttempts = strictPort ? 1 : PORT_SEARCH_LIMIT;
|
|
3752
|
+
const apiToken = (0, node_crypto_1.randomBytes)(32).toString('base64url');
|
|
3753
|
+
activeHost = host;
|
|
3754
|
+
assetRoot = options.assetRoot ?? getDefaultAssetRoot();
|
|
3755
|
+
activeLogsDirectory = options.logsDirectory ?? null;
|
|
3756
|
+
activeServicePort = servicePort;
|
|
3757
|
+
activeWebPreviewTarget = createWebPreviewDebuggerTarget(options.webPreviewUrl, options.chromiumDebuggingPort ?? DEFAULT_CHROMIUM_DEBUGGING_PORT);
|
|
3758
|
+
activeDebuggerTargetDiscovery = options.targetDiscovery ?? DEFAULT_DEBUGGER_TARGET_DISCOVERY;
|
|
3759
|
+
debuggerUiState = createDebuggerUiState(defaultServicePort());
|
|
3760
|
+
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
3761
|
+
const port = preferredPort + attempt;
|
|
3762
|
+
const server = createDebuggerHttpServer(activeHost, port, apiToken);
|
|
3763
|
+
try {
|
|
3764
|
+
await listen(server, activeHost, port);
|
|
3765
|
+
closeAssetWatchers();
|
|
3766
|
+
await watchDebuggerAssets(assetRoot);
|
|
3767
|
+
let closePromise;
|
|
3768
|
+
return {
|
|
3769
|
+
server,
|
|
3770
|
+
close: () => {
|
|
3771
|
+
closePromise ??= closeDebuggerServer(server);
|
|
3772
|
+
return closePromise;
|
|
3773
|
+
},
|
|
3774
|
+
host: activeHost,
|
|
3775
|
+
port,
|
|
3776
|
+
url: `http://${hostForUrl(activeHost)}:${port}/`,
|
|
3777
|
+
apiToken,
|
|
3778
|
+
apiTokenHeader: API_TOKEN_HEADER,
|
|
3779
|
+
requestedPort: preferredPort,
|
|
3780
|
+
portWasAutoSelected: port !== preferredPort,
|
|
3781
|
+
};
|
|
3782
|
+
}
|
|
3783
|
+
catch (error) {
|
|
3784
|
+
server.close();
|
|
3785
|
+
const err = error;
|
|
3786
|
+
if (strictPort || err.code !== 'EADDRINUSE') {
|
|
3787
|
+
throw error;
|
|
3788
|
+
}
|
|
3789
|
+
}
|
|
3790
|
+
}
|
|
3791
|
+
throw new Error(`No available port found in ${preferredPort}-${preferredPort + maxAttempts - 1}.`);
|
|
3792
|
+
}
|
|
3793
|
+
catch (error) {
|
|
3794
|
+
activeWebPreviewTarget = previousWebPreviewTarget;
|
|
3795
|
+
activeDebuggerTargetDiscovery = previousDebuggerTargetDiscovery;
|
|
3796
|
+
closeAssetWatchers();
|
|
3797
|
+
debuggerServerClosing = false;
|
|
3798
|
+
debuggerServerLifecycleActive = false;
|
|
3799
|
+
throw error;
|
|
3800
|
+
}
|
|
3801
|
+
}
|