@snap/valdi 1.1.7 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.metadata/.bazelrc.template +8 -2
- package/.metadata/MODULE.bazel.template +20 -3
- 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/README.md +35 -1
- 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-bazel/skill.md +2 -6
- package/bundled-skills/skills/valdi-cpp-runtime/skill.md +18 -0
- 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-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-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/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 +6 -5
- package/dist/commands/debugger.js +163 -0
- package/dist/commands/doctor.js +3 -62
- 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/projectsync.js +15 -0
- package/dist/commands/webHotreload.js +31 -0
- package/dist/core/constants.js +22 -6
- 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 +3 -0
- package/dist/utils/chromiumDevToolsClient.js +350 -0
- package/dist/utils/daemonClient.js +364 -44
- 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/stringUtils.js +13 -1
- 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,3329 @@
|
|
|
1
|
+
const query = new URLSearchParams(window.location.search);
|
|
2
|
+
const MAX_REGISTRY_CAPABILITIES = 32;
|
|
3
|
+
const MAX_REGISTRY_ENTRIES = 256;
|
|
4
|
+
const MAX_REGISTRY_ID_CHARACTERS = 512;
|
|
5
|
+
const MAX_REGISTRY_LABEL_CHARACTERS = 96;
|
|
6
|
+
const MAX_REGISTRY_LABEL_TOTAL_CHARACTERS = 180;
|
|
7
|
+
const MAX_CONSOLE_ENTRIES = 500;
|
|
8
|
+
const MAX_CONSOLE_ENTRY_CHARACTERS = 50_000;
|
|
9
|
+
const MAX_CONSOLE_HISTORY_ENTRIES = 100;
|
|
10
|
+
const MAX_PERFORMANCE_SAMPLES = 120;
|
|
11
|
+
const MAX_PERFORMANCE_TIMELINE_ROWS = 120;
|
|
12
|
+
const MAX_PERFORMANCE_SUMMARY_ROWS = 12;
|
|
13
|
+
const MAX_RUNTIME_STATE_CHARACTERS = 65_536;
|
|
14
|
+
const MAX_RUNTIME_STATE_COMPONENT_ROWS = 500;
|
|
15
|
+
const MAX_RUNTIME_STATE_CONTAINER_ENTRIES = 100;
|
|
16
|
+
const MAX_RUNTIME_STATE_DEPTH = 12;
|
|
17
|
+
const MAX_RUNTIME_STATE_KEY_CHARACTERS = 1_024;
|
|
18
|
+
const MAX_RUNTIME_STATE_TOKENS = 2_000;
|
|
19
|
+
const MAX_RUNTIME_STATE_VALUE_ROWS = 1_000;
|
|
20
|
+
const RUNTIME_STATE_SOURCE_NATIVE = 'native';
|
|
21
|
+
const RUNTIME_STATE_SOURCE_WEB = 'web';
|
|
22
|
+
const COMPONENT_PROPERTY_TOKEN_PATTERN = /^[0-9a-f]{32}$/;
|
|
23
|
+
const COMPONENT_PROPERTY_EDIT_ERROR = 'The component property edit is stale or invalid.';
|
|
24
|
+
const COMPONENT_PROPERTY_EDIT_PROTOCOL_VERSION = 1;
|
|
25
|
+
const SNAPSHOT_REFRESH_APPLIED = 'applied';
|
|
26
|
+
const SNAPSHOT_REFRESH_RUNTIME_STATE_DEFERRED = 'runtime-state-deferred';
|
|
27
|
+
const SNAPSHOT_REFRESH_SKIPPED = 'skipped';
|
|
28
|
+
const FORBIDDEN_COMPONENT_PROPERTY_NAMES = new Set(['__proto__', 'children', 'constructor', 'prototype']);
|
|
29
|
+
const componentPropertyEditorBindings = new WeakMap();
|
|
30
|
+
const runtimeStateInspectBindings = new WeakMap();
|
|
31
|
+
const runtimeStateParseCache = new WeakMap();
|
|
32
|
+
const MANUAL_WEB_CAPABILITIES = new Set([
|
|
33
|
+
'component-properties',
|
|
34
|
+
'components',
|
|
35
|
+
'console',
|
|
36
|
+
'highlight',
|
|
37
|
+
'performance',
|
|
38
|
+
'snapshot',
|
|
39
|
+
'storage',
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
function parseLaunchIdentity(searchParams) {
|
|
43
|
+
const targetIds = searchParams.getAll('targetId');
|
|
44
|
+
const inspectedUrls = searchParams.getAll('inspectedUrl');
|
|
45
|
+
const targetNonces = searchParams.getAll('targetNonce');
|
|
46
|
+
if (targetIds.length > 1 || inspectedUrls.length > 1 || targetNonces.length > 1) {
|
|
47
|
+
return { error: 'The DevTools URL contains a duplicated target identity.' };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const targetId = targetIds[0];
|
|
51
|
+
const inspectedPageUrl = inspectedUrls[0];
|
|
52
|
+
const targetNonce = targetNonces[0];
|
|
53
|
+
if (targetId !== undefined) {
|
|
54
|
+
if (
|
|
55
|
+
targetId.length === 0 ||
|
|
56
|
+
targetId.length > MAX_REGISTRY_ID_CHARACTERS ||
|
|
57
|
+
/[\u0000-\u001f\u007f]/.test(targetId) ||
|
|
58
|
+
inspectedPageUrl !== undefined ||
|
|
59
|
+
targetNonce !== undefined
|
|
60
|
+
) {
|
|
61
|
+
return { error: 'Direct DevTools requires one bounded targetId and no inspected-page identity.' };
|
|
62
|
+
}
|
|
63
|
+
return { mode: 'target-id', requestedTargetId: targetId };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (
|
|
67
|
+
inspectedPageUrl === undefined ||
|
|
68
|
+
inspectedPageUrl.length === 0 ||
|
|
69
|
+
targetNonce === undefined ||
|
|
70
|
+
targetNonce.length === 0
|
|
71
|
+
) {
|
|
72
|
+
return { error: 'Inspected-page DevTools requires both inspectedUrl and targetNonce.' };
|
|
73
|
+
}
|
|
74
|
+
return { inspectedUrl: inspectedPageUrl, mode: 'inspected-page', targetNonce };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const launchIdentity = parseLaunchIdentity(query);
|
|
78
|
+
const inspectedUrl = launchIdentity.mode === 'inspected-page' ? launchIdentity.inspectedUrl : null;
|
|
79
|
+
const inspectedTargetNonce = launchIdentity.mode === 'inspected-page' ? launchIdentity.targetNonce : null;
|
|
80
|
+
|
|
81
|
+
const state = {
|
|
82
|
+
target: null,
|
|
83
|
+
targetGeneration: 0,
|
|
84
|
+
targetSwitchMessage: null,
|
|
85
|
+
registryTargets: [],
|
|
86
|
+
registryError: null,
|
|
87
|
+
registryGeneration: 0,
|
|
88
|
+
registryRequestGeneration: 0,
|
|
89
|
+
registryPending: false,
|
|
90
|
+
connectionRequestGeneration: 0,
|
|
91
|
+
initialTargetResolutionPending: launchIdentity.mode === 'target-id',
|
|
92
|
+
unavailableTargetId: null,
|
|
93
|
+
snapshot: null,
|
|
94
|
+
activeSection: 'elements',
|
|
95
|
+
activeDetail: 'styles',
|
|
96
|
+
selectedNodeId: null,
|
|
97
|
+
remoteSelectedNodeId: null,
|
|
98
|
+
expandedNodeIds: new Set(),
|
|
99
|
+
search: '',
|
|
100
|
+
autoRefresh: true,
|
|
101
|
+
refreshTimer: null,
|
|
102
|
+
refreshPending: false,
|
|
103
|
+
snapshotRequestCompletion: null,
|
|
104
|
+
snapshotGeneration: 0,
|
|
105
|
+
snapshotRequestGeneration: 0,
|
|
106
|
+
hoveredNodeId: null,
|
|
107
|
+
hoveredSnapshotGeneration: 0,
|
|
108
|
+
highlightTimer: null,
|
|
109
|
+
highlightIntentGeneration: 0,
|
|
110
|
+
highlightMayBeActive: false,
|
|
111
|
+
highlightRequestTail: Promise.resolve(),
|
|
112
|
+
consoleEntries: [],
|
|
113
|
+
consoleEntryKeys: new Set(),
|
|
114
|
+
consoleHistory: [],
|
|
115
|
+
consoleHistoryIndex: 0,
|
|
116
|
+
consoleStream: null,
|
|
117
|
+
consoleStreamTargetKey: null,
|
|
118
|
+
performance: {
|
|
119
|
+
data: null,
|
|
120
|
+
durationSeconds: 3,
|
|
121
|
+
error: null,
|
|
122
|
+
lastTrace: null,
|
|
123
|
+
navigationExpanded: false,
|
|
124
|
+
operationGeneration: 0,
|
|
125
|
+
ownerIdentity: null,
|
|
126
|
+
pending: false,
|
|
127
|
+
rendererTracingEnabled: false,
|
|
128
|
+
requestGeneration: 0,
|
|
129
|
+
samples: [],
|
|
130
|
+
snapshotPending: false,
|
|
131
|
+
traceActive: false,
|
|
132
|
+
traceScope: 'valdi',
|
|
133
|
+
traceSearch: '',
|
|
134
|
+
},
|
|
135
|
+
componentPropertyEdit: {
|
|
136
|
+
error: null,
|
|
137
|
+
focused: false,
|
|
138
|
+
operationGeneration: 0,
|
|
139
|
+
pending: false,
|
|
140
|
+
},
|
|
141
|
+
runtimeState: {
|
|
142
|
+
expandedComponents: new Set(),
|
|
143
|
+
expandedInspectorValues: new Set(),
|
|
144
|
+
expandedMainValues: new Set(),
|
|
145
|
+
inspectGeneration: 0,
|
|
146
|
+
inspectorNodeId: null,
|
|
147
|
+
search: '',
|
|
148
|
+
},
|
|
149
|
+
error: null,
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const elements = {
|
|
153
|
+
mainTabs: Array.from(document.querySelectorAll('.main-tab')),
|
|
154
|
+
detailTabs: Array.from(document.querySelectorAll('.detail-tab')),
|
|
155
|
+
sections: Array.from(document.querySelectorAll('.section')),
|
|
156
|
+
targetStatusDot: document.getElementById('targetStatusDot'),
|
|
157
|
+
targetSelectLabel: document.getElementById('targetSelectLabel'),
|
|
158
|
+
targetSelect: document.getElementById('targetSelect'),
|
|
159
|
+
targetName: document.getElementById('targetName'),
|
|
160
|
+
targetMetadata: document.getElementById('targetMetadata'),
|
|
161
|
+
targetPickerStatus: document.getElementById('targetPickerStatus'),
|
|
162
|
+
autoRefreshToggle: document.getElementById('autoRefreshToggle'),
|
|
163
|
+
refreshButton: document.getElementById('refreshButton'),
|
|
164
|
+
treeFilter: document.getElementById('treeFilter'),
|
|
165
|
+
filterSummary: document.getElementById('filterSummary'),
|
|
166
|
+
tree: document.getElementById('tree'),
|
|
167
|
+
treeEmpty: document.getElementById('treeEmpty'),
|
|
168
|
+
expandButton: document.getElementById('expandButton'),
|
|
169
|
+
inspector: document.getElementById('inspector'),
|
|
170
|
+
copyNodeButton: document.getElementById('copyNodeButton'),
|
|
171
|
+
breadcrumbs: document.getElementById('breadcrumbs'),
|
|
172
|
+
nodeSummary: document.getElementById('nodeSummary'),
|
|
173
|
+
elementsSection: document.getElementById('elementsSection'),
|
|
174
|
+
splitHandle: document.getElementById('splitHandle'),
|
|
175
|
+
clearConsoleButton: document.getElementById('clearConsoleButton'),
|
|
176
|
+
consoleMessages: document.getElementById('consoleMessages'),
|
|
177
|
+
consoleForm: document.getElementById('consoleForm'),
|
|
178
|
+
consoleInput: document.getElementById('consoleInput'),
|
|
179
|
+
performanceContent: document.getElementById('performanceContent'),
|
|
180
|
+
stateContent: document.getElementById('stateContent'),
|
|
181
|
+
stateFilter: document.getElementById('stateFilter'),
|
|
182
|
+
stateSection: document.getElementById('stateSection'),
|
|
183
|
+
stateSummary: document.getElementById('stateSummary'),
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
function escapeHtml(value) {
|
|
187
|
+
return String(value ?? '')
|
|
188
|
+
.replaceAll('&', '&')
|
|
189
|
+
.replaceAll('<', '<')
|
|
190
|
+
.replaceAll('>', '>')
|
|
191
|
+
.replaceAll('"', '"')
|
|
192
|
+
.replaceAll("'", ''');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function applyTheme(theme) {
|
|
196
|
+
document.documentElement.dataset.theme = theme === 'dark' ? 'dark' : 'light';
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function requestJson(path, params, options) {
|
|
200
|
+
const url = new URL(path, window.location.origin);
|
|
201
|
+
for (const [key, value] of Object.entries(params)) {
|
|
202
|
+
if (value !== undefined && value !== null && value !== '') {
|
|
203
|
+
url.searchParams.set(key, String(value));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const response = await fetch(url, {
|
|
208
|
+
method: options.body ? 'POST' : 'GET',
|
|
209
|
+
cache: 'no-store',
|
|
210
|
+
headers: debuggerApiHeaders(options.body ? { 'Content-Type': 'application/json' } : {}),
|
|
211
|
+
...(options.body ? { body: JSON.stringify(options.body) } : {}),
|
|
212
|
+
});
|
|
213
|
+
const payload = await response.json();
|
|
214
|
+
if (!response.ok || payload.error) {
|
|
215
|
+
throw new Error(payload.error || `Request failed: ${response.status}`);
|
|
216
|
+
}
|
|
217
|
+
return payload;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function isDirectMode() {
|
|
221
|
+
return launchIdentity.mode === 'target-id';
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function targetCapabilities(target = state.target) {
|
|
225
|
+
if (Array.isArray(target?.capabilities)) return new Set(target.capabilities);
|
|
226
|
+
return launchIdentity.mode === 'inspected-page' ? MANUAL_WEB_CAPABILITIES : new Set();
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function targetSupports(capability, target = state.target) {
|
|
230
|
+
return Boolean(target && targetCapabilities(target).has(capability));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function targetIdentityParameters(target = state.target) {
|
|
234
|
+
if (!target) throw new Error('No debugger target is selected.');
|
|
235
|
+
if (isDirectMode()) return { targetId: target.id };
|
|
236
|
+
if (!target.sessionId || !inspectedUrl || !inspectedTargetNonce) {
|
|
237
|
+
throw new Error('The selected inspected page does not have a complete target identity.');
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
inspectedUrl,
|
|
241
|
+
sessionId: target.sessionId,
|
|
242
|
+
targetNonce: inspectedTargetNonce,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function targetIdentityKey(target = state.target) {
|
|
247
|
+
const identity = targetIdentityParameters(target);
|
|
248
|
+
return Object.keys(identity)
|
|
249
|
+
.sort()
|
|
250
|
+
.map(key => `${key}:${identity[key]}`)
|
|
251
|
+
.join('|');
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function targetOperationalKey(target) {
|
|
255
|
+
return `${targetIdentityKey(target)}|capabilities:${JSON.stringify(Array.from(targetCapabilities(target)).sort())}`;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function targetEventMatches(target, payload) {
|
|
259
|
+
if (!target || payload.targetId !== target.id) return false;
|
|
260
|
+
return isDirectMode() || payload.sessionId === target.sessionId;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function boundedRegistryLabel(value, fallback) {
|
|
264
|
+
if (typeof value !== 'string') return fallback;
|
|
265
|
+
const normalized = value
|
|
266
|
+
.slice(0, MAX_REGISTRY_LABEL_CHARACTERS * 2)
|
|
267
|
+
.replace(/[\u0000-\u001f\u007f]+/g, ' ')
|
|
268
|
+
.trim();
|
|
269
|
+
if (!normalized) return fallback;
|
|
270
|
+
const characters = Array.from(normalized);
|
|
271
|
+
return characters.length <= MAX_REGISTRY_LABEL_CHARACTERS
|
|
272
|
+
? normalized
|
|
273
|
+
: `${characters.slice(0, MAX_REGISTRY_LABEL_CHARACTERS - 1).join('')}…`;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function parseRegistryTarget(value) {
|
|
277
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
|
|
278
|
+
const id = value.id;
|
|
279
|
+
if (
|
|
280
|
+
typeof id !== 'string' ||
|
|
281
|
+
id.length === 0 ||
|
|
282
|
+
id.length > MAX_REGISTRY_ID_CHARACTERS ||
|
|
283
|
+
/[\u0000-\u001f\u007f]/.test(id) ||
|
|
284
|
+
typeof value.attachable !== 'boolean' ||
|
|
285
|
+
!['inspected-page', 'target-id'].includes(value.identityMode) ||
|
|
286
|
+
typeof value.transport !== 'string' ||
|
|
287
|
+
value.transport.length === 0 ||
|
|
288
|
+
value.transport.length > 64 ||
|
|
289
|
+
!Array.isArray(value.capabilities) ||
|
|
290
|
+
value.capabilities.length > MAX_REGISTRY_CAPABILITIES
|
|
291
|
+
) {
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const capabilities = [];
|
|
296
|
+
const seenCapabilities = new Set();
|
|
297
|
+
for (const capability of value.capabilities) {
|
|
298
|
+
if (
|
|
299
|
+
typeof capability !== 'string' ||
|
|
300
|
+
capability.length === 0 ||
|
|
301
|
+
capability.length > 64 ||
|
|
302
|
+
/[\u0000-\u001f\u007f]/.test(capability) ||
|
|
303
|
+
seenCapabilities.has(capability)
|
|
304
|
+
) {
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
seenCapabilities.add(capability);
|
|
308
|
+
capabilities.push(capability);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (value.state !== undefined && !['attached', 'available', 'waiting'].includes(value.state)) return null;
|
|
312
|
+
if (value.platform !== undefined && (typeof value.platform !== 'string' || value.platform.length > 32)) return null;
|
|
313
|
+
if (value.port !== undefined && (!Number.isSafeInteger(value.port) || value.port <= 0 || value.port > 65_535)) {
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
const name = boundedRegistryLabel(value.name, '');
|
|
317
|
+
return {
|
|
318
|
+
attachable: value.attachable,
|
|
319
|
+
capabilities,
|
|
320
|
+
id,
|
|
321
|
+
identityMode: value.identityMode,
|
|
322
|
+
name: name || boundedRegistryLabel(value.applicationId, 'Valdi target'),
|
|
323
|
+
platform: boundedRegistryLabel(value.platform, 'unknown'),
|
|
324
|
+
...(value.port === undefined ? {} : { port: value.port }),
|
|
325
|
+
state: value.state || 'available',
|
|
326
|
+
transport: value.transport,
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function parseTargetRegistry(payload) {
|
|
331
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload) || !Array.isArray(payload.targets)) {
|
|
332
|
+
throw new Error('The debugger target registry returned an invalid response.');
|
|
333
|
+
}
|
|
334
|
+
if (payload.targets.length > MAX_REGISTRY_ENTRIES) {
|
|
335
|
+
throw new Error(`The debugger target registry exceeded ${MAX_REGISTRY_ENTRIES} entries.`);
|
|
336
|
+
}
|
|
337
|
+
const targets = [];
|
|
338
|
+
const ids = new Set();
|
|
339
|
+
for (const value of payload.targets) {
|
|
340
|
+
const target = parseRegistryTarget(value);
|
|
341
|
+
if (!target) throw new Error('The debugger target registry contains a malformed entry.');
|
|
342
|
+
if (ids.has(target.id)) throw new Error(`The debugger target registry contains duplicate target IDs.`);
|
|
343
|
+
ids.add(target.id);
|
|
344
|
+
targets.push(target);
|
|
345
|
+
}
|
|
346
|
+
return targets;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function isSelectableDirectTarget(target) {
|
|
350
|
+
const capabilities = targetCapabilities(target);
|
|
351
|
+
return Boolean(
|
|
352
|
+
target.attachable &&
|
|
353
|
+
target.state !== 'waiting' &&
|
|
354
|
+
target.identityMode === 'target-id' &&
|
|
355
|
+
target.transport === 'valdi-daemon' &&
|
|
356
|
+
capabilities.has('components') &&
|
|
357
|
+
capabilities.has('snapshot'),
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function directTargetUnavailableReason(target) {
|
|
362
|
+
if (target.identityMode === 'inspected-page') return 'Open from the inspected page';
|
|
363
|
+
if (!target.attachable || target.state === 'waiting') return 'Waiting for application';
|
|
364
|
+
if (target.transport !== 'valdi-daemon') return 'Unsupported transport';
|
|
365
|
+
if (!targetSupports('components', target) || !targetSupports('snapshot', target)) {
|
|
366
|
+
return 'Component snapshots unavailable';
|
|
367
|
+
}
|
|
368
|
+
return 'Unavailable';
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function directTargetLabel(target) {
|
|
372
|
+
const metadata = [target.platform, target.port === undefined ? null : `:${target.port}`].filter(Boolean).join(' ');
|
|
373
|
+
const reason = isSelectableDirectTarget(target) ? '' : ` — ${directTargetUnavailableReason(target)}`;
|
|
374
|
+
const label = `${target.name}${metadata ? ` (${metadata})` : ''}${reason}`;
|
|
375
|
+
const characters = Array.from(label);
|
|
376
|
+
return characters.length <= MAX_REGISTRY_LABEL_TOTAL_CHARACTERS
|
|
377
|
+
? label
|
|
378
|
+
: `${characters.slice(0, MAX_REGISTRY_LABEL_TOTAL_CHARACTERS - 1).join('')}…`;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function appendTargetOption(value, label, options = {}) {
|
|
382
|
+
const option = document.createElement('option');
|
|
383
|
+
option.value = value;
|
|
384
|
+
option.textContent = label;
|
|
385
|
+
option.disabled = Boolean(options.disabled);
|
|
386
|
+
option.selected = Boolean(options.selected);
|
|
387
|
+
elements.targetSelect.append(option);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function setTargetPickerStatus(message) {
|
|
391
|
+
elements.targetPickerStatus.textContent = message || '';
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function renderTargetPicker() {
|
|
395
|
+
const direct = isDirectMode();
|
|
396
|
+
elements.targetSelect.hidden = !direct;
|
|
397
|
+
elements.targetSelectLabel.hidden = !direct;
|
|
398
|
+
elements.targetName.hidden = direct;
|
|
399
|
+
if (!direct) return;
|
|
400
|
+
|
|
401
|
+
elements.targetSelect.replaceChildren();
|
|
402
|
+
const selectedId = state.target?.id || null;
|
|
403
|
+
const unavailableTarget = state.unavailableTargetId
|
|
404
|
+
? state.registryTargets.find(target => target.id === state.unavailableTargetId)
|
|
405
|
+
: null;
|
|
406
|
+
appendTargetOption('', state.registryPending ? 'Loading debugger targets…' : 'Choose a debugger target', {
|
|
407
|
+
disabled: false,
|
|
408
|
+
selected: selectedId === null,
|
|
409
|
+
});
|
|
410
|
+
for (const target of state.registryTargets) {
|
|
411
|
+
appendTargetOption(target.id, directTargetLabel(target), {
|
|
412
|
+
disabled: !isSelectableDirectTarget(target),
|
|
413
|
+
selected: target.id === selectedId,
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
if (state.unavailableTargetId && !unavailableTarget) {
|
|
417
|
+
appendTargetOption(state.unavailableTargetId, 'Requested target is unavailable', { disabled: true });
|
|
418
|
+
}
|
|
419
|
+
elements.targetSelect.value = selectedId || '';
|
|
420
|
+
if (state.targetSwitchMessage) {
|
|
421
|
+
setTargetPickerStatus(state.targetSwitchMessage);
|
|
422
|
+
} else if (state.registryError) {
|
|
423
|
+
setTargetPickerStatus(state.registryError);
|
|
424
|
+
} else if (state.error) {
|
|
425
|
+
setTargetPickerStatus(state.error);
|
|
426
|
+
} else if (state.target) {
|
|
427
|
+
setTargetPickerStatus(`Connected to ${state.target.name}.`);
|
|
428
|
+
} else if (state.unavailableTargetId) {
|
|
429
|
+
setTargetPickerStatus(
|
|
430
|
+
unavailableTarget && isSelectableDirectTarget(unavailableTarget)
|
|
431
|
+
? 'The requested target is available. Select it to connect.'
|
|
432
|
+
: unavailableTarget
|
|
433
|
+
? directTargetUnavailableReason(unavailableTarget)
|
|
434
|
+
: 'The requested target is unavailable. Choose another target.',
|
|
435
|
+
);
|
|
436
|
+
} else {
|
|
437
|
+
setTargetPickerStatus('Choose a target. Targets are never selected automatically.');
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function stopPerformanceOnPageHide() {
|
|
442
|
+
const identity = state.performance.ownerIdentity;
|
|
443
|
+
if (!identity) return;
|
|
444
|
+
const url = new URL('/api/devtools/performance/trace/stop', window.location.origin);
|
|
445
|
+
for (const [key, value] of Object.entries(identity)) url.searchParams.set(key, String(value));
|
|
446
|
+
void fetch(url, {
|
|
447
|
+
body: '{}',
|
|
448
|
+
headers: debuggerApiHeaders({ 'Content-Type': 'application/json' }),
|
|
449
|
+
keepalive: true,
|
|
450
|
+
method: 'POST',
|
|
451
|
+
}).catch(error => console.warn('Unable to stop the web preview performance trace while closing DevTools.', error));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function formatNumber(value) {
|
|
455
|
+
const numeric = Number(value);
|
|
456
|
+
if (!Number.isFinite(numeric)) return '—';
|
|
457
|
+
return Number.isInteger(numeric)
|
|
458
|
+
? numeric.toLocaleString()
|
|
459
|
+
: numeric.toLocaleString(undefined, { maximumFractionDigits: 1 });
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function formatBytes(value) {
|
|
463
|
+
const numeric = Number(value);
|
|
464
|
+
if (!Number.isFinite(numeric) || numeric < 0) return '—';
|
|
465
|
+
if (numeric < 1024) return `${formatNumber(numeric)} B`;
|
|
466
|
+
if (numeric < 1024 * 1024) return `${formatNumber(numeric / 1024)} KiB`;
|
|
467
|
+
return `${formatNumber(numeric / (1024 * 1024))} MiB`;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function formatDuration(value) {
|
|
471
|
+
const numeric = Number(value);
|
|
472
|
+
if (!Number.isFinite(numeric) || numeric < 0) return '—';
|
|
473
|
+
if (numeric < 1) return `${formatNumber(numeric * 1000)} µs`;
|
|
474
|
+
if (numeric < 1000) return `${formatNumber(numeric)} ms`;
|
|
475
|
+
return `${formatNumber(numeric / 1000)} s`;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function formatUptime(value) {
|
|
479
|
+
const numeric = Number(value);
|
|
480
|
+
if (!Number.isFinite(numeric) || numeric < 0) return '—';
|
|
481
|
+
if (numeric < 60_000) return `${formatNumber(numeric / 1000)} s`;
|
|
482
|
+
return `${formatNumber(numeric / 60_000)} min`;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function performanceIdentity(target = state.target) {
|
|
486
|
+
if (!targetSupports('performance', target)) throw new Error('The selected target does not support Performance.');
|
|
487
|
+
return targetIdentityParameters(target);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function samePerformanceIdentity(left, right) {
|
|
491
|
+
if (!left || !right) return false;
|
|
492
|
+
if (left.targetId !== undefined || right.targetId !== undefined) {
|
|
493
|
+
return left.targetId !== undefined && left.targetId === right.targetId;
|
|
494
|
+
}
|
|
495
|
+
return (
|
|
496
|
+
left.sessionId === right.sessionId &&
|
|
497
|
+
left.inspectedUrl === right.inspectedUrl &&
|
|
498
|
+
left.targetNonce === right.targetNonce
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function performanceIdentityIsCurrent(identity) {
|
|
503
|
+
// This only rejects stale client-side responses. The server validates the
|
|
504
|
+
// complete session, inspected URL, and per-tab nonce on every request.
|
|
505
|
+
try {
|
|
506
|
+
return samePerformanceIdentity(identity, performanceIdentity());
|
|
507
|
+
} catch {
|
|
508
|
+
return false;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function performancePollingInputIsFocused() {
|
|
513
|
+
return ['performanceDurationInput', 'performanceTraceFilter'].includes(document.activeElement?.id);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function preparePerformanceForTargetChange() {
|
|
517
|
+
const perf = state.performance;
|
|
518
|
+
perf.requestGeneration++;
|
|
519
|
+
perf.operationGeneration++;
|
|
520
|
+
perf.snapshotPending = false;
|
|
521
|
+
perf.pending = false;
|
|
522
|
+
perf.data = null;
|
|
523
|
+
perf.lastTrace = null;
|
|
524
|
+
perf.navigationExpanded = false;
|
|
525
|
+
perf.rendererTracingEnabled = false;
|
|
526
|
+
perf.samples = [];
|
|
527
|
+
perf.traceScope = 'valdi';
|
|
528
|
+
perf.traceSearch = '';
|
|
529
|
+
if (perf.traceActive || perf.ownerIdentity) {
|
|
530
|
+
perf.error = 'The previous web preview still owns a performance recording. Stop and retrieve it before switching.';
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
perf.error = null;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function performanceBlocksTargetSwitch() {
|
|
537
|
+
const perf = state.performance;
|
|
538
|
+
return Boolean(perf.pending || perf.traceActive || perf.ownerIdentity);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function sectionIsAvailable(section) {
|
|
542
|
+
if (section === 'elements') return true;
|
|
543
|
+
if (section === 'state') return targetSupports('components') && targetSupports('snapshot');
|
|
544
|
+
if (section === 'console') return targetSupports('console');
|
|
545
|
+
if (section === 'performance') return targetSupports('performance') || Boolean(state.performance.ownerIdentity);
|
|
546
|
+
return false;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function updateCapabilityUi() {
|
|
550
|
+
for (const tab of elements.mainTabs) {
|
|
551
|
+
const available = sectionIsAvailable(tab.dataset.section);
|
|
552
|
+
tab.disabled = !available;
|
|
553
|
+
tab.setAttribute('aria-disabled', String(!available));
|
|
554
|
+
}
|
|
555
|
+
elements.consoleInput.disabled = !targetSupports('console');
|
|
556
|
+
elements.clearConsoleButton.disabled = !targetSupports('console');
|
|
557
|
+
elements.refreshButton.disabled = !state.target;
|
|
558
|
+
if (!sectionIsAvailable(state.activeSection)) setActiveSection('elements');
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function resetHighlightForTargetChange() {
|
|
562
|
+
state.highlightIntentGeneration++;
|
|
563
|
+
if (state.highlightTimer) window.clearTimeout(state.highlightTimer);
|
|
564
|
+
state.highlightTimer = null;
|
|
565
|
+
state.hoveredNodeId = null;
|
|
566
|
+
state.hoveredSnapshotGeneration = 0;
|
|
567
|
+
state.highlightMayBeActive = false;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function enqueueExactHighlightClear(target) {
|
|
571
|
+
if (!target || !targetSupports('highlight', target) || !state.highlightMayBeActive) return;
|
|
572
|
+
const identity = targetIdentityParameters(target);
|
|
573
|
+
const request = state.highlightRequestTail.then(() =>
|
|
574
|
+
requestJson('/api/devtools/highlight', {}, { body: identity }).catch(error => {
|
|
575
|
+
console.warn('Unable to clear the previous Valdi target highlight.', error);
|
|
576
|
+
}),
|
|
577
|
+
);
|
|
578
|
+
state.highlightRequestTail = request.catch(error => {
|
|
579
|
+
console.warn('Unable to order the previous Valdi target highlight clear.', error);
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function resetConsoleForTargetChange() {
|
|
584
|
+
clearConsole();
|
|
585
|
+
state.consoleHistory = [];
|
|
586
|
+
state.consoleHistoryIndex = 0;
|
|
587
|
+
elements.consoleInput.value = '';
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function resetComponentPropertyEditForTargetChange() {
|
|
591
|
+
state.componentPropertyEdit.operationGeneration++;
|
|
592
|
+
state.componentPropertyEdit.pending = false;
|
|
593
|
+
state.componentPropertyEdit.focused = false;
|
|
594
|
+
state.componentPropertyEdit.error = null;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function resetRuntimeStateForTargetChange() {
|
|
598
|
+
const runtimeState = state.runtimeState;
|
|
599
|
+
runtimeState.inspectGeneration++;
|
|
600
|
+
runtimeState.inspectorNodeId = null;
|
|
601
|
+
runtimeState.search = '';
|
|
602
|
+
runtimeState.expandedComponents.clear();
|
|
603
|
+
runtimeState.expandedInspectorValues.clear();
|
|
604
|
+
runtimeState.expandedMainValues.clear();
|
|
605
|
+
if (elements.stateFilter) elements.stateFilter.value = '';
|
|
606
|
+
if (elements.stateSummary) elements.stateSummary.textContent = '';
|
|
607
|
+
if (elements.stateContent) elements.stateContent.innerHTML = '';
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function resetRuntimeStateForSelectionChange(selectedNodeId) {
|
|
611
|
+
if (state.runtimeState.inspectorNodeId === selectedNodeId) return;
|
|
612
|
+
state.runtimeState.inspectGeneration++;
|
|
613
|
+
state.runtimeState.inspectorNodeId = selectedNodeId;
|
|
614
|
+
state.runtimeState.expandedInspectorValues.clear();
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function clearTargetPresentation(message) {
|
|
618
|
+
state.snapshotRequestGeneration++;
|
|
619
|
+
state.refreshPending = false;
|
|
620
|
+
state.snapshotRequestCompletion = null;
|
|
621
|
+
state.snapshot = null;
|
|
622
|
+
state.snapshotGeneration++;
|
|
623
|
+
state.selectedNodeId = null;
|
|
624
|
+
state.remoteSelectedNodeId = null;
|
|
625
|
+
state.expandedNodeIds.clear();
|
|
626
|
+
resetHighlightForTargetChange();
|
|
627
|
+
resetConsoleForTargetChange();
|
|
628
|
+
resetComponentPropertyEditForTargetChange();
|
|
629
|
+
resetRuntimeStateForTargetChange();
|
|
630
|
+
preparePerformanceForTargetChange();
|
|
631
|
+
elements.treeEmpty.textContent = message;
|
|
632
|
+
render();
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function applyDirectTargetSelection(nextTarget, options = {}) {
|
|
636
|
+
const currentId = state.target?.id || null;
|
|
637
|
+
const nextId = nextTarget?.id || null;
|
|
638
|
+
if (currentId !== null && currentId === nextId && !options.force) {
|
|
639
|
+
state.targetSwitchMessage = null;
|
|
640
|
+
renderTargetPicker();
|
|
641
|
+
return true;
|
|
642
|
+
}
|
|
643
|
+
if (!options.force && performanceBlocksTargetSwitch()) {
|
|
644
|
+
state.targetSwitchMessage = 'Stop or finish the current Performance operation before switching debugger targets.';
|
|
645
|
+
renderTargetPicker();
|
|
646
|
+
return false;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
stopConsoleStream();
|
|
650
|
+
enqueueExactHighlightClear(state.target);
|
|
651
|
+
state.targetGeneration++;
|
|
652
|
+
clearTargetPresentation(nextTarget ? 'Loading the selected target…' : 'Choose a debugger target to inspect.');
|
|
653
|
+
state.target = nextTarget;
|
|
654
|
+
state.unavailableTargetId = options.unavailableTargetId || null;
|
|
655
|
+
state.targetSwitchMessage = options.message || null;
|
|
656
|
+
state.error = nextTarget
|
|
657
|
+
? null
|
|
658
|
+
: options.unavailableTargetId
|
|
659
|
+
? options.message || 'The selected target is unavailable.'
|
|
660
|
+
: null;
|
|
661
|
+
if (nextTarget) {
|
|
662
|
+
elements.targetMetadata.textContent = [
|
|
663
|
+
nextTarget.platform,
|
|
664
|
+
nextTarget.port === undefined ? null : `:${nextTarget.port}`,
|
|
665
|
+
]
|
|
666
|
+
.filter(Boolean)
|
|
667
|
+
.join(' · ');
|
|
668
|
+
setConnected(true);
|
|
669
|
+
} else {
|
|
670
|
+
elements.targetMetadata.textContent = '';
|
|
671
|
+
setConnected(false);
|
|
672
|
+
}
|
|
673
|
+
updateCapabilityUi();
|
|
674
|
+
if (state.activeSection === 'performance') renderPerformance();
|
|
675
|
+
renderTargetPicker();
|
|
676
|
+
if (nextTarget) {
|
|
677
|
+
startConsoleStream();
|
|
678
|
+
void refreshSnapshot();
|
|
679
|
+
}
|
|
680
|
+
return true;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function nodeAttributes(node) {
|
|
684
|
+
return valdiDebuggerTreeModel.attributes(node);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
function nodeId(node) {
|
|
688
|
+
return valdiDebuggerTreeModel.id(node);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
function inspectedNodeId(node) {
|
|
692
|
+
if (!node) return null;
|
|
693
|
+
if (node.component) {
|
|
694
|
+
return node.component.elementId === undefined ? null : String(node.component.elementId);
|
|
695
|
+
}
|
|
696
|
+
return nodeId(node);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
function inspectedNode(node) {
|
|
700
|
+
const id = inspectedNodeId(node);
|
|
701
|
+
return id === null ? node : findNode(id) || node;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
function treeRowId(id) {
|
|
705
|
+
return `valdi-tree-node-${encodeURIComponent(id)}`;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function nodeText(node) {
|
|
709
|
+
const attributes = nodeAttributes(node);
|
|
710
|
+
const candidates = [attributes.accessibilityLabel, node?.element?.dom?.textContent, attributes.value];
|
|
711
|
+
for (const candidate of candidates) {
|
|
712
|
+
if (candidate === undefined || candidate === null || candidate === '') continue;
|
|
713
|
+
const formatted = valdiDebuggerTreeModel.formatValue(candidate, 0).trim();
|
|
714
|
+
if (formatted) return formatted;
|
|
715
|
+
}
|
|
716
|
+
return '';
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function walk(node, callback) {
|
|
720
|
+
valdiDebuggerTreeModel.walk(node, callback, [], 0);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function walkVisible(node, callback) {
|
|
724
|
+
valdiDebuggerTreeModel.walkVisible(node, callback, current => state.expandedNodeIds.has(nodeId(current)), [], 0);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function nodeCount() {
|
|
728
|
+
let count = 0;
|
|
729
|
+
walk(state.snapshot?.tree, () => count++);
|
|
730
|
+
return count;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function findNode(id) {
|
|
734
|
+
return valdiDebuggerTreeModel.findNode(state.snapshot?.tree, id);
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
function findNodePath(id) {
|
|
738
|
+
return valdiDebuggerTreeModel.pathToNode(state.snapshot?.tree, id);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
function selectedNodeProjectionJson() {
|
|
742
|
+
const node = findNode(state.selectedNodeId);
|
|
743
|
+
return node ? JSON.stringify(valdiDebuggerTreeModel.projectTree(node), null, 2) : null;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
function chooseInitialNode(root) {
|
|
747
|
+
let selected = null;
|
|
748
|
+
walk(root, node => {
|
|
749
|
+
const attributes = nodeAttributes(node);
|
|
750
|
+
if (attributes.accessibilityId || attributes.accessibilityLabel || typeof attributes.value === 'string') {
|
|
751
|
+
selected = node;
|
|
752
|
+
return false;
|
|
753
|
+
}
|
|
754
|
+
return true;
|
|
755
|
+
});
|
|
756
|
+
return selected || root;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
function revealPath(id) {
|
|
760
|
+
const path = findNodePath(id);
|
|
761
|
+
for (const node of path.slice(0, -1)) {
|
|
762
|
+
state.expandedNodeIds.add(nodeId(node));
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function expandUsefulNodes(root) {
|
|
767
|
+
if (!root) return;
|
|
768
|
+
let current = root;
|
|
769
|
+
let depth = 0;
|
|
770
|
+
while (current && depth < 8) {
|
|
771
|
+
state.expandedNodeIds.add(nodeId(current));
|
|
772
|
+
const children = valdiDebuggerTreeModel.children(current);
|
|
773
|
+
if (children.length !== 1) break;
|
|
774
|
+
current = children[0];
|
|
775
|
+
depth++;
|
|
776
|
+
}
|
|
777
|
+
for (const child of valdiDebuggerTreeModel.children(current)) {
|
|
778
|
+
if (valdiDebuggerTreeModel.hasChildren(child) && depth < 5) {
|
|
779
|
+
state.expandedNodeIds.add(nodeId(child));
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
function setConnected(connected, message) {
|
|
785
|
+
elements.targetStatusDot.className = `status-dot${connected ? '' : state.error ? ' error' : ' connecting'}`;
|
|
786
|
+
if (message) {
|
|
787
|
+
if (isDirectMode()) setTargetPickerStatus(message);
|
|
788
|
+
else elements.targetName.textContent = message;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
function reportError(error) {
|
|
793
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
794
|
+
state.error = message;
|
|
795
|
+
setConnected(false, message);
|
|
796
|
+
elements.treeEmpty.textContent = message;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
async function refreshTargetRegistry() {
|
|
800
|
+
if (!isDirectMode() || state.registryPending) return;
|
|
801
|
+
state.registryPending = true;
|
|
802
|
+
const requestGeneration = ++state.registryRequestGeneration;
|
|
803
|
+
renderTargetPicker();
|
|
804
|
+
try {
|
|
805
|
+
const payload = await requestJson('/api/devtools/targets', {}, {});
|
|
806
|
+
if (requestGeneration !== state.registryRequestGeneration) return;
|
|
807
|
+
const targets = parseTargetRegistry(payload);
|
|
808
|
+
state.registryTargets = targets;
|
|
809
|
+
state.registryGeneration++;
|
|
810
|
+
state.registryError = null;
|
|
811
|
+
if (!state.target) state.error = null;
|
|
812
|
+
|
|
813
|
+
if (state.initialTargetResolutionPending) {
|
|
814
|
+
state.initialTargetResolutionPending = false;
|
|
815
|
+
const requestedId = launchIdentity.requestedTargetId;
|
|
816
|
+
const requestedTarget = targets.find(target => target.id === requestedId);
|
|
817
|
+
if (requestedTarget && isSelectableDirectTarget(requestedTarget)) {
|
|
818
|
+
state.unavailableTargetId = null;
|
|
819
|
+
applyDirectTargetSelection(requestedTarget, { force: true });
|
|
820
|
+
} else {
|
|
821
|
+
state.unavailableTargetId = requestedId;
|
|
822
|
+
state.error = 'The requested target is unavailable.';
|
|
823
|
+
updateCapabilityUi();
|
|
824
|
+
setConnected(false);
|
|
825
|
+
}
|
|
826
|
+
} else if (state.target) {
|
|
827
|
+
const refreshedTarget = targets.find(target => target.id === state.target.id);
|
|
828
|
+
if (!refreshedTarget || !isSelectableDirectTarget(refreshedTarget)) {
|
|
829
|
+
const unavailableTargetId = state.target.id;
|
|
830
|
+
applyDirectTargetSelection(null, {
|
|
831
|
+
force: true,
|
|
832
|
+
message: 'The selected target is no longer available. Choose another target.',
|
|
833
|
+
unavailableTargetId,
|
|
834
|
+
});
|
|
835
|
+
} else {
|
|
836
|
+
const previousTarget = state.target;
|
|
837
|
+
const targetChanged = targetOperationalKey(previousTarget) !== targetOperationalKey(refreshedTarget);
|
|
838
|
+
if (targetChanged) {
|
|
839
|
+
stopConsoleStream();
|
|
840
|
+
enqueueExactHighlightClear(previousTarget);
|
|
841
|
+
state.targetGeneration++;
|
|
842
|
+
clearTargetPresentation('Refreshing the selected target…');
|
|
843
|
+
}
|
|
844
|
+
state.target = refreshedTarget;
|
|
845
|
+
elements.targetMetadata.textContent = [
|
|
846
|
+
refreshedTarget.platform,
|
|
847
|
+
refreshedTarget.port === undefined ? null : `:${refreshedTarget.port}`,
|
|
848
|
+
]
|
|
849
|
+
.filter(Boolean)
|
|
850
|
+
.join(' · ');
|
|
851
|
+
updateCapabilityUi();
|
|
852
|
+
if (state.activeSection === 'performance') renderPerformance();
|
|
853
|
+
if (targetChanged) {
|
|
854
|
+
startConsoleStream();
|
|
855
|
+
void refreshSnapshot();
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
if (!state.target) setConnected(false);
|
|
860
|
+
renderTargetPicker();
|
|
861
|
+
} catch (error) {
|
|
862
|
+
if (requestGeneration !== state.registryRequestGeneration) return;
|
|
863
|
+
state.registryError = error instanceof Error ? error.message : String(error);
|
|
864
|
+
if (!state.target) {
|
|
865
|
+
state.error = state.registryError;
|
|
866
|
+
setConnected(false);
|
|
867
|
+
}
|
|
868
|
+
renderTargetPicker();
|
|
869
|
+
} finally {
|
|
870
|
+
if (requestGeneration === state.registryRequestGeneration) {
|
|
871
|
+
state.registryPending = false;
|
|
872
|
+
renderTargetPicker();
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
async function connectToInspectedPage() {
|
|
878
|
+
const connectionGeneration = ++state.connectionRequestGeneration;
|
|
879
|
+
|
|
880
|
+
try {
|
|
881
|
+
const payload = await requestJson('/api/devtools/target', { inspectedUrl, targetNonce: inspectedTargetNonce }, {});
|
|
882
|
+
if (connectionGeneration !== state.connectionRequestGeneration) return;
|
|
883
|
+
const previousTargetKey = state.target
|
|
884
|
+
? `${state.target.id}:${state.target.sessionId}:${inspectedTargetNonce}`
|
|
885
|
+
: null;
|
|
886
|
+
const nextTargetKey = `${payload.target.id}:${payload.target.sessionId}:${inspectedTargetNonce}`;
|
|
887
|
+
if (previousTargetKey !== null && previousTargetKey !== nextTargetKey) {
|
|
888
|
+
stopConsoleStream();
|
|
889
|
+
enqueueExactHighlightClear(state.target);
|
|
890
|
+
resetConsoleForTargetChange();
|
|
891
|
+
resetComponentPropertyEditForTargetChange();
|
|
892
|
+
resetRuntimeStateForTargetChange();
|
|
893
|
+
preparePerformanceForTargetChange();
|
|
894
|
+
state.snapshotRequestGeneration++;
|
|
895
|
+
state.refreshPending = false;
|
|
896
|
+
state.snapshotRequestCompletion = null;
|
|
897
|
+
state.snapshot = null;
|
|
898
|
+
state.snapshotGeneration++;
|
|
899
|
+
state.selectedNodeId = null;
|
|
900
|
+
state.remoteSelectedNodeId = null;
|
|
901
|
+
state.expandedNodeIds.clear();
|
|
902
|
+
resetHighlightForTargetChange();
|
|
903
|
+
render();
|
|
904
|
+
}
|
|
905
|
+
if (previousTargetKey !== nextTargetKey) state.targetGeneration++;
|
|
906
|
+
state.target = payload.target;
|
|
907
|
+
if (previousTargetKey !== null && previousTargetKey !== nextTargetKey) render();
|
|
908
|
+
elements.targetName.textContent = state.target.name || 'Valdi application';
|
|
909
|
+
elements.targetName.title = state.target.applicationUrl || inspectedUrl;
|
|
910
|
+
elements.targetMetadata.textContent = `Chromium · :${state.target.debuggingPort}`;
|
|
911
|
+
renderTargetPicker();
|
|
912
|
+
updateCapabilityUi();
|
|
913
|
+
if (state.activeSection === 'performance') renderPerformance();
|
|
914
|
+
setConnected(true);
|
|
915
|
+
if (previousTargetKey !== nextTargetKey) {
|
|
916
|
+
addConsoleEntry('info', `Connected to ${state.target.applicationUrl}`);
|
|
917
|
+
}
|
|
918
|
+
startConsoleStream();
|
|
919
|
+
await refreshSnapshot();
|
|
920
|
+
startRefreshTimer();
|
|
921
|
+
} catch (error) {
|
|
922
|
+
if (connectionGeneration !== state.connectionRequestGeneration) return;
|
|
923
|
+
reportError(error);
|
|
924
|
+
window.setTimeout(connectToInspectedPage, 1500);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
async function connectToInspectedApplication() {
|
|
929
|
+
renderTargetPicker();
|
|
930
|
+
updateCapabilityUi();
|
|
931
|
+
if (launchIdentity.error) {
|
|
932
|
+
state.error = launchIdentity.error;
|
|
933
|
+
setConnected(false, state.error);
|
|
934
|
+
elements.treeEmpty.textContent = state.error;
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
if (isDirectMode()) {
|
|
938
|
+
await refreshTargetRegistry();
|
|
939
|
+
startRefreshTimer();
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
await connectToInspectedPage();
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
async function refreshSnapshot() {
|
|
946
|
+
await refreshSnapshotInternal(null);
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
function runtimeStatePresentationHasFocus() {
|
|
950
|
+
const activeElement = document.activeElement;
|
|
951
|
+
if (!activeElement) return false;
|
|
952
|
+
if (elements.stateSection?.contains(activeElement)) return true;
|
|
953
|
+
return state.activeDetail === 'state' && elements.inspector?.contains(activeElement);
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
async function refreshSnapshotInternal(componentPropertyEditOperationGeneration) {
|
|
957
|
+
const componentPropertyEditOwnsRefresh = () =>
|
|
958
|
+
componentPropertyEditOperationGeneration !== null &&
|
|
959
|
+
state.componentPropertyEdit.operationGeneration === componentPropertyEditOperationGeneration &&
|
|
960
|
+
state.componentPropertyEdit.pending;
|
|
961
|
+
const refreshIsAllowed = () =>
|
|
962
|
+
state.target &&
|
|
963
|
+
targetSupports('components') &&
|
|
964
|
+
targetSupports('snapshot') &&
|
|
965
|
+
((!state.componentPropertyEdit.focused && !state.componentPropertyEdit.pending) ||
|
|
966
|
+
componentPropertyEditOwnsRefresh()) &&
|
|
967
|
+
!runtimeStatePresentationHasFocus();
|
|
968
|
+
if (!refreshIsAllowed()) {
|
|
969
|
+
return runtimeStatePresentationHasFocus() ? SNAPSHOT_REFRESH_RUNTIME_STATE_DEFERRED : SNAPSHOT_REFRESH_SKIPPED;
|
|
970
|
+
}
|
|
971
|
+
if (state.refreshPending) {
|
|
972
|
+
const activeRequestCompletion = state.snapshotRequestCompletion;
|
|
973
|
+
if (!componentPropertyEditOwnsRefresh() || activeRequestCompletion === null) {
|
|
974
|
+
return SNAPSHOT_REFRESH_SKIPPED;
|
|
975
|
+
}
|
|
976
|
+
await activeRequestCompletion;
|
|
977
|
+
if (!refreshIsAllowed() || state.refreshPending) {
|
|
978
|
+
return runtimeStatePresentationHasFocus() ? SNAPSHOT_REFRESH_RUNTIME_STATE_DEFERRED : SNAPSHOT_REFRESH_SKIPPED;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
state.refreshPending = true;
|
|
982
|
+
let resolveRequestCompletion;
|
|
983
|
+
const requestCompletion = new Promise(resolve => {
|
|
984
|
+
resolveRequestCompletion = resolve;
|
|
985
|
+
});
|
|
986
|
+
state.snapshotRequestCompletion = requestCompletion;
|
|
987
|
+
const requestTarget = state.target;
|
|
988
|
+
const requestTargetGeneration = state.targetGeneration;
|
|
989
|
+
const requestGeneration = ++state.snapshotRequestGeneration;
|
|
990
|
+
const requestIsCurrent = () =>
|
|
991
|
+
state.targetGeneration === requestTargetGeneration &&
|
|
992
|
+
state.target?.id === requestTarget.id &&
|
|
993
|
+
state.snapshotRequestGeneration === requestGeneration;
|
|
994
|
+
try {
|
|
995
|
+
const snapshot = await requestJson('/api/devtools/snapshot', targetIdentityParameters(requestTarget), {});
|
|
996
|
+
if (!requestIsCurrent()) return SNAPSHOT_REFRESH_SKIPPED;
|
|
997
|
+
if (runtimeStatePresentationHasFocus()) return SNAPSHOT_REFRESH_RUNTIME_STATE_DEFERRED;
|
|
998
|
+
if (
|
|
999
|
+
(state.componentPropertyEdit.focused || state.componentPropertyEdit.pending) &&
|
|
1000
|
+
!componentPropertyEditOwnsRefresh()
|
|
1001
|
+
) {
|
|
1002
|
+
return SNAPSHOT_REFRESH_SKIPPED;
|
|
1003
|
+
}
|
|
1004
|
+
if (
|
|
1005
|
+
snapshot.target?.id === requestTarget.id &&
|
|
1006
|
+
Array.isArray(snapshot.target.capabilities) &&
|
|
1007
|
+
snapshot.target.capabilities.length <= MAX_REGISTRY_CAPABILITIES &&
|
|
1008
|
+
snapshot.target.capabilities.every(capability => typeof capability === 'string' && capability.length <= 64)
|
|
1009
|
+
) {
|
|
1010
|
+
state.target = { ...requestTarget, capabilities: [...snapshot.target.capabilities] };
|
|
1011
|
+
updateCapabilityUi();
|
|
1012
|
+
}
|
|
1013
|
+
snapshot.tree = valdiDebuggerTreeModel.restoreTree(snapshot.tree);
|
|
1014
|
+
const wasEmpty = !state.snapshot?.tree;
|
|
1015
|
+
const previousSelectedNodeId = state.selectedNodeId;
|
|
1016
|
+
const shouldClearHighlight = state.hoveredNodeId !== null || state.highlightMayBeActive;
|
|
1017
|
+
state.snapshot = snapshot;
|
|
1018
|
+
state.runtimeState.inspectGeneration++;
|
|
1019
|
+
state.componentPropertyEdit.error = null;
|
|
1020
|
+
state.snapshotGeneration++;
|
|
1021
|
+
if (state.highlightTimer) window.clearTimeout(state.highlightTimer);
|
|
1022
|
+
state.highlightTimer = null;
|
|
1023
|
+
state.hoveredNodeId = null;
|
|
1024
|
+
state.hoveredSnapshotGeneration = state.snapshotGeneration - 1;
|
|
1025
|
+
if (shouldClearHighlight) queueHighlight(null);
|
|
1026
|
+
state.error = null;
|
|
1027
|
+
setConnected(true);
|
|
1028
|
+
renderTargetPicker();
|
|
1029
|
+
|
|
1030
|
+
if (wasEmpty) {
|
|
1031
|
+
expandUsefulNodes(snapshot.tree);
|
|
1032
|
+
state.selectedNodeId = nodeId(chooseInitialNode(snapshot.tree));
|
|
1033
|
+
revealPath(state.selectedNodeId);
|
|
1034
|
+
}
|
|
1035
|
+
if (snapshot.selectedNodeId && snapshot.selectedNodeId !== state.remoteSelectedNodeId) {
|
|
1036
|
+
state.remoteSelectedNodeId = String(snapshot.selectedNodeId);
|
|
1037
|
+
state.selectedNodeId = state.remoteSelectedNodeId;
|
|
1038
|
+
revealPath(state.selectedNodeId);
|
|
1039
|
+
}
|
|
1040
|
+
if (!findNode(state.selectedNodeId)) {
|
|
1041
|
+
state.selectedNodeId = nodeId(chooseInitialNode(snapshot.tree));
|
|
1042
|
+
revealPath(state.selectedNodeId);
|
|
1043
|
+
}
|
|
1044
|
+
if (state.selectedNodeId !== previousSelectedNodeId) {
|
|
1045
|
+
resetRuntimeStateForSelectionChange(state.selectedNodeId);
|
|
1046
|
+
}
|
|
1047
|
+
render();
|
|
1048
|
+
return SNAPSHOT_REFRESH_APPLIED;
|
|
1049
|
+
} catch (error) {
|
|
1050
|
+
if (requestIsCurrent()) reportError(error);
|
|
1051
|
+
return SNAPSHOT_REFRESH_SKIPPED;
|
|
1052
|
+
} finally {
|
|
1053
|
+
if (state.snapshotRequestCompletion === requestCompletion) {
|
|
1054
|
+
state.snapshotRequestCompletion = null;
|
|
1055
|
+
state.refreshPending = false;
|
|
1056
|
+
}
|
|
1057
|
+
resolveRequestCompletion();
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
function startRefreshTimer() {
|
|
1062
|
+
if (state.refreshTimer) window.clearInterval(state.refreshTimer);
|
|
1063
|
+
state.refreshTimer = window.setInterval(() => {
|
|
1064
|
+
if (document.hidden) return;
|
|
1065
|
+
if (isDirectMode()) void refreshTargetRegistry();
|
|
1066
|
+
if (!state.autoRefresh) return;
|
|
1067
|
+
if (state.componentPropertyEdit.focused || state.componentPropertyEdit.pending) return;
|
|
1068
|
+
if (runtimeStatePresentationHasFocus()) return;
|
|
1069
|
+
if (state.activeSection === 'elements' || state.activeSection === 'state') void refreshSnapshot();
|
|
1070
|
+
if (state.activeSection === 'performance') void refreshPerformance({ silent: true });
|
|
1071
|
+
}, 1200);
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
function visibleSearchIds(root, search) {
|
|
1075
|
+
const ids = new Set();
|
|
1076
|
+
const normalized = search.toLowerCase();
|
|
1077
|
+
const records = [];
|
|
1078
|
+
walk(root, (node, ancestors) => {
|
|
1079
|
+
const metadata = valdiDebuggerTreeModel.stringifyValue(nodeAttributes(node), 0);
|
|
1080
|
+
const text = `${node.tag} ${nodeText(node)} ${metadata}`.toLowerCase();
|
|
1081
|
+
records.push({ matched: text.includes(normalized), node, parent: ancestors.at(-1) });
|
|
1082
|
+
});
|
|
1083
|
+
const matchedSubtrees = new Set();
|
|
1084
|
+
for (let index = records.length - 1; index >= 0; index -= 1) {
|
|
1085
|
+
const record = records[index];
|
|
1086
|
+
if (!record.matched && !matchedSubtrees.has(record.node)) continue;
|
|
1087
|
+
ids.add(nodeId(record.node));
|
|
1088
|
+
if (record.parent) matchedSubtrees.add(record.parent);
|
|
1089
|
+
}
|
|
1090
|
+
return ids;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
function selectedAttribute(node) {
|
|
1094
|
+
const attributes = nodeAttributes(node);
|
|
1095
|
+
if (attributes.accessibilityId) {
|
|
1096
|
+
return ['id', valdiDebuggerTreeModel.formatValue(attributes.accessibilityId, 0)];
|
|
1097
|
+
}
|
|
1098
|
+
if (attributes.accessibilityCategory && attributes.accessibilityCategory !== 'view') {
|
|
1099
|
+
return ['role', valdiDebuggerTreeModel.formatValue(attributes.accessibilityCategory, 0)];
|
|
1100
|
+
}
|
|
1101
|
+
if (attributes.onTap || attributes.touchEnabled) return ['interactive', 'true'];
|
|
1102
|
+
return null;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
function renderTree() {
|
|
1106
|
+
const root = state.snapshot?.tree;
|
|
1107
|
+
if (!root) {
|
|
1108
|
+
elements.tree.innerHTML = '';
|
|
1109
|
+
elements.tree.removeAttribute('aria-activedescendant');
|
|
1110
|
+
elements.filterSummary.textContent = '';
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
const search = state.search.trim();
|
|
1115
|
+
const visibleIds = search ? visibleSearchIds(root, search) : null;
|
|
1116
|
+
const rows = [];
|
|
1117
|
+
let matches = 0;
|
|
1118
|
+
const normalizedSearch = search.toLowerCase();
|
|
1119
|
+
const traversal = search ? walk : walkVisible;
|
|
1120
|
+
traversal(root, (node, _ancestors, depth) => {
|
|
1121
|
+
const id = nodeId(node);
|
|
1122
|
+
if (visibleIds && !visibleIds.has(id)) return;
|
|
1123
|
+
const hasChildren = valdiDebuggerTreeModel.hasChildren(node);
|
|
1124
|
+
const expanded = Boolean(search) || state.expandedNodeIds.has(id);
|
|
1125
|
+
const selected = id === state.selectedNodeId;
|
|
1126
|
+
const attribute = selectedAttribute(node);
|
|
1127
|
+
const text = nodeText(node);
|
|
1128
|
+
const attributes = nodeAttributes(node);
|
|
1129
|
+
const serializedAttributes = valdiDebuggerTreeModel.stringifyValue(attributes, 0);
|
|
1130
|
+
if (!search || `${node.tag} ${text} ${serializedAttributes}`.toLowerCase().includes(normalizedSearch)) {
|
|
1131
|
+
matches++;
|
|
1132
|
+
}
|
|
1133
|
+
rows.push(`
|
|
1134
|
+
<div id="${escapeHtml(treeRowId(id))}" class="tree-row${node.component ? ' component-row' : ''}${selected ? ' selected' : ''}" data-node-id="${escapeHtml(id)}" role="treeitem" aria-level="${depth + 1}" aria-selected="${selected}"${hasChildren ? ` aria-expanded="${expanded}"` : ''} style="padding-left:${depth * 13 + 2}px">
|
|
1135
|
+
<button class="disclosure${hasChildren ? '' : ' empty'}" data-toggle-id="${escapeHtml(id)}" tabindex="-1" aria-label="${expanded ? 'Collapse' : 'Expand'}">${expanded ? '▾' : '▸'}</button>
|
|
1136
|
+
<span class="tag-bracket"><</span><span class="tag-name">${escapeHtml(node.tag || 'view')}</span>
|
|
1137
|
+
${attribute ? `<span class="attribute-name">${escapeHtml(attribute[0])}</span>=<span class="attribute-value">"${escapeHtml(attribute[1])}"</span>` : ''}<span class="tag-bracket">></span>
|
|
1138
|
+
${text ? `<span class="tree-text">${escapeHtml(text)}</span>` : ''}
|
|
1139
|
+
</div>
|
|
1140
|
+
`);
|
|
1141
|
+
});
|
|
1142
|
+
|
|
1143
|
+
const scrollTop = elements.tree.scrollTop;
|
|
1144
|
+
elements.tree.innerHTML = rows.join('');
|
|
1145
|
+
elements.tree.scrollTop = scrollTop;
|
|
1146
|
+
const selectedRow = document.getElementById(treeRowId(state.selectedNodeId));
|
|
1147
|
+
if (selectedRow && elements.tree.contains(selectedRow)) {
|
|
1148
|
+
elements.tree.setAttribute('aria-activedescendant', selectedRow.id);
|
|
1149
|
+
} else {
|
|
1150
|
+
elements.tree.removeAttribute('aria-activedescendant');
|
|
1151
|
+
}
|
|
1152
|
+
elements.filterSummary.textContent = search ? `${matches} match${matches === 1 ? '' : 'es'}` : '';
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
function renderValue(value) {
|
|
1156
|
+
if (value === undefined || value === null) return '<span class="property-value empty">null</span>';
|
|
1157
|
+
const type = typeof value;
|
|
1158
|
+
const serialized = valdiDebuggerTreeModel.formatValue(value, 0);
|
|
1159
|
+
const printable = serialized === undefined ? String(value) : serialized;
|
|
1160
|
+
const formatted = printable.length > 160 ? `${printable.slice(0, 157)}…` : printable;
|
|
1161
|
+
return `<span class="property-value ${type}">${escapeHtml(formatted)}</span>`;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
function propertyRows(attributes, options) {
|
|
1165
|
+
const entries = Object.entries(attributes || {}).sort(([first], [second]) => first.localeCompare(second));
|
|
1166
|
+
if (!entries.length) return '<div class="empty-state">No properties available.</div>';
|
|
1167
|
+
return entries
|
|
1168
|
+
.map(
|
|
1169
|
+
([key, value]) =>
|
|
1170
|
+
`<div class="property-row"><span class="property-name">${escapeHtml(key)}</span>: ${renderValue(value)}${options.css ? ';' : ''}</div>`,
|
|
1171
|
+
)
|
|
1172
|
+
.join('');
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
function runtimeStateParseError(message) {
|
|
1176
|
+
return new Error(`Runtime state ${message}.`);
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
function runtimeStateKeywordAt(source, offset, keyword) {
|
|
1180
|
+
return source.startsWith(keyword, offset) && !/[A-Za-z0-9_$]/.test(source[offset + keyword.length] || '');
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
function readRuntimeStateToken(source, parser) {
|
|
1184
|
+
while (parser.offset < source.length && /[\t\n\r ]/.test(source[parser.offset])) parser.offset++;
|
|
1185
|
+
if (parser.offset >= source.length) return { type: 'end' };
|
|
1186
|
+
parser.tokens++;
|
|
1187
|
+
if (parser.tokens > MAX_RUNTIME_STATE_TOKENS) throw runtimeStateParseError('exceeds the token limit');
|
|
1188
|
+
if (parser.sourceType !== RUNTIME_STATE_SOURCE_WEB) {
|
|
1189
|
+
throw runtimeStateParseError('cannot structurally parse a native snapshot');
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
const character = source[parser.offset];
|
|
1193
|
+
if ('{}[]:,'.includes(character)) {
|
|
1194
|
+
parser.offset++;
|
|
1195
|
+
return { type: 'punctuation', value: character };
|
|
1196
|
+
}
|
|
1197
|
+
if (character === '"') {
|
|
1198
|
+
const start = parser.offset;
|
|
1199
|
+
parser.offset++;
|
|
1200
|
+
let closed = false;
|
|
1201
|
+
while (parser.offset < source.length) {
|
|
1202
|
+
const code = source.charCodeAt(parser.offset);
|
|
1203
|
+
if (code < 0x20) throw runtimeStateParseError('contains an invalid string');
|
|
1204
|
+
if (source[parser.offset] === '"') {
|
|
1205
|
+
parser.offset++;
|
|
1206
|
+
closed = true;
|
|
1207
|
+
break;
|
|
1208
|
+
}
|
|
1209
|
+
if (source[parser.offset] !== '\\') {
|
|
1210
|
+
parser.offset++;
|
|
1211
|
+
continue;
|
|
1212
|
+
}
|
|
1213
|
+
parser.offset++;
|
|
1214
|
+
const escape = source[parser.offset];
|
|
1215
|
+
if ('"\\/bfnrt'.includes(escape)) {
|
|
1216
|
+
parser.offset++;
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1219
|
+
if (escape !== 'u' || !/^[0-9a-fA-F]{4}$/.test(source.slice(parser.offset + 1, parser.offset + 5))) {
|
|
1220
|
+
throw runtimeStateParseError('contains an invalid string escape');
|
|
1221
|
+
}
|
|
1222
|
+
parser.offset += 5;
|
|
1223
|
+
}
|
|
1224
|
+
if (!closed) throw runtimeStateParseError('contains an unterminated string');
|
|
1225
|
+
let value;
|
|
1226
|
+
try {
|
|
1227
|
+
value = JSON.parse(source.slice(start, parser.offset));
|
|
1228
|
+
} catch (_error) {
|
|
1229
|
+
throw runtimeStateParseError('contains an invalid string');
|
|
1230
|
+
}
|
|
1231
|
+
return { type: 'string', value };
|
|
1232
|
+
}
|
|
1233
|
+
if (runtimeStateKeywordAt(source, parser.offset, 'true')) {
|
|
1234
|
+
parser.offset += 4;
|
|
1235
|
+
return { type: 'value', value: true };
|
|
1236
|
+
}
|
|
1237
|
+
if (runtimeStateKeywordAt(source, parser.offset, 'false')) {
|
|
1238
|
+
parser.offset += 5;
|
|
1239
|
+
return { type: 'value', value: false };
|
|
1240
|
+
}
|
|
1241
|
+
if (runtimeStateKeywordAt(source, parser.offset, 'null')) {
|
|
1242
|
+
parser.offset += 4;
|
|
1243
|
+
return { type: 'value', value: null };
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
const start = parser.offset;
|
|
1247
|
+
if (source[parser.offset] === '-') parser.offset++;
|
|
1248
|
+
if (source[parser.offset] === '0') {
|
|
1249
|
+
parser.offset++;
|
|
1250
|
+
if (/\d/.test(source[parser.offset] || '')) throw runtimeStateParseError('contains an invalid number');
|
|
1251
|
+
} else if (/[1-9]/.test(source[parser.offset] || '')) {
|
|
1252
|
+
while (/\d/.test(source[parser.offset] || '')) parser.offset++;
|
|
1253
|
+
} else {
|
|
1254
|
+
throw runtimeStateParseError('contains an unsupported token');
|
|
1255
|
+
}
|
|
1256
|
+
if (source[parser.offset] === '.') {
|
|
1257
|
+
parser.offset++;
|
|
1258
|
+
if (!/\d/.test(source[parser.offset] || '')) throw runtimeStateParseError('contains an invalid number');
|
|
1259
|
+
while (/\d/.test(source[parser.offset] || '')) parser.offset++;
|
|
1260
|
+
}
|
|
1261
|
+
if (source[parser.offset] === 'e' || source[parser.offset] === 'E') {
|
|
1262
|
+
parser.offset++;
|
|
1263
|
+
if (source[parser.offset] === '+' || source[parser.offset] === '-') parser.offset++;
|
|
1264
|
+
if (!/\d/.test(source[parser.offset] || '')) throw runtimeStateParseError('contains an invalid number');
|
|
1265
|
+
while (/\d/.test(source[parser.offset] || '')) parser.offset++;
|
|
1266
|
+
}
|
|
1267
|
+
const value = Number(source.slice(start, parser.offset));
|
|
1268
|
+
if (!Number.isFinite(value)) throw runtimeStateParseError('contains a non-finite number');
|
|
1269
|
+
return { type: 'value', value };
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
function parseRuntimeState(source, sourceType) {
|
|
1273
|
+
if (typeof source !== 'string') {
|
|
1274
|
+
return { error: 'Runtime state is not a serialized document.', parsed: false, value: null };
|
|
1275
|
+
}
|
|
1276
|
+
if (source.length === 0 || source.length > MAX_RUNTIME_STATE_CHARACTERS) {
|
|
1277
|
+
return {
|
|
1278
|
+
error: `Runtime state must contain between 1 and ${MAX_RUNTIME_STATE_CHARACTERS} characters.`,
|
|
1279
|
+
parsed: false,
|
|
1280
|
+
value: null,
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
if (sourceType !== RUNTIME_STATE_SOURCE_NATIVE && sourceType !== RUNTIME_STATE_SOURCE_WEB) {
|
|
1284
|
+
return { error: 'Runtime state has an unknown snapshot source.', parsed: false, value: null };
|
|
1285
|
+
}
|
|
1286
|
+
if (sourceType === RUNTIME_STATE_SOURCE_NATIVE) {
|
|
1287
|
+
return {
|
|
1288
|
+
error: 'Native runtime state is displayed as escaped raw text.',
|
|
1289
|
+
parsed: false,
|
|
1290
|
+
value: null,
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
const parser = { offset: 0, sourceType, tokens: 0 };
|
|
1295
|
+
const stack = [];
|
|
1296
|
+
let root;
|
|
1297
|
+
let rootSet = false;
|
|
1298
|
+
|
|
1299
|
+
const setValue = value => {
|
|
1300
|
+
if (stack.length === 0) {
|
|
1301
|
+
if (rootSet) throw runtimeStateParseError('contains trailing data');
|
|
1302
|
+
root = value;
|
|
1303
|
+
rootSet = true;
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
const frame = stack[stack.length - 1];
|
|
1307
|
+
if (frame.type === 'array') {
|
|
1308
|
+
if (frame.stage !== 'initialOrEnd' && frame.stage !== 'value') {
|
|
1309
|
+
throw runtimeStateParseError('contains an unexpected array value');
|
|
1310
|
+
}
|
|
1311
|
+
if (frame.entries >= MAX_RUNTIME_STATE_CONTAINER_ENTRIES) {
|
|
1312
|
+
throw runtimeStateParseError('exceeds the per-container entry limit');
|
|
1313
|
+
}
|
|
1314
|
+
frame.values.push(value);
|
|
1315
|
+
frame.entries++;
|
|
1316
|
+
frame.stage = 'commaOrEnd';
|
|
1317
|
+
return;
|
|
1318
|
+
}
|
|
1319
|
+
if (frame.stage !== 'value' || frame.key === null) {
|
|
1320
|
+
throw runtimeStateParseError('contains an unexpected object value');
|
|
1321
|
+
}
|
|
1322
|
+
if (frame.entries >= MAX_RUNTIME_STATE_CONTAINER_ENTRIES) {
|
|
1323
|
+
throw runtimeStateParseError('exceeds the per-container entry limit');
|
|
1324
|
+
}
|
|
1325
|
+
if (Object.prototype.hasOwnProperty.call(frame.target, frame.key)) {
|
|
1326
|
+
throw runtimeStateParseError('contains a duplicate object key');
|
|
1327
|
+
}
|
|
1328
|
+
Object.defineProperty(frame.target, frame.key, {
|
|
1329
|
+
configurable: true,
|
|
1330
|
+
enumerable: true,
|
|
1331
|
+
value,
|
|
1332
|
+
writable: true,
|
|
1333
|
+
});
|
|
1334
|
+
frame.entries++;
|
|
1335
|
+
frame.key = null;
|
|
1336
|
+
frame.stage = 'commaOrEnd';
|
|
1337
|
+
};
|
|
1338
|
+
|
|
1339
|
+
const beginContainer = type => {
|
|
1340
|
+
if (stack.length >= MAX_RUNTIME_STATE_DEPTH) throw runtimeStateParseError('exceeds the depth limit');
|
|
1341
|
+
const target = type === 'array' ? [] : Object.create(null);
|
|
1342
|
+
setValue(target);
|
|
1343
|
+
stack.push({ entries: 0, key: null, stage: 'initialOrEnd', target, type, values: target });
|
|
1344
|
+
};
|
|
1345
|
+
|
|
1346
|
+
const acceptValueToken = token => {
|
|
1347
|
+
if (token.type === 'value' || token.type === 'string') {
|
|
1348
|
+
setValue(token.value);
|
|
1349
|
+
return true;
|
|
1350
|
+
}
|
|
1351
|
+
if (token.type === 'punctuation' && token.value === '{') {
|
|
1352
|
+
beginContainer('object');
|
|
1353
|
+
return true;
|
|
1354
|
+
}
|
|
1355
|
+
if (token.type === 'punctuation' && token.value === '[') {
|
|
1356
|
+
beginContainer('array');
|
|
1357
|
+
return true;
|
|
1358
|
+
}
|
|
1359
|
+
return false;
|
|
1360
|
+
};
|
|
1361
|
+
|
|
1362
|
+
try {
|
|
1363
|
+
while (true) {
|
|
1364
|
+
const token = readRuntimeStateToken(source, parser);
|
|
1365
|
+
if (token.type === 'end') {
|
|
1366
|
+
if (!rootSet) throw runtimeStateParseError('is empty');
|
|
1367
|
+
if (stack.length > 0) throw runtimeStateParseError('contains an unterminated container');
|
|
1368
|
+
return { error: null, parsed: true, value: root };
|
|
1369
|
+
}
|
|
1370
|
+
if (stack.length === 0) {
|
|
1371
|
+
if (rootSet || !acceptValueToken(token)) throw runtimeStateParseError('contains trailing data');
|
|
1372
|
+
continue;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
const frame = stack[stack.length - 1];
|
|
1376
|
+
if (frame.type === 'object') {
|
|
1377
|
+
if (frame.stage === 'initialOrEnd' || frame.stage === 'key') {
|
|
1378
|
+
if (token.type === 'punctuation' && token.value === '}' && frame.stage === 'initialOrEnd') {
|
|
1379
|
+
stack.pop();
|
|
1380
|
+
continue;
|
|
1381
|
+
}
|
|
1382
|
+
if (token.type !== 'string') {
|
|
1383
|
+
throw runtimeStateParseError('contains an invalid object key');
|
|
1384
|
+
}
|
|
1385
|
+
if (token.value.length > MAX_RUNTIME_STATE_KEY_CHARACTERS) {
|
|
1386
|
+
throw runtimeStateParseError('contains an overlong object key');
|
|
1387
|
+
}
|
|
1388
|
+
frame.key = token.value;
|
|
1389
|
+
frame.stage = 'colon';
|
|
1390
|
+
continue;
|
|
1391
|
+
}
|
|
1392
|
+
if (frame.stage === 'colon') {
|
|
1393
|
+
if (token.type !== 'punctuation' || token.value !== ':') {
|
|
1394
|
+
throw runtimeStateParseError('is missing an object value separator');
|
|
1395
|
+
}
|
|
1396
|
+
frame.stage = 'value';
|
|
1397
|
+
continue;
|
|
1398
|
+
}
|
|
1399
|
+
if (frame.stage === 'value') {
|
|
1400
|
+
if (!acceptValueToken(token)) throw runtimeStateParseError('contains an invalid object value');
|
|
1401
|
+
continue;
|
|
1402
|
+
}
|
|
1403
|
+
if (token.type === 'punctuation' && token.value === ',') {
|
|
1404
|
+
frame.stage = 'key';
|
|
1405
|
+
continue;
|
|
1406
|
+
}
|
|
1407
|
+
if (token.type === 'punctuation' && token.value === '}') {
|
|
1408
|
+
stack.pop();
|
|
1409
|
+
continue;
|
|
1410
|
+
}
|
|
1411
|
+
throw runtimeStateParseError('contains an invalid object separator');
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
if (frame.stage === 'initialOrEnd') {
|
|
1415
|
+
if (token.type === 'punctuation' && token.value === ']') {
|
|
1416
|
+
stack.pop();
|
|
1417
|
+
continue;
|
|
1418
|
+
}
|
|
1419
|
+
if (!acceptValueToken(token)) throw runtimeStateParseError('contains an invalid array value');
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
if (frame.stage === 'value') {
|
|
1423
|
+
if (!acceptValueToken(token)) throw runtimeStateParseError('contains an invalid array value');
|
|
1424
|
+
continue;
|
|
1425
|
+
}
|
|
1426
|
+
if (token.type === 'punctuation' && token.value === ',') {
|
|
1427
|
+
frame.stage = 'value';
|
|
1428
|
+
continue;
|
|
1429
|
+
}
|
|
1430
|
+
if (token.type === 'punctuation' && token.value === ']') {
|
|
1431
|
+
stack.pop();
|
|
1432
|
+
continue;
|
|
1433
|
+
}
|
|
1434
|
+
throw runtimeStateParseError('contains an invalid array separator');
|
|
1435
|
+
}
|
|
1436
|
+
} catch (error) {
|
|
1437
|
+
return {
|
|
1438
|
+
error: error instanceof Error ? error.message : 'Runtime state could not be parsed.',
|
|
1439
|
+
parsed: false,
|
|
1440
|
+
value: null,
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
function runtimeStateOwnDataValue(source, propertyName) {
|
|
1446
|
+
if (typeof source !== 'object' || source === null) return null;
|
|
1447
|
+
try {
|
|
1448
|
+
const descriptor = Object.getOwnPropertyDescriptor(source, propertyName);
|
|
1449
|
+
if (descriptor?.enumerable !== true || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) {
|
|
1450
|
+
return null;
|
|
1451
|
+
}
|
|
1452
|
+
return { value: descriptor.value };
|
|
1453
|
+
} catch (_error) {
|
|
1454
|
+
return null;
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
function runtimeStateExactNodeId(value) {
|
|
1459
|
+
if (typeof value === 'string' && value.length > 0) return value;
|
|
1460
|
+
if (Number.isSafeInteger(value) && value >= 0) return String(value);
|
|
1461
|
+
return null;
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
function runtimeStateSelectableNodeId(node) {
|
|
1465
|
+
if (typeof node !== 'object' || node === null) return null;
|
|
1466
|
+
try {
|
|
1467
|
+
const nodeIdDescriptor = Object.getOwnPropertyDescriptor(node, 'id');
|
|
1468
|
+
if (nodeIdDescriptor !== undefined) {
|
|
1469
|
+
if (nodeIdDescriptor.enumerable !== true || !Object.prototype.hasOwnProperty.call(nodeIdDescriptor, 'value')) {
|
|
1470
|
+
return null;
|
|
1471
|
+
}
|
|
1472
|
+
return runtimeStateExactNodeId(nodeIdDescriptor.value);
|
|
1473
|
+
}
|
|
1474
|
+
} catch (_error) {
|
|
1475
|
+
return null;
|
|
1476
|
+
}
|
|
1477
|
+
const elementValue = runtimeStateOwnDataValue(node, 'element')?.value;
|
|
1478
|
+
return runtimeStateExactNodeId(runtimeStateOwnDataValue(elementValue, 'id')?.value);
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
function runtimeStateSourceType() {
|
|
1482
|
+
return launchIdentity.mode === 'inspected-page' ? RUNTIME_STATE_SOURCE_WEB : RUNTIME_STATE_SOURCE_NATIVE;
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
function runtimeStateComponentRecord(node, structuralId) {
|
|
1486
|
+
const componentValue = runtimeStateOwnDataValue(node, 'component')?.value;
|
|
1487
|
+
const stateValue = runtimeStateOwnDataValue(componentValue, 'state')?.value;
|
|
1488
|
+
if (typeof stateValue !== 'string' || stateValue.length === 0 || stateValue.length > MAX_RUNTIME_STATE_CHARACTERS) {
|
|
1489
|
+
return null;
|
|
1490
|
+
}
|
|
1491
|
+
const sourceType = runtimeStateSourceType();
|
|
1492
|
+
const nameValue = runtimeStateOwnDataValue(componentValue, 'name')?.value;
|
|
1493
|
+
const componentKeyValue = runtimeStateOwnDataValue(componentValue, 'key')?.value;
|
|
1494
|
+
const nodeKeyValue = runtimeStateOwnDataValue(node, 'key')?.value;
|
|
1495
|
+
const keyValue = sourceType === RUNTIME_STATE_SOURCE_WEB ? componentKeyValue : nodeKeyValue;
|
|
1496
|
+
const tagValue = runtimeStateOwnDataValue(node, 'tag')?.value;
|
|
1497
|
+
return {
|
|
1498
|
+
key: typeof keyValue === 'string' ? keyValue : '',
|
|
1499
|
+
name:
|
|
1500
|
+
typeof nameValue === 'string' && nameValue.length > 0
|
|
1501
|
+
? nameValue
|
|
1502
|
+
: typeof tagValue === 'string' && tagValue.length > 0
|
|
1503
|
+
? tagValue
|
|
1504
|
+
: 'Component',
|
|
1505
|
+
node,
|
|
1506
|
+
selectableNodeId: runtimeStateSelectableNodeId(node),
|
|
1507
|
+
source: stateValue,
|
|
1508
|
+
sourceType,
|
|
1509
|
+
structuralId,
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
function parseRuntimeStateRecord(record) {
|
|
1514
|
+
const cached = runtimeStateParseCache.get(record.node);
|
|
1515
|
+
if (cached?.source === record.source && cached.sourceType === record.sourceType) return cached.parsed;
|
|
1516
|
+
const parsed = parseRuntimeState(record.source, record.sourceType);
|
|
1517
|
+
runtimeStateParseCache.set(record.node, {
|
|
1518
|
+
parsed,
|
|
1519
|
+
source: record.source,
|
|
1520
|
+
sourceType: record.sourceType,
|
|
1521
|
+
});
|
|
1522
|
+
return parsed;
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
function collectRuntimeStateComponents(root) {
|
|
1526
|
+
const exactSelectableNodes = new Map();
|
|
1527
|
+
const records = [];
|
|
1528
|
+
const structuralPaths = new WeakMap();
|
|
1529
|
+
let truncated = false;
|
|
1530
|
+
walk(root, (node, ancestors, _depth, sourceChildIndex) => {
|
|
1531
|
+
let structuralPath;
|
|
1532
|
+
if (ancestors.length === 0) {
|
|
1533
|
+
structuralPath = [];
|
|
1534
|
+
} else {
|
|
1535
|
+
const parentPath = structuralPaths.get(ancestors[ancestors.length - 1]);
|
|
1536
|
+
if (!Array.isArray(parentPath) || !Number.isSafeInteger(sourceChildIndex) || sourceChildIndex < 0) {
|
|
1537
|
+
return false;
|
|
1538
|
+
}
|
|
1539
|
+
structuralPath = [...parentPath, sourceChildIndex];
|
|
1540
|
+
}
|
|
1541
|
+
structuralPaths.set(node, structuralPath);
|
|
1542
|
+
const selectableNodeId = runtimeStateSelectableNodeId(node);
|
|
1543
|
+
if (selectableNodeId !== null) {
|
|
1544
|
+
if (exactSelectableNodes.has(selectableNodeId)) exactSelectableNodes.set(selectableNodeId, null);
|
|
1545
|
+
else exactSelectableNodes.set(selectableNodeId, node);
|
|
1546
|
+
}
|
|
1547
|
+
const record = runtimeStateComponentRecord(node, JSON.stringify(structuralPath));
|
|
1548
|
+
if (record === null) return true;
|
|
1549
|
+
if (records.length >= MAX_RUNTIME_STATE_COMPONENT_ROWS) {
|
|
1550
|
+
truncated = true;
|
|
1551
|
+
return true;
|
|
1552
|
+
}
|
|
1553
|
+
records.push(record);
|
|
1554
|
+
return true;
|
|
1555
|
+
});
|
|
1556
|
+
for (const record of records) {
|
|
1557
|
+
if (record.selectableNodeId !== null && exactSelectableNodes.get(record.selectableNodeId) !== record.node) {
|
|
1558
|
+
record.selectableNodeId = null;
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
return { records, truncated };
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
function findRuntimeStateRecordByStructuralId(structuralId) {
|
|
1565
|
+
return (
|
|
1566
|
+
collectRuntimeStateComponents(state.snapshot?.tree).records.find(record => record.structuralId === structuralId) ||
|
|
1567
|
+
null
|
|
1568
|
+
);
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
function runtimeStateContainerEntries(value) {
|
|
1572
|
+
if (Array.isArray(value)) return value.map((entry, index) => [String(index), entry]);
|
|
1573
|
+
if (typeof value !== 'object' || value === null) return [];
|
|
1574
|
+
return Object.keys(value).map(key => [key, Object.getOwnPropertyDescriptor(value, key)?.value]);
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
function runtimeStateDescription(value) {
|
|
1578
|
+
if (Array.isArray(value)) return `${value.length} item${value.length === 1 ? '' : 's'}`;
|
|
1579
|
+
if (typeof value === 'object' && value !== null) {
|
|
1580
|
+
const count = Object.keys(value).length;
|
|
1581
|
+
return `${count} field${count === 1 ? '' : 's'}`;
|
|
1582
|
+
}
|
|
1583
|
+
return typeof value;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
function renderRuntimeStatePrimitive(value) {
|
|
1587
|
+
if (value === null) return '<span class="runtime-state-value-null">null</span>';
|
|
1588
|
+
const type = typeof value;
|
|
1589
|
+
const serialized = type === 'string' ? JSON.stringify(value) : String(value);
|
|
1590
|
+
return `<span class="runtime-state-value-${escapeHtml(type)}">${escapeHtml(serialized)}</span>`;
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
function runtimeStateValuePath(scope, componentId, segments) {
|
|
1594
|
+
return JSON.stringify([scope, componentId, ...segments]);
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
function renderRuntimeStateEntries(value, context, segments) {
|
|
1598
|
+
const entries = runtimeStateContainerEntries(value);
|
|
1599
|
+
if (entries.length === 0) return '<div class="empty-state">This state container is empty.</div>';
|
|
1600
|
+
const rows = [];
|
|
1601
|
+
for (const [key, entryValue] of entries) {
|
|
1602
|
+
if (context.rows >= MAX_RUNTIME_STATE_VALUE_ROWS) {
|
|
1603
|
+
context.truncated = true;
|
|
1604
|
+
break;
|
|
1605
|
+
}
|
|
1606
|
+
context.rows++;
|
|
1607
|
+
const entrySegments = [...segments, key];
|
|
1608
|
+
const keyLabel = Array.isArray(value) ? `[${key}]` : key;
|
|
1609
|
+
if (typeof entryValue !== 'object' || entryValue === null) {
|
|
1610
|
+
rows.push(
|
|
1611
|
+
`<div class="runtime-state-value-row"><span class="runtime-state-value-key">${escapeHtml(keyLabel)}</span>: ${renderRuntimeStatePrimitive(entryValue)}</div>`,
|
|
1612
|
+
);
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
const path = runtimeStateValuePath(context.scope, context.componentId, entrySegments);
|
|
1616
|
+
const expanded = context.expandedPaths.has(path);
|
|
1617
|
+
rows.push(`
|
|
1618
|
+
<details class="runtime-state-value-details" data-runtime-state-value-path="${escapeHtml(path)}" data-runtime-state-value-scope="${escapeHtml(context.scope)}"${expanded ? ' open' : ''}>
|
|
1619
|
+
<summary class="runtime-state-value-summary"><span class="runtime-state-disclosure">›</span><span class="runtime-state-value-key">${escapeHtml(keyLabel)}</span>: <span class="runtime-state-value-description">${escapeHtml(runtimeStateDescription(entryValue))}</span></summary>
|
|
1620
|
+
${expanded ? `<div class="runtime-state-value-children">${renderRuntimeStateEntries(entryValue, context, entrySegments)}</div>` : ''}
|
|
1621
|
+
</details>
|
|
1622
|
+
`);
|
|
1623
|
+
}
|
|
1624
|
+
if (context.truncated && !context.limitRendered) {
|
|
1625
|
+
context.limitRendered = true;
|
|
1626
|
+
rows.push('<div class="runtime-state-limit">Additional state rows were omitted.</div>');
|
|
1627
|
+
}
|
|
1628
|
+
return rows.join('');
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
function renderRuntimeStateDocument(record, parsed, context) {
|
|
1632
|
+
if (!parsed.parsed || typeof parsed.value !== 'object' || parsed.value === null) {
|
|
1633
|
+
return `<div class="runtime-state-limit">${escapeHtml(parsed.error || 'Runtime state is not an object document.')}</div><pre class="runtime-state-raw">${escapeHtml(record.source)}</pre>`;
|
|
1634
|
+
}
|
|
1635
|
+
return renderRuntimeStateEntries(parsed.value, context, []);
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
function hydrateRuntimeStateInspectButtons(models) {
|
|
1639
|
+
const buttons = elements.stateContent?.querySelectorAll?.('[data-runtime-state-inspect-slot]') || [];
|
|
1640
|
+
for (const button of buttons) {
|
|
1641
|
+
const index = Number(button.dataset.runtimeStateInspectSlot);
|
|
1642
|
+
const model = Number.isSafeInteger(index) && index >= 0 ? models[index] : undefined;
|
|
1643
|
+
if (!model) continue;
|
|
1644
|
+
delete button.dataset.runtimeStateInspectSlot;
|
|
1645
|
+
button.dataset.runtimeStateInspect = '';
|
|
1646
|
+
runtimeStateInspectBindings.set(button, model);
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
function renderRuntimeStateSection() {
|
|
1651
|
+
if (!elements.stateContent || !elements.stateSummary) return;
|
|
1652
|
+
const renderGeneration = ++state.runtimeState.inspectGeneration;
|
|
1653
|
+
const snapshotGeneration = state.snapshotGeneration;
|
|
1654
|
+
const collected = collectRuntimeStateComponents(state.snapshot?.tree);
|
|
1655
|
+
const normalizedSearch = state.runtimeState.search.trim().toLowerCase();
|
|
1656
|
+
const records = normalizedSearch
|
|
1657
|
+
? collected.records.filter(record =>
|
|
1658
|
+
`${record.name} ${record.key} ${record.source}`.toLowerCase().includes(normalizedSearch),
|
|
1659
|
+
)
|
|
1660
|
+
: collected.records;
|
|
1661
|
+
elements.stateSummary.textContent = `${records.length}${normalizedSearch ? ` of ${collected.records.length}` : ''} component${collected.records.length === 1 ? '' : 's'}${collected.truncated ? ' · first 500' : ''}`;
|
|
1662
|
+
if (!state.snapshot?.tree) {
|
|
1663
|
+
elements.stateContent.innerHTML = '<div class="empty-state">Waiting for the inspected component hierarchy…</div>';
|
|
1664
|
+
return;
|
|
1665
|
+
}
|
|
1666
|
+
if (records.length === 0) {
|
|
1667
|
+
elements.stateContent.innerHTML = `<div class="empty-state">${normalizedSearch ? 'No component state matches this filter.' : 'No mounted component has published bounded runtime state.'}</div>`;
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
const inspectModels = [];
|
|
1672
|
+
const renderContext = {
|
|
1673
|
+
componentId: '',
|
|
1674
|
+
expandedPaths: state.runtimeState.expandedMainValues,
|
|
1675
|
+
rows: 0,
|
|
1676
|
+
limitRendered: false,
|
|
1677
|
+
scope: 'main',
|
|
1678
|
+
truncated: false,
|
|
1679
|
+
};
|
|
1680
|
+
const markup = records
|
|
1681
|
+
.map(record => {
|
|
1682
|
+
const expanded = state.runtimeState.expandedComponents.has(record.structuralId);
|
|
1683
|
+
const parsed = parseRuntimeStateRecord(record);
|
|
1684
|
+
let inspectButton = '';
|
|
1685
|
+
if (record.selectableNodeId !== null) {
|
|
1686
|
+
const inspectIndex =
|
|
1687
|
+
inspectModels.push({
|
|
1688
|
+
generation: renderGeneration,
|
|
1689
|
+
node: record.node,
|
|
1690
|
+
selectableNodeId: record.selectableNodeId,
|
|
1691
|
+
snapshotGeneration,
|
|
1692
|
+
source: record.source,
|
|
1693
|
+
structuralId: record.structuralId,
|
|
1694
|
+
}) - 1;
|
|
1695
|
+
inspectButton = `<button type="button" class="runtime-state-inspect" data-runtime-state-inspect-slot="${inspectIndex}" aria-label="${escapeHtml(`Inspect ${record.name}${record.key ? ` ${record.key}` : ''} state, component ${record.selectableNodeId}`)}">Inspect</button>`;
|
|
1696
|
+
}
|
|
1697
|
+
renderContext.componentId = record.structuralId;
|
|
1698
|
+
const description = parsed.parsed ? runtimeStateDescription(parsed.value) : 'bounded raw snapshot';
|
|
1699
|
+
const body = expanded
|
|
1700
|
+
? `<div class="runtime-state-component-body">${renderRuntimeStateDocument(record, parsed, renderContext)}</div>`
|
|
1701
|
+
: '';
|
|
1702
|
+
return `
|
|
1703
|
+
<div class="runtime-state-component">
|
|
1704
|
+
<details class="runtime-state-component-details" data-runtime-state-component-id="${escapeHtml(record.structuralId)}"${expanded ? ' open' : ''}>
|
|
1705
|
+
<summary class="runtime-state-component-summary"><span class="runtime-state-disclosure">›</span><span class="runtime-state-component-name">${escapeHtml(record.name)}</span>${record.key ? `<span class="runtime-state-component-key">${escapeHtml(record.key)}</span>` : ''}<span class="runtime-state-component-description">${escapeHtml(description)}</span></summary>
|
|
1706
|
+
${body}
|
|
1707
|
+
</details>
|
|
1708
|
+
${inspectButton}
|
|
1709
|
+
</div>
|
|
1710
|
+
`;
|
|
1711
|
+
})
|
|
1712
|
+
.join('');
|
|
1713
|
+
elements.stateContent.innerHTML = markup;
|
|
1714
|
+
hydrateRuntimeStateInspectButtons(inspectModels);
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
function renderSelectedRuntimeState(node) {
|
|
1718
|
+
resetRuntimeStateForSelectionChange(nodeId(node));
|
|
1719
|
+
const record = runtimeStateComponentRecord(node, JSON.stringify(['selected']));
|
|
1720
|
+
if (record === null) {
|
|
1721
|
+
return '<div class="empty-state">This selected component has no bounded runtime state snapshot.</div>';
|
|
1722
|
+
}
|
|
1723
|
+
const parsed = parseRuntimeStateRecord(record);
|
|
1724
|
+
const context = {
|
|
1725
|
+
componentId: record.structuralId,
|
|
1726
|
+
expandedPaths: state.runtimeState.expandedInspectorValues,
|
|
1727
|
+
rows: 0,
|
|
1728
|
+
limitRendered: false,
|
|
1729
|
+
scope: 'inspector',
|
|
1730
|
+
truncated: false,
|
|
1731
|
+
};
|
|
1732
|
+
return `<section class="runtime-state-inspector"><div class="rule-header">Component state <span class="rule-origin">${escapeHtml(record.name)}</span></div>${renderRuntimeStateDocument(record, parsed, context)}</section>`;
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
function inspectRuntimeStateBinding(binding) {
|
|
1736
|
+
if (
|
|
1737
|
+
binding?.generation !== state.runtimeState.inspectGeneration ||
|
|
1738
|
+
binding.snapshotGeneration !== state.snapshotGeneration
|
|
1739
|
+
) {
|
|
1740
|
+
return false;
|
|
1741
|
+
}
|
|
1742
|
+
const currentRecord = findRuntimeStateRecordByStructuralId(binding.structuralId);
|
|
1743
|
+
if (
|
|
1744
|
+
currentRecord?.node !== binding.node ||
|
|
1745
|
+
currentRecord.selectableNodeId !== binding.selectableNodeId ||
|
|
1746
|
+
currentRecord.source !== binding.source
|
|
1747
|
+
) {
|
|
1748
|
+
return false;
|
|
1749
|
+
}
|
|
1750
|
+
setActiveSection('elements');
|
|
1751
|
+
selectNode(binding.selectableNodeId);
|
|
1752
|
+
setActiveDetail('state');
|
|
1753
|
+
elements.detailTabs.find(tab => tab.dataset.detail === 'state')?.focus?.({ preventScroll: true });
|
|
1754
|
+
return true;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
function restoreRuntimeStateDisclosureFocus(scope, componentId, valuePath) {
|
|
1758
|
+
const container = scope === 'inspector' ? elements.inspector : elements.stateContent;
|
|
1759
|
+
const detailsElements = container?.querySelectorAll?.('details') || [];
|
|
1760
|
+
for (const candidate of detailsElements) {
|
|
1761
|
+
if (
|
|
1762
|
+
(componentId !== null && candidate.dataset.runtimeStateComponentId === componentId) ||
|
|
1763
|
+
(valuePath !== null && candidate.dataset.runtimeStateValuePath === valuePath)
|
|
1764
|
+
) {
|
|
1765
|
+
candidate.querySelector?.('summary')?.focus?.({ preventScroll: true });
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
function updateRuntimeStateDisclosure(details) {
|
|
1772
|
+
if (!details?.dataset) return;
|
|
1773
|
+
const valuePath = details.dataset.runtimeStateValuePath;
|
|
1774
|
+
if (valuePath) {
|
|
1775
|
+
const summary = details.querySelector?.('summary');
|
|
1776
|
+
const restoreFocus = summary !== null && summary !== undefined && summary === document.activeElement;
|
|
1777
|
+
const scope = details.dataset.runtimeStateValueScope === 'inspector' ? 'inspector' : 'main';
|
|
1778
|
+
const expandedPaths =
|
|
1779
|
+
scope === 'inspector' ? state.runtimeState.expandedInspectorValues : state.runtimeState.expandedMainValues;
|
|
1780
|
+
if (details.open === expandedPaths.has(valuePath)) return;
|
|
1781
|
+
if (details.open) expandedPaths.add(valuePath);
|
|
1782
|
+
else expandedPaths.delete(valuePath);
|
|
1783
|
+
if (scope === 'inspector') renderInspector();
|
|
1784
|
+
else renderRuntimeStateSection();
|
|
1785
|
+
if (restoreFocus) restoreRuntimeStateDisclosureFocus(scope, null, valuePath);
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
const structuralId = details.dataset.runtimeStateComponentId;
|
|
1789
|
+
if (!structuralId) return;
|
|
1790
|
+
const summary = details.querySelector?.('summary');
|
|
1791
|
+
const restoreFocus = summary !== null && summary !== undefined && summary === document.activeElement;
|
|
1792
|
+
const expanded = state.runtimeState.expandedComponents.has(structuralId);
|
|
1793
|
+
if (details.open === expanded) return;
|
|
1794
|
+
const record = findRuntimeStateRecordByStructuralId(structuralId);
|
|
1795
|
+
if (details.open && record === null) return;
|
|
1796
|
+
if (details.open) state.runtimeState.expandedComponents.add(structuralId);
|
|
1797
|
+
else state.runtimeState.expandedComponents.delete(structuralId);
|
|
1798
|
+
renderRuntimeStateSection();
|
|
1799
|
+
if (restoreFocus) restoreRuntimeStateDisclosureFocus('main', structuralId, null);
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
function componentPropertyEditMetadata(node, propertyName, value) {
|
|
1803
|
+
if (
|
|
1804
|
+
launchIdentity.mode !== 'inspected-page' ||
|
|
1805
|
+
state.componentPropertyEdit.error !== null ||
|
|
1806
|
+
!targetSupports('component-properties') ||
|
|
1807
|
+
!targetSupports('component-property-edit') ||
|
|
1808
|
+
!node.component ||
|
|
1809
|
+
typeof node.component.propertyEdits !== 'object' ||
|
|
1810
|
+
node.component.propertyEdits === null ||
|
|
1811
|
+
propertyName.trim().length === 0 ||
|
|
1812
|
+
FORBIDDEN_COMPONENT_PROPERTY_NAMES.has(propertyName) ||
|
|
1813
|
+
!['boolean', 'number', 'string'].includes(typeof value) ||
|
|
1814
|
+
(typeof value === 'number' && (!Number.isFinite(value) || Object.is(value, -0)))
|
|
1815
|
+
) {
|
|
1816
|
+
return null;
|
|
1817
|
+
}
|
|
1818
|
+
let metadataDescriptor;
|
|
1819
|
+
try {
|
|
1820
|
+
metadataDescriptor = Object.getOwnPropertyDescriptor(node.component.propertyEdits, propertyName);
|
|
1821
|
+
} catch (_error) {
|
|
1822
|
+
return null;
|
|
1823
|
+
}
|
|
1824
|
+
const metadata = metadataDescriptor?.value;
|
|
1825
|
+
if (
|
|
1826
|
+
metadataDescriptor?.enumerable !== true ||
|
|
1827
|
+
metadataDescriptor.get !== undefined ||
|
|
1828
|
+
metadataDescriptor.set !== undefined ||
|
|
1829
|
+
typeof metadata !== 'object' ||
|
|
1830
|
+
metadata === null ||
|
|
1831
|
+
Array.isArray(metadata)
|
|
1832
|
+
) {
|
|
1833
|
+
return null;
|
|
1834
|
+
}
|
|
1835
|
+
let componentTokenDescriptor;
|
|
1836
|
+
let snapshotRevisionDescriptor;
|
|
1837
|
+
try {
|
|
1838
|
+
componentTokenDescriptor = Object.getOwnPropertyDescriptor(metadata, 'componentToken');
|
|
1839
|
+
snapshotRevisionDescriptor = Object.getOwnPropertyDescriptor(metadata, 'snapshotRevision');
|
|
1840
|
+
} catch (_error) {
|
|
1841
|
+
return null;
|
|
1842
|
+
}
|
|
1843
|
+
const componentToken = componentTokenDescriptor?.value;
|
|
1844
|
+
const snapshotRevision = snapshotRevisionDescriptor?.value;
|
|
1845
|
+
if (
|
|
1846
|
+
componentTokenDescriptor?.enumerable !== true ||
|
|
1847
|
+
componentTokenDescriptor.get !== undefined ||
|
|
1848
|
+
componentTokenDescriptor.set !== undefined ||
|
|
1849
|
+
snapshotRevisionDescriptor?.enumerable !== true ||
|
|
1850
|
+
snapshotRevisionDescriptor.get !== undefined ||
|
|
1851
|
+
snapshotRevisionDescriptor.set !== undefined ||
|
|
1852
|
+
typeof componentToken !== 'string' ||
|
|
1853
|
+
!COMPONENT_PROPERTY_TOKEN_PATTERN.test(componentToken) ||
|
|
1854
|
+
!Number.isSafeInteger(snapshotRevision) ||
|
|
1855
|
+
snapshotRevision <= 0
|
|
1856
|
+
) {
|
|
1857
|
+
return null;
|
|
1858
|
+
}
|
|
1859
|
+
return { componentToken, snapshotRevision };
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
function createComponentPropertyEditor(node, propertyName, value, metadata) {
|
|
1863
|
+
const valueType = typeof value;
|
|
1864
|
+
const form = document.createElement('form');
|
|
1865
|
+
form.className = 'component-property-editor';
|
|
1866
|
+
form.dataset.componentPropertyEditor = '';
|
|
1867
|
+
const label = document.createElement('label');
|
|
1868
|
+
label.className = 'component-property-label';
|
|
1869
|
+
const propertyNameLabel = document.createElement('span');
|
|
1870
|
+
propertyNameLabel.className = 'property-name';
|
|
1871
|
+
propertyNameLabel.textContent = propertyName;
|
|
1872
|
+
const separator = document.createElement('span');
|
|
1873
|
+
separator.setAttribute('aria-hidden', 'true');
|
|
1874
|
+
separator.textContent = ':';
|
|
1875
|
+
let editor;
|
|
1876
|
+
if (valueType === 'string') {
|
|
1877
|
+
editor = document.createElement('textarea');
|
|
1878
|
+
editor.className = 'component-property-input component-property-string-input';
|
|
1879
|
+
editor.setAttribute('aria-label', `Edit Valdi prop ${propertyName} as a JSON string literal`);
|
|
1880
|
+
editor.setAttribute('rows', '1');
|
|
1881
|
+
editor.setAttribute('spellcheck', 'false');
|
|
1882
|
+
editor.value = JSON.stringify(value);
|
|
1883
|
+
} else {
|
|
1884
|
+
editor = document.createElement('input');
|
|
1885
|
+
editor.className = 'component-property-input';
|
|
1886
|
+
editor.setAttribute('aria-label', `Edit Valdi prop ${propertyName}`);
|
|
1887
|
+
editor.setAttribute('type', valueType === 'boolean' ? 'checkbox' : 'number');
|
|
1888
|
+
if (valueType === 'boolean') editor.checked = value;
|
|
1889
|
+
else {
|
|
1890
|
+
editor.setAttribute('step', 'any');
|
|
1891
|
+
editor.value = String(value);
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
editor.dataset.componentPropertyInput = '';
|
|
1895
|
+
const applyButton = document.createElement('button');
|
|
1896
|
+
applyButton.className = 'component-property-apply';
|
|
1897
|
+
applyButton.setAttribute('aria-label', `Apply Valdi prop ${propertyName}`);
|
|
1898
|
+
applyButton.setAttribute('type', 'submit');
|
|
1899
|
+
applyButton.disabled = state.componentPropertyEdit.pending;
|
|
1900
|
+
applyButton.textContent = 'Apply';
|
|
1901
|
+
label.append(propertyNameLabel);
|
|
1902
|
+
label.append(separator);
|
|
1903
|
+
label.append(editor);
|
|
1904
|
+
form.append(label);
|
|
1905
|
+
form.append(applyButton);
|
|
1906
|
+
componentPropertyEditorBindings.set(form, {
|
|
1907
|
+
componentId: node.id,
|
|
1908
|
+
componentToken: metadata.componentToken,
|
|
1909
|
+
propertyName,
|
|
1910
|
+
snapshotRevision: metadata.snapshotRevision,
|
|
1911
|
+
valueType,
|
|
1912
|
+
});
|
|
1913
|
+
return form;
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
function componentPropertyRows(node, editorModels) {
|
|
1917
|
+
const entries = Object.entries(node.component?.properties || {}).sort(([first], [second]) =>
|
|
1918
|
+
first.localeCompare(second),
|
|
1919
|
+
);
|
|
1920
|
+
if (!entries.length) return '<div class="empty-state">No properties available.</div>';
|
|
1921
|
+
return entries
|
|
1922
|
+
.map(([propertyName, value]) => {
|
|
1923
|
+
const metadata = componentPropertyEditMetadata(node, propertyName, value);
|
|
1924
|
+
if (metadata) {
|
|
1925
|
+
const editorIndex = editorModels.push({ metadata, node, propertyName, value }) - 1;
|
|
1926
|
+
return `<div class="component-property-editor-slot" data-component-property-editor-slot="${editorIndex}"></div>`;
|
|
1927
|
+
}
|
|
1928
|
+
return `<div class="property-row"><span class="property-name">${escapeHtml(propertyName)}</span>: ${renderValue(value)}</div>`;
|
|
1929
|
+
})
|
|
1930
|
+
.join('');
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
function hydrateComponentPropertyEditors(editorModels) {
|
|
1934
|
+
const slots = elements.inspector.querySelectorAll?.('[data-component-property-editor-slot]') || [];
|
|
1935
|
+
for (const slot of slots) {
|
|
1936
|
+
const editorIndex = Number(slot.dataset.componentPropertyEditorSlot);
|
|
1937
|
+
const model = Number.isSafeInteger(editorIndex) && editorIndex >= 0 ? editorModels[editorIndex] : undefined;
|
|
1938
|
+
if (model) {
|
|
1939
|
+
slot.replaceChildren(createComponentPropertyEditor(model.node, model.propertyName, model.value, model.metadata));
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
async function submitComponentPropertyEdit(componentId, propertyName, componentToken, snapshotRevision, value) {
|
|
1945
|
+
if (!state.target || state.componentPropertyEdit.pending) return;
|
|
1946
|
+
const node = findNode(componentId);
|
|
1947
|
+
let currentValue;
|
|
1948
|
+
try {
|
|
1949
|
+
currentValue = Object.getOwnPropertyDescriptor(node?.component?.properties, propertyName)?.value;
|
|
1950
|
+
} catch (_error) {
|
|
1951
|
+
return;
|
|
1952
|
+
}
|
|
1953
|
+
const metadata = node ? componentPropertyEditMetadata(node, propertyName, currentValue) : null;
|
|
1954
|
+
if (
|
|
1955
|
+
!node?.component ||
|
|
1956
|
+
metadata === null ||
|
|
1957
|
+
metadata.componentToken !== componentToken ||
|
|
1958
|
+
metadata.snapshotRevision !== snapshotRevision
|
|
1959
|
+
) {
|
|
1960
|
+
return;
|
|
1961
|
+
}
|
|
1962
|
+
const requestTarget = state.target;
|
|
1963
|
+
const targetGeneration = state.targetGeneration;
|
|
1964
|
+
const snapshotGeneration = state.snapshotGeneration;
|
|
1965
|
+
const selectedNodeId = state.selectedNodeId;
|
|
1966
|
+
const operationGeneration = ++state.componentPropertyEdit.operationGeneration;
|
|
1967
|
+
const operationIsCurrent = () => state.componentPropertyEdit.operationGeneration === operationGeneration;
|
|
1968
|
+
const requestIsCurrent = () =>
|
|
1969
|
+
operationIsCurrent() &&
|
|
1970
|
+
state.targetGeneration === targetGeneration &&
|
|
1971
|
+
state.target?.id === requestTarget.id &&
|
|
1972
|
+
state.snapshotGeneration === snapshotGeneration &&
|
|
1973
|
+
state.selectedNodeId === selectedNodeId;
|
|
1974
|
+
state.componentPropertyEdit.focused = false;
|
|
1975
|
+
state.componentPropertyEdit.pending = true;
|
|
1976
|
+
state.componentPropertyEdit.error = null;
|
|
1977
|
+
state.snapshotRequestGeneration++;
|
|
1978
|
+
renderInspector();
|
|
1979
|
+
let updated = false;
|
|
1980
|
+
let refreshed = false;
|
|
1981
|
+
let refreshDeferredForRuntimeState = false;
|
|
1982
|
+
try {
|
|
1983
|
+
const result = await requestJson(
|
|
1984
|
+
'/api/devtools/component-property',
|
|
1985
|
+
{},
|
|
1986
|
+
{
|
|
1987
|
+
body: {
|
|
1988
|
+
...targetIdentityParameters(requestTarget),
|
|
1989
|
+
componentId,
|
|
1990
|
+
componentToken,
|
|
1991
|
+
propertyName,
|
|
1992
|
+
protocolVersion: COMPONENT_PROPERTY_EDIT_PROTOCOL_VERSION,
|
|
1993
|
+
snapshotRevision,
|
|
1994
|
+
value,
|
|
1995
|
+
},
|
|
1996
|
+
},
|
|
1997
|
+
);
|
|
1998
|
+
if (requestIsCurrent()) {
|
|
1999
|
+
updated = result.updated === true;
|
|
2000
|
+
if (updated) {
|
|
2001
|
+
const refreshOutcome = await refreshSnapshotInternal(operationGeneration);
|
|
2002
|
+
refreshed = refreshOutcome === SNAPSHOT_REFRESH_APPLIED;
|
|
2003
|
+
refreshDeferredForRuntimeState = refreshOutcome === SNAPSHOT_REFRESH_RUNTIME_STATE_DEFERRED;
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
} catch (error) {
|
|
2007
|
+
if (requestIsCurrent()) {
|
|
2008
|
+
state.componentPropertyEdit.error = error instanceof Error ? error.message : String(error);
|
|
2009
|
+
}
|
|
2010
|
+
} finally {
|
|
2011
|
+
if (operationIsCurrent()) {
|
|
2012
|
+
state.componentPropertyEdit.pending = false;
|
|
2013
|
+
state.componentPropertyEdit.focused = false;
|
|
2014
|
+
if (updated && !refreshed && !refreshDeferredForRuntimeState && state.componentPropertyEdit.error === null) {
|
|
2015
|
+
state.componentPropertyEdit.error = COMPONENT_PROPERTY_EDIT_ERROR;
|
|
2016
|
+
}
|
|
2017
|
+
if (!runtimeStatePresentationHasFocus()) renderInspector();
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
function readComponentPropertyEditorValue(editor, valueType) {
|
|
2023
|
+
if (valueType === 'boolean') return Boolean(editor.checked);
|
|
2024
|
+
if (valueType === 'number') {
|
|
2025
|
+
const input = editor.value.trim();
|
|
2026
|
+
if (!input) return undefined;
|
|
2027
|
+
const value = Number(input);
|
|
2028
|
+
return Number.isFinite(value) && !Object.is(value, -0) ? value : undefined;
|
|
2029
|
+
}
|
|
2030
|
+
if (valueType !== 'string') return undefined;
|
|
2031
|
+
try {
|
|
2032
|
+
const value = JSON.parse(editor.value);
|
|
2033
|
+
return typeof value === 'string' ? value : undefined;
|
|
2034
|
+
} catch (_error) {
|
|
2035
|
+
return undefined;
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
function componentMetadata(node) {
|
|
2040
|
+
if (!node.component) return {};
|
|
2041
|
+
return {
|
|
2042
|
+
...(node.component.elementId === undefined ? {} : { elementId: node.component.elementId }),
|
|
2043
|
+
key: node.component.key,
|
|
2044
|
+
name: node.component.name,
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
function renderComponentProperties(node, editorModels) {
|
|
2049
|
+
if (node.component?.properties === undefined || !targetSupports('component-properties')) return '';
|
|
2050
|
+
const editable = targetSupports('component-property-edit') && state.componentPropertyEdit.error === null;
|
|
2051
|
+
return `
|
|
2052
|
+
<section class="component-properties" aria-label="Valdi props">
|
|
2053
|
+
<div class="rule-header">Valdi props <span class="rule-origin">${editable ? 'editable scalars' : 'read only'}</span></div>
|
|
2054
|
+
${state.componentPropertyEdit.error ? `<div class="component-property-error" role="alert">${escapeHtml(state.componentPropertyEdit.error)}</div>` : ''}
|
|
2055
|
+
<div class="property-list">${componentPropertyRows(node, editorModels)}</div>
|
|
2056
|
+
</section>
|
|
2057
|
+
`;
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2060
|
+
function renderStyles(node) {
|
|
2061
|
+
const attributes = nodeAttributes(node);
|
|
2062
|
+
const domStyle = node.element?.dom?.attributes?.style
|
|
2063
|
+
? valdiDebuggerTreeModel.formatValue(node.element.dom.attributes.style, 0)
|
|
2064
|
+
: '';
|
|
2065
|
+
return `
|
|
2066
|
+
<div class="rule-header">element.style <span class="rule-origin">Valdi ${escapeHtml(valdiDebuggerTreeModel.formatValue(node.tag, 0))}</span></div>
|
|
2067
|
+
<div>{</div><div class="property-list">${propertyRows(attributes, { css: true })}</div><div>}</div>
|
|
2068
|
+
${
|
|
2069
|
+
domStyle
|
|
2070
|
+
? `<div class="rule-header">DOM style <span class="rule-origin">rendered</span></div><div>{</div><div class="property-list">${domStyle
|
|
2071
|
+
.split(';')
|
|
2072
|
+
.map(rule => rule.trim())
|
|
2073
|
+
.filter(Boolean)
|
|
2074
|
+
.map(rule => {
|
|
2075
|
+
const [name, ...value] = rule.split(':');
|
|
2076
|
+
return `<div class="property-row"><span class="property-name">${escapeHtml(name)}</span>: ${escapeHtml(value.join(':').trim())};</div>`;
|
|
2077
|
+
})
|
|
2078
|
+
.join('')}</div><div>}</div>`
|
|
2079
|
+
: ''
|
|
2080
|
+
}
|
|
2081
|
+
`;
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
function edgeValues(attributes, prefix) {
|
|
2085
|
+
const all = attributes[prefix];
|
|
2086
|
+
return {
|
|
2087
|
+
top: attributes[`${prefix}Top`] ?? all ?? 0,
|
|
2088
|
+
right: attributes[`${prefix}Right`] ?? all ?? 0,
|
|
2089
|
+
bottom: attributes[`${prefix}Bottom`] ?? all ?? 0,
|
|
2090
|
+
left: attributes[`${prefix}Left`] ?? all ?? 0,
|
|
2091
|
+
};
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
function renderComputed(node) {
|
|
2095
|
+
const attributes = nodeAttributes(node);
|
|
2096
|
+
const bounds = node.bounds || {};
|
|
2097
|
+
const margin = edgeValues(attributes, 'margin');
|
|
2098
|
+
const padding = edgeValues(attributes, 'padding');
|
|
2099
|
+
const computed = {
|
|
2100
|
+
width: `${formatNumber(bounds.width)} px`,
|
|
2101
|
+
height: `${formatNumber(bounds.height)} px`,
|
|
2102
|
+
x: `${formatNumber(bounds.x)} px`,
|
|
2103
|
+
y: `${formatNumber(bounds.y)} px`,
|
|
2104
|
+
display: attributes.flexDirection ? 'flex' : 'block',
|
|
2105
|
+
position: attributes.position || 'relative',
|
|
2106
|
+
...(attributes.flexDirection ? { 'flex-direction': attributes.flexDirection } : {}),
|
|
2107
|
+
...(attributes.alignItems ? { 'align-items': attributes.alignItems } : {}),
|
|
2108
|
+
...(attributes.justifyContent ? { 'justify-content': attributes.justifyContent } : {}),
|
|
2109
|
+
...(attributes.gap !== undefined ? { gap: `${attributes.gap} px` } : {}),
|
|
2110
|
+
...(attributes.backgroundColor ? { background: attributes.backgroundColor } : {}),
|
|
2111
|
+
...(attributes.color ? { color: attributes.color } : {}),
|
|
2112
|
+
};
|
|
2113
|
+
return `
|
|
2114
|
+
<div class="box-model">
|
|
2115
|
+
<div class="box-layer margin"><span class="box-label">margin ${escapeHtml(valdiDebuggerTreeModel.formatValue(margin.top, 0))} ${escapeHtml(valdiDebuggerTreeModel.formatValue(margin.right, 0))} ${escapeHtml(valdiDebuggerTreeModel.formatValue(margin.bottom, 0))} ${escapeHtml(valdiDebuggerTreeModel.formatValue(margin.left, 0))}</span>
|
|
2116
|
+
<div class="box-layer border"><span class="box-label">border</span>
|
|
2117
|
+
<div class="box-layer padding"><span class="box-label">padding ${escapeHtml(valdiDebuggerTreeModel.formatValue(padding.top, 0))} ${escapeHtml(valdiDebuggerTreeModel.formatValue(padding.right, 0))} ${escapeHtml(valdiDebuggerTreeModel.formatValue(padding.bottom, 0))} ${escapeHtml(valdiDebuggerTreeModel.formatValue(padding.left, 0))}</span>
|
|
2118
|
+
<div class="box-layer content">${formatNumber(bounds.width)} × ${formatNumber(bounds.height)}</div>
|
|
2119
|
+
</div>
|
|
2120
|
+
</div>
|
|
2121
|
+
</div>
|
|
2122
|
+
</div>
|
|
2123
|
+
<table class="computed-list">${Object.entries(computed)
|
|
2124
|
+
.map(
|
|
2125
|
+
([key, value]) =>
|
|
2126
|
+
`<tr><td>${escapeHtml(key)}</td><td>${escapeHtml(valdiDebuggerTreeModel.formatValue(value, 0))}</td></tr>`,
|
|
2127
|
+
)
|
|
2128
|
+
.join('')}</table>
|
|
2129
|
+
`;
|
|
2130
|
+
}
|
|
2131
|
+
|
|
2132
|
+
function renderInspector() {
|
|
2133
|
+
const node = findNode(state.selectedNodeId);
|
|
2134
|
+
if (!node) {
|
|
2135
|
+
elements.inspector.innerHTML = '<div class="empty-state">Select a Valdi element to inspect it.</div>';
|
|
2136
|
+
return;
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
const renderedNode = inspectedNode(node);
|
|
2140
|
+
const componentPropertyEditorModels = [];
|
|
2141
|
+
const renderMarkup = markup => {
|
|
2142
|
+
elements.inspector.innerHTML = markup;
|
|
2143
|
+
hydrateComponentPropertyEditors(componentPropertyEditorModels);
|
|
2144
|
+
};
|
|
2145
|
+
if (state.activeDetail === 'state') {
|
|
2146
|
+
renderMarkup(renderSelectedRuntimeState(node));
|
|
2147
|
+
return;
|
|
2148
|
+
}
|
|
2149
|
+
const componentProperties = renderComponentProperties(node, componentPropertyEditorModels);
|
|
2150
|
+
if (node.component && renderedNode === node) {
|
|
2151
|
+
renderMarkup(
|
|
2152
|
+
`<div class="rule-header">Valdi component <span class="rule-origin">${escapeHtml(node.tag)}</span></div>${propertyRows(componentMetadata(node), { css: false })}${componentProperties}<div class="empty-state">This component does not currently render a backing element.</div>`,
|
|
2153
|
+
);
|
|
2154
|
+
return;
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
if (state.activeDetail === 'styles') {
|
|
2158
|
+
renderMarkup(`${componentProperties}${renderStyles(renderedNode)}`);
|
|
2159
|
+
} else if (state.activeDetail === 'computed') {
|
|
2160
|
+
renderMarkup(`${componentProperties}${renderComputed(renderedNode)}`);
|
|
2161
|
+
} else {
|
|
2162
|
+
const textContent = renderedNode.element?.dom?.textContent
|
|
2163
|
+
? valdiDebuggerTreeModel.formatValue(renderedNode.element.dom.textContent, 0)
|
|
2164
|
+
: '';
|
|
2165
|
+
const componentDetails = node.component
|
|
2166
|
+
? `<div class="rule-header">Valdi component <span class="rule-origin">${escapeHtml(node.tag)}</span></div>${propertyRows(componentMetadata(node), { css: false })}`
|
|
2167
|
+
: '';
|
|
2168
|
+
renderMarkup(
|
|
2169
|
+
`${componentDetails}${componentProperties}<div class="rule-header">Rendered <${escapeHtml(valdiDebuggerTreeModel.formatValue(renderedNode.element?.dom?.tagName || 'div', 0))}></div>${propertyRows(renderedNode.element?.dom?.attributes, { css: false })}${textContent ? `<div class="rule-header">Text content</div><pre class="json-view">${escapeHtml(textContent)}</pre>` : ''}`,
|
|
2170
|
+
);
|
|
2171
|
+
}
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
function renderBreadcrumbs() {
|
|
2175
|
+
const path = findNodePath(state.selectedNodeId);
|
|
2176
|
+
elements.breadcrumbs.innerHTML = path
|
|
2177
|
+
.map(
|
|
2178
|
+
(node, index) =>
|
|
2179
|
+
`${index ? ' › ' : ''}<button class="breadcrumb" data-breadcrumb-id="${escapeHtml(nodeId(node))}">${escapeHtml(node.tag || 'view')}</button>`,
|
|
2180
|
+
)
|
|
2181
|
+
.join('');
|
|
2182
|
+
elements.nodeSummary.textContent = `${nodeCount()} nodes`;
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
function render() {
|
|
2186
|
+
renderTree();
|
|
2187
|
+
renderInspector();
|
|
2188
|
+
renderBreadcrumbs();
|
|
2189
|
+
if (state.activeSection === 'state') renderRuntimeStateSection();
|
|
2190
|
+
}
|
|
2191
|
+
|
|
2192
|
+
function selectNode(id) {
|
|
2193
|
+
const node = findNode(id);
|
|
2194
|
+
if (!node) return;
|
|
2195
|
+
const selectedNodeId = nodeId(node);
|
|
2196
|
+
resetRuntimeStateForSelectionChange(selectedNodeId);
|
|
2197
|
+
state.selectedNodeId = selectedNodeId;
|
|
2198
|
+
revealPath(state.selectedNodeId);
|
|
2199
|
+
render();
|
|
2200
|
+
}
|
|
2201
|
+
|
|
2202
|
+
function scrollSelectedTreeRowIntoView() {
|
|
2203
|
+
document.getElementById(treeRowId(state.selectedNodeId))?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
function handleTreeNavigation(event) {
|
|
2207
|
+
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
|
|
2208
|
+
const key = event.key;
|
|
2209
|
+
if (!['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(key)) return;
|
|
2210
|
+
|
|
2211
|
+
event.preventDefault();
|
|
2212
|
+
event.stopPropagation();
|
|
2213
|
+
const rows = Array.from(elements.tree.querySelectorAll('.tree-row'));
|
|
2214
|
+
if (!rows.length) return;
|
|
2215
|
+
|
|
2216
|
+
const selectedIndex = rows.findIndex(row => row.dataset.nodeId === state.selectedNodeId);
|
|
2217
|
+
const selectedNode = findNode(state.selectedNodeId);
|
|
2218
|
+
let nextNodeId = null;
|
|
2219
|
+
|
|
2220
|
+
if (key === 'ArrowUp') {
|
|
2221
|
+
nextNodeId = rows[Math.max(0, selectedIndex - 1)]?.dataset.nodeId;
|
|
2222
|
+
} else if (key === 'ArrowDown') {
|
|
2223
|
+
nextNodeId = rows[Math.min(rows.length - 1, selectedIndex + 1)]?.dataset.nodeId;
|
|
2224
|
+
} else if (key === 'Home') {
|
|
2225
|
+
nextNodeId = rows[0].dataset.nodeId;
|
|
2226
|
+
} else if (key === 'End') {
|
|
2227
|
+
nextNodeId = rows[rows.length - 1].dataset.nodeId;
|
|
2228
|
+
} else if (key === 'ArrowRight' && selectedNode) {
|
|
2229
|
+
const children = valdiDebuggerTreeModel.children(selectedNode);
|
|
2230
|
+
const expanded = Boolean(state.search.trim()) || state.expandedNodeIds.has(state.selectedNodeId);
|
|
2231
|
+
if (children.length && !expanded) {
|
|
2232
|
+
state.expandedNodeIds.add(state.selectedNodeId);
|
|
2233
|
+
renderTree();
|
|
2234
|
+
} else if (children.length) {
|
|
2235
|
+
nextNodeId = rows[selectedIndex + 1]?.dataset.nodeId;
|
|
2236
|
+
}
|
|
2237
|
+
} else if (key === 'ArrowLeft' && selectedNode) {
|
|
2238
|
+
if (
|
|
2239
|
+
valdiDebuggerTreeModel.hasChildren(selectedNode) &&
|
|
2240
|
+
state.expandedNodeIds.has(state.selectedNodeId) &&
|
|
2241
|
+
!state.search.trim()
|
|
2242
|
+
) {
|
|
2243
|
+
state.expandedNodeIds.delete(state.selectedNodeId);
|
|
2244
|
+
renderTree();
|
|
2245
|
+
} else {
|
|
2246
|
+
const path = findNodePath(state.selectedNodeId);
|
|
2247
|
+
nextNodeId = path.length > 1 ? nodeId(path[path.length - 2]) : null;
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
|
|
2251
|
+
if (nextNodeId && nextNodeId !== state.selectedNodeId) selectNode(nextNodeId);
|
|
2252
|
+
scrollSelectedTreeRowIntoView();
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2255
|
+
function enqueueHighlightRequest(
|
|
2256
|
+
intentGeneration,
|
|
2257
|
+
target,
|
|
2258
|
+
targetGeneration,
|
|
2259
|
+
snapshotGeneration,
|
|
2260
|
+
identity,
|
|
2261
|
+
nodeIdValue,
|
|
2262
|
+
) {
|
|
2263
|
+
const request = state.highlightRequestTail.then(async () => {
|
|
2264
|
+
if (
|
|
2265
|
+
intentGeneration !== state.highlightIntentGeneration ||
|
|
2266
|
+
state.targetGeneration !== targetGeneration ||
|
|
2267
|
+
state.target?.id !== target.id ||
|
|
2268
|
+
state.snapshotGeneration !== snapshotGeneration
|
|
2269
|
+
) {
|
|
2270
|
+
return;
|
|
2271
|
+
}
|
|
2272
|
+
try {
|
|
2273
|
+
await requestJson(
|
|
2274
|
+
'/api/devtools/highlight',
|
|
2275
|
+
{},
|
|
2276
|
+
{
|
|
2277
|
+
body: {
|
|
2278
|
+
...identity,
|
|
2279
|
+
...(nodeIdValue ? { nodeId: nodeIdValue } : {}),
|
|
2280
|
+
},
|
|
2281
|
+
},
|
|
2282
|
+
);
|
|
2283
|
+
if (
|
|
2284
|
+
nodeIdValue === null &&
|
|
2285
|
+
intentGeneration === state.highlightIntentGeneration &&
|
|
2286
|
+
state.targetGeneration === targetGeneration
|
|
2287
|
+
) {
|
|
2288
|
+
state.highlightMayBeActive = false;
|
|
2289
|
+
}
|
|
2290
|
+
} catch (error) {
|
|
2291
|
+
console.warn('Unable to update the inspected Valdi highlight.', error);
|
|
2292
|
+
}
|
|
2293
|
+
});
|
|
2294
|
+
state.highlightRequestTail = request.catch(error => {
|
|
2295
|
+
console.warn('Unable to order the inspected Valdi highlight request.', error);
|
|
2296
|
+
});
|
|
2297
|
+
}
|
|
2298
|
+
|
|
2299
|
+
function queueHighlight(nodeIdValue) {
|
|
2300
|
+
if (
|
|
2301
|
+
!state.target ||
|
|
2302
|
+
!targetSupports('highlight') ||
|
|
2303
|
+
(state.hoveredNodeId === nodeIdValue &&
|
|
2304
|
+
state.hoveredSnapshotGeneration === state.snapshotGeneration &&
|
|
2305
|
+
!(nodeIdValue === null && state.highlightMayBeActive))
|
|
2306
|
+
)
|
|
2307
|
+
return;
|
|
2308
|
+
const target = state.target;
|
|
2309
|
+
const targetGeneration = state.targetGeneration;
|
|
2310
|
+
const identity = targetIdentityParameters(target);
|
|
2311
|
+
const snapshotGeneration = state.snapshotGeneration;
|
|
2312
|
+
const intentGeneration = ++state.highlightIntentGeneration;
|
|
2313
|
+
state.hoveredNodeId = nodeIdValue;
|
|
2314
|
+
state.hoveredSnapshotGeneration = snapshotGeneration;
|
|
2315
|
+
if (state.highlightTimer) window.clearTimeout(state.highlightTimer);
|
|
2316
|
+
state.highlightTimer = window.setTimeout(
|
|
2317
|
+
() => {
|
|
2318
|
+
state.highlightTimer = null;
|
|
2319
|
+
if (
|
|
2320
|
+
state.targetGeneration !== targetGeneration ||
|
|
2321
|
+
state.target?.id !== target.id ||
|
|
2322
|
+
state.snapshotGeneration !== snapshotGeneration
|
|
2323
|
+
)
|
|
2324
|
+
return;
|
|
2325
|
+
if (nodeIdValue !== null) state.highlightMayBeActive = true;
|
|
2326
|
+
enqueueHighlightRequest(intentGeneration, target, targetGeneration, snapshotGeneration, identity, nodeIdValue);
|
|
2327
|
+
},
|
|
2328
|
+
nodeIdValue ? 80 : 20,
|
|
2329
|
+
);
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
function renderPerformanceMetric(label, value) {
|
|
2333
|
+
return `<div class="metric-card"><div class="metric-label">${escapeHtml(label)}</div><div class="metric-value">${escapeHtml(value)}</div></div>`;
|
|
2334
|
+
}
|
|
2335
|
+
|
|
2336
|
+
function recordPerformanceSample(data) {
|
|
2337
|
+
const uptimeMs = Number(data?.uptimeMs);
|
|
2338
|
+
if (!Number.isFinite(uptimeMs) || uptimeMs < 0) return;
|
|
2339
|
+
const samples = state.performance.samples;
|
|
2340
|
+
const previous = samples[samples.length - 1];
|
|
2341
|
+
if (previous?.uptimeMs === uptimeMs) return;
|
|
2342
|
+
if (previous && previous.uptimeMs > uptimeMs) samples.length = 0;
|
|
2343
|
+
const sample = { uptimeMs };
|
|
2344
|
+
for (const [property, value] of [
|
|
2345
|
+
['heapUsedBytes', data?.memory?.usedBytes],
|
|
2346
|
+
['layoutDurationMs', data?.mainThread?.layoutDurationMs],
|
|
2347
|
+
['resourceCount', data?.resourceCount],
|
|
2348
|
+
['scriptDurationMs', data?.mainThread?.scriptDurationMs],
|
|
2349
|
+
['taskDurationMs', data?.mainThread?.taskDurationMs],
|
|
2350
|
+
]) {
|
|
2351
|
+
const numeric = Number(value);
|
|
2352
|
+
if (Number.isFinite(numeric) && numeric >= 0) sample[property] = numeric;
|
|
2353
|
+
}
|
|
2354
|
+
samples.push(sample);
|
|
2355
|
+
if (samples.length > MAX_PERFORMANCE_SAMPLES) {
|
|
2356
|
+
samples.splice(0, samples.length - MAX_PERFORMANCE_SAMPLES);
|
|
2357
|
+
}
|
|
2358
|
+
}
|
|
2359
|
+
|
|
2360
|
+
function performanceGraphPath(points, minimum, maximum) {
|
|
2361
|
+
if (!points.length) return '';
|
|
2362
|
+
const firstTime = points[0].time;
|
|
2363
|
+
const lastTime = points[points.length - 1].time;
|
|
2364
|
+
const timeSpan = Math.max(lastTime - firstTime, 1);
|
|
2365
|
+
const valueSpan = Math.max(maximum - minimum, 1);
|
|
2366
|
+
return points
|
|
2367
|
+
.map((point, index) => {
|
|
2368
|
+
const x = points.length === 1 ? 100 : ((point.time - firstTime) / timeSpan) * 100;
|
|
2369
|
+
const y = 27 - Math.max(0, Math.min(1, (point.value - minimum) / valueSpan)) * 23;
|
|
2370
|
+
return `${index === 0 ? 'M' : 'L'}${x.toFixed(2)} ${y.toFixed(2)}`;
|
|
2371
|
+
})
|
|
2372
|
+
.join(' ');
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2375
|
+
function renderSampledPerformanceMetric(label, kind, property, formattedValue) {
|
|
2376
|
+
const points = state.performance.samples
|
|
2377
|
+
.filter(sample => Number.isFinite(sample[property]))
|
|
2378
|
+
.map(sample => ({ time: sample.uptimeMs, value: sample[property] }));
|
|
2379
|
+
if (!points.length) return renderPerformanceMetric(label, formattedValue);
|
|
2380
|
+
const minimum = Math.min(...points.map(point => point.value));
|
|
2381
|
+
const maximum = Math.max(...points.map(point => point.value));
|
|
2382
|
+
const padding = Math.max((maximum - minimum) * 0.12, maximum * 0.015, 1);
|
|
2383
|
+
const path = performanceGraphPath(points, Math.max(0, minimum - padding), maximum + padding);
|
|
2384
|
+
return `
|
|
2385
|
+
<article class="metric-card metric-card-chart">
|
|
2386
|
+
<div class="metric-label">${escapeHtml(label)}</div>
|
|
2387
|
+
<div class="metric-value">${escapeHtml(formattedValue)}</div>
|
|
2388
|
+
<svg class="performance-sparkline ${escapeHtml(kind)}" viewBox="0 0 100 30" preserveAspectRatio="none" role="img" aria-label="${escapeHtml(label)} over time">
|
|
2389
|
+
<path class="performance-sparkline-baseline" d="M0 27H100" />
|
|
2390
|
+
<path class="performance-sparkline-area" d="${path} L100 27 L0 27 Z" />
|
|
2391
|
+
<path class="performance-sparkline-line" d="${path}" />
|
|
2392
|
+
</svg>
|
|
2393
|
+
</article>
|
|
2394
|
+
`;
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
function performanceScopeMatches(trace, scope) {
|
|
2398
|
+
const name = String(trace?.trace || '');
|
|
2399
|
+
if (scope === 'valdi') return name.startsWith('Valdi.');
|
|
2400
|
+
if (scope === 'browser') return name.startsWith('Browser.');
|
|
2401
|
+
return name.startsWith('Valdi.') || name.startsWith('Browser.');
|
|
2402
|
+
}
|
|
2403
|
+
|
|
2404
|
+
function filteredPerformanceTraces(result) {
|
|
2405
|
+
const search = String(state.performance.traceSearch || '')
|
|
2406
|
+
.trim()
|
|
2407
|
+
.toLowerCase();
|
|
2408
|
+
const traces = Array.isArray(result?.traces) ? result.traces : [];
|
|
2409
|
+
return traces.filter(
|
|
2410
|
+
trace =>
|
|
2411
|
+
performanceScopeMatches(trace, state.performance.traceScope) &&
|
|
2412
|
+
(!search ||
|
|
2413
|
+
String(trace.trace || '')
|
|
2414
|
+
.toLowerCase()
|
|
2415
|
+
.includes(search)),
|
|
2416
|
+
);
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
function performanceScopeCounts(traces) {
|
|
2420
|
+
const counts = { all: 0, browser: 0, valdi: 0 };
|
|
2421
|
+
for (const trace of traces) {
|
|
2422
|
+
if (!performanceScopeMatches(trace, 'all')) continue;
|
|
2423
|
+
counts.all++;
|
|
2424
|
+
if (performanceScopeMatches(trace, 'valdi')) counts.valdi++;
|
|
2425
|
+
if (performanceScopeMatches(trace, 'browser')) counts.browser++;
|
|
2426
|
+
}
|
|
2427
|
+
return counts;
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
function performanceLane(trace) {
|
|
2431
|
+
const name = String(trace?.trace || '');
|
|
2432
|
+
if (name.startsWith('Valdi.')) return 'valdi';
|
|
2433
|
+
if (name.startsWith('Browser.Layout.')) return 'layout';
|
|
2434
|
+
if (name.startsWith('Browser.Paint.')) return 'paint';
|
|
2435
|
+
if (name.startsWith('Browser.Frames.')) return 'frames';
|
|
2436
|
+
if (name.startsWith('Browser.GC.')) return 'gc';
|
|
2437
|
+
return 'script';
|
|
2438
|
+
}
|
|
2439
|
+
|
|
2440
|
+
function renderPerformanceTimeline(result) {
|
|
2441
|
+
const traces = Array.isArray(result?.traces) ? result.traces : [];
|
|
2442
|
+
const counts = performanceScopeCounts(traces);
|
|
2443
|
+
const scopes = [
|
|
2444
|
+
['valdi', 'Valdi'],
|
|
2445
|
+
['browser', 'Browser'],
|
|
2446
|
+
['all', 'All'],
|
|
2447
|
+
];
|
|
2448
|
+
const controls = `
|
|
2449
|
+
<div class="performance-trace-filters">
|
|
2450
|
+
<div class="performance-scope-group" role="group" aria-label="Trace event scope">
|
|
2451
|
+
${scopes
|
|
2452
|
+
.map(
|
|
2453
|
+
([scope, label]) =>
|
|
2454
|
+
`<button type="button" class="performance-scope-button${state.performance.traceScope === scope ? ' selected' : ''}" data-performance-scope="${scope}" aria-pressed="${state.performance.traceScope === scope ? 'true' : 'false'}">${label} <span>${escapeHtml(formatNumber(counts[scope]))}</span></button>`,
|
|
2455
|
+
)
|
|
2456
|
+
.join('')}
|
|
2457
|
+
</div>
|
|
2458
|
+
<input id="performanceTraceFilter" class="performance-trace-search" type="search" value="${escapeHtml(state.performance.traceSearch)}" placeholder="Filter trace names" aria-label="Filter trace names" />
|
|
2459
|
+
</div>
|
|
2460
|
+
`;
|
|
2461
|
+
if (!traces.length) {
|
|
2462
|
+
return `${controls}<div class="empty-state">Record an interaction to inspect browser and Valdi renderer events.</div>`;
|
|
2463
|
+
}
|
|
2464
|
+
const filtered = filteredPerformanceTraces(result);
|
|
2465
|
+
if (!filtered.length) return `${controls}<div class="empty-state">No captured events match this filter.</div>`;
|
|
2466
|
+
|
|
2467
|
+
let firstTimestamp = Infinity;
|
|
2468
|
+
let lastTimestamp = -Infinity;
|
|
2469
|
+
for (const trace of filtered) {
|
|
2470
|
+
firstTimestamp = Math.min(firstTimestamp, Number(trace.startMicros));
|
|
2471
|
+
lastTimestamp = Math.max(lastTimestamp, Number(trace.endMicros));
|
|
2472
|
+
}
|
|
2473
|
+
const spanMicros = Math.max(lastTimestamp - firstTimestamp, 1000);
|
|
2474
|
+
const displayed = filtered.slice(0, MAX_PERFORMANCE_TIMELINE_ROWS);
|
|
2475
|
+
const rows = displayed
|
|
2476
|
+
.map(trace => {
|
|
2477
|
+
const startMicros = Number(trace.startMicros);
|
|
2478
|
+
const durationMicros = Math.max(0, Number(trace.endMicros) - startMicros);
|
|
2479
|
+
const offset = Math.max(0, Math.min(100, ((startMicros - firstTimestamp) / spanMicros) * 100));
|
|
2480
|
+
const width = Math.max(0.65, Math.min(100 - offset, (durationMicros / spanMicros) * 100));
|
|
2481
|
+
const duration = trace.type === 1 ? 'instant' : formatDuration(durationMicros / 1000);
|
|
2482
|
+
const name = String(trace.trace || '').replace(/^Browser\./, '');
|
|
2483
|
+
return `
|
|
2484
|
+
<div class="performance-timeline-row" title="${escapeHtml(trace.trace)}">
|
|
2485
|
+
<span class="performance-event-name">${escapeHtml(name)}</span>
|
|
2486
|
+
<span class="performance-event-track"><span class="performance-event-bar ${performanceLane(trace)}" style="left:${offset.toFixed(3)}%;width:${width.toFixed(3)}%"></span></span>
|
|
2487
|
+
<span class="performance-event-duration">${escapeHtml(duration)}</span>
|
|
2488
|
+
</div>
|
|
2489
|
+
`;
|
|
2490
|
+
})
|
|
2491
|
+
.join('');
|
|
2492
|
+
const truncated =
|
|
2493
|
+
filtered.length > displayed.length
|
|
2494
|
+
? `<div class="performance-caption">Showing ${formatNumber(displayed.length)} of ${formatNumber(filtered.length)} matching events. Export includes every bounded event.</div>`
|
|
2495
|
+
: '';
|
|
2496
|
+
return `
|
|
2497
|
+
${controls}
|
|
2498
|
+
<div class="performance-legend">
|
|
2499
|
+
<span class="performance-legend-item valdi">Valdi</span>
|
|
2500
|
+
<span class="performance-legend-item script">JavaScript</span>
|
|
2501
|
+
<span class="performance-legend-item layout">Layout</span>
|
|
2502
|
+
<span class="performance-legend-item paint">Paint</span>
|
|
2503
|
+
<span class="performance-legend-item frames">Frames</span>
|
|
2504
|
+
<span class="performance-legend-item gc">GC</span>
|
|
2505
|
+
</div>
|
|
2506
|
+
<div class="performance-timeline">${rows}</div>
|
|
2507
|
+
${truncated}
|
|
2508
|
+
`;
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2511
|
+
function renderPerformanceSummary(result) {
|
|
2512
|
+
const grouped = new Map();
|
|
2513
|
+
for (const trace of filteredPerformanceTraces(result)) {
|
|
2514
|
+
const name = String(trace.trace || '');
|
|
2515
|
+
const event = grouped.get(name) || { count: 0, durationMs: 0, name };
|
|
2516
|
+
event.count++;
|
|
2517
|
+
event.durationMs += Math.max(0, Number(trace.endMicros) - Number(trace.startMicros)) / 1000;
|
|
2518
|
+
grouped.set(name, event);
|
|
2519
|
+
}
|
|
2520
|
+
const rows = Array.from(grouped.values())
|
|
2521
|
+
.sort((left, right) => right.durationMs - left.durationMs || right.count - left.count)
|
|
2522
|
+
.slice(0, MAX_PERFORMANCE_SUMMARY_ROWS)
|
|
2523
|
+
.map(
|
|
2524
|
+
event =>
|
|
2525
|
+
`<tr><td>${escapeHtml(event.name)}</td><td>${escapeHtml(formatNumber(event.count))}</td><td>${escapeHtml(formatDuration(event.durationMs))}</td></tr>`,
|
|
2526
|
+
)
|
|
2527
|
+
.join('');
|
|
2528
|
+
if (!rows) return '';
|
|
2529
|
+
return `
|
|
2530
|
+
<div class="utility-heading">Total captured duration by event</div>
|
|
2531
|
+
<table class="performance-results-table"><thead><tr><th>Operation</th><th>Calls</th><th>Inclusive total</th></tr></thead><tbody>${rows}</tbody></table>
|
|
2532
|
+
`;
|
|
2533
|
+
}
|
|
2534
|
+
|
|
2535
|
+
function performanceButton(label, action, options = {}) {
|
|
2536
|
+
return `<button type="button" class="performance-button${options.primary ? ' primary' : ''}" data-performance-action="${escapeHtml(action)}"${options.disabled ? ' disabled' : ''}>${escapeHtml(label)}</button>`;
|
|
2537
|
+
}
|
|
2538
|
+
|
|
2539
|
+
function replacePerformanceContent(html) {
|
|
2540
|
+
const contentScrollTop = elements.performanceContent.scrollTop;
|
|
2541
|
+
const previousTimeline = elements.performanceContent.querySelector?.('.performance-timeline');
|
|
2542
|
+
const timelineScrollLeft = previousTimeline?.scrollLeft ?? 0;
|
|
2543
|
+
const timelineScrollTop = previousTimeline?.scrollTop ?? 0;
|
|
2544
|
+
elements.performanceContent.innerHTML = html;
|
|
2545
|
+
elements.performanceContent.scrollTop = contentScrollTop;
|
|
2546
|
+
const nextTimeline = elements.performanceContent.querySelector?.('.performance-timeline');
|
|
2547
|
+
if (nextTimeline) {
|
|
2548
|
+
nextTimeline.scrollLeft = timelineScrollLeft;
|
|
2549
|
+
nextTimeline.scrollTop = timelineScrollTop;
|
|
2550
|
+
}
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
function renderPerformance(data = state.performance.data) {
|
|
2554
|
+
const perf = state.performance;
|
|
2555
|
+
if (!data) {
|
|
2556
|
+
const error = perf.error ? `<div class="performance-error" role="alert">${escapeHtml(perf.error)}</div>` : '';
|
|
2557
|
+
const ownerRecovery = perf.ownerIdentity
|
|
2558
|
+
? `<section class="performance-recorder-card"><div class="performance-recorder-heading"><strong>Previous web preview recording</strong><span class="performance-status recording" role="status" aria-live="polite">${perf.traceActive ? 'Recording' : 'Result pending'}</span></div><div class="performance-recorder-controls">${performanceButton('Stop and retrieve', 'trace-stop', { disabled: perf.pending, primary: true })}</div></section>`
|
|
2559
|
+
: '';
|
|
2560
|
+
replacePerformanceContent(
|
|
2561
|
+
error || ownerRecovery
|
|
2562
|
+
? `${error}${ownerRecovery}`
|
|
2563
|
+
: '<div class="empty-state">Loading web preview performance…</div>',
|
|
2564
|
+
);
|
|
2565
|
+
return;
|
|
2566
|
+
}
|
|
2567
|
+
perf.data = data;
|
|
2568
|
+
recordPerformanceSample(data);
|
|
2569
|
+
const browserMetrics = perf.lastTrace?.browserMetrics || {};
|
|
2570
|
+
const browserSummary = perf.lastTrace?.browserSummary || {};
|
|
2571
|
+
const metrics = [
|
|
2572
|
+
renderSampledPerformanceMetric('JS heap', 'heap', 'heapUsedBytes', formatBytes(data.memory?.usedBytes)),
|
|
2573
|
+
renderSampledPerformanceMetric(
|
|
2574
|
+
'Main-thread time (page lifetime)',
|
|
2575
|
+
'main-thread',
|
|
2576
|
+
'taskDurationMs',
|
|
2577
|
+
formatDuration(data.mainThread?.taskDurationMs),
|
|
2578
|
+
),
|
|
2579
|
+
renderSampledPerformanceMetric(
|
|
2580
|
+
'JavaScript time (page lifetime)',
|
|
2581
|
+
'script',
|
|
2582
|
+
'scriptDurationMs',
|
|
2583
|
+
formatDuration(data.mainThread?.scriptDurationMs),
|
|
2584
|
+
),
|
|
2585
|
+
renderSampledPerformanceMetric(
|
|
2586
|
+
'Layout time (page lifetime)',
|
|
2587
|
+
'layout',
|
|
2588
|
+
'layoutDurationMs',
|
|
2589
|
+
formatDuration(data.mainThread?.layoutDurationMs),
|
|
2590
|
+
),
|
|
2591
|
+
renderSampledPerformanceMetric('Resources', 'resources', 'resourceCount', formatNumber(data.resourceCount)),
|
|
2592
|
+
renderPerformanceMetric('Page uptime', formatUptime(data.uptimeMs)),
|
|
2593
|
+
];
|
|
2594
|
+
if (perf.lastTrace) {
|
|
2595
|
+
metrics.push(
|
|
2596
|
+
renderPerformanceMetric('Captured events', formatNumber(perf.lastTrace.traceCount)),
|
|
2597
|
+
renderPerformanceMetric('Long tasks', formatNumber(browserSummary.longTaskCount)),
|
|
2598
|
+
renderPerformanceMetric('Layout passes', formatNumber(browserMetrics.LayoutCount)),
|
|
2599
|
+
);
|
|
2600
|
+
}
|
|
2601
|
+
const hasTraceOwner = Boolean(perf.traceActive || perf.ownerIdentity);
|
|
2602
|
+
const rendererStatus = perf.rendererTracingEnabled
|
|
2603
|
+
? '<span class="performance-tracing-badge enabled">Valdi renderer events enabled</span>'
|
|
2604
|
+
: '<span class="performance-tracing-badge disabled">Valdi renderer events disabled</span>';
|
|
2605
|
+
const rendererNotice = perf.rendererTracingEnabled
|
|
2606
|
+
? ''
|
|
2607
|
+
: `<div class="performance-notice">Browser events can be recorded now. Valdi renderer events require reloading the inspected page; reloading can reset page state. ${performanceButton('Enable renderer events', 'enable-tracing', { disabled: perf.pending || hasTraceOwner })}</div>`;
|
|
2608
|
+
const traceStatus = `<span class="performance-status${hasTraceOwner ? ' recording' : ''}" role="status" aria-live="polite">${perf.traceActive ? 'Recording' : perf.ownerIdentity ? 'Result pending' : 'Idle'}</span>`;
|
|
2609
|
+
const traceCaption = perf.lastTrace
|
|
2610
|
+
? `<div class="performance-caption">${escapeHtml(formatNumber(perf.lastTrace.traceCount))} events · ${escapeHtml(formatDuration(perf.lastTrace.elapsedMs))}${perf.lastTrace.droppedTraceEventCount ? ` · ${escapeHtml(formatNumber(perf.lastTrace.droppedTraceEventCount))} dropped` : ''}</div>`
|
|
2611
|
+
: '';
|
|
2612
|
+
const paints = (Array.isArray(data.paints) ? data.paints : [])
|
|
2613
|
+
.map(paint => `<tr><td>${escapeHtml(paint.name)}</td><td>${escapeHtml(formatDuration(paint.startTime))}</td></tr>`)
|
|
2614
|
+
.join('');
|
|
2615
|
+
replacePerformanceContent(`
|
|
2616
|
+
<div class="metric-grid">${metrics.join('')}</div>
|
|
2617
|
+
<div class="performance-caption">Main-thread, JavaScript, and layout counters are cumulative for the current page lifetime.</div>
|
|
2618
|
+
${perf.error ? `<div class="performance-error" role="alert">${escapeHtml(perf.error)}</div>` : ''}
|
|
2619
|
+
<section class="performance-recorder-card">
|
|
2620
|
+
<div class="performance-recorder-heading"><div><strong>Rendering and main-thread trace</strong>${rendererStatus}</div>${traceStatus}</div>
|
|
2621
|
+
<div class="performance-recorder-controls">
|
|
2622
|
+
<label class="performance-duration">Duration <input id="performanceDurationInput" type="number" min="0.1" max="15" step="0.5" value="${escapeHtml(perf.durationSeconds)}" /> s</label>
|
|
2623
|
+
${performanceButton('Start', 'trace-start', { disabled: perf.pending || hasTraceOwner })}
|
|
2624
|
+
${performanceButton('Stop', 'trace-stop', { disabled: perf.pending || !hasTraceOwner, primary: hasTraceOwner })}
|
|
2625
|
+
${performanceButton('Capture', 'trace-capture', { disabled: perf.pending || hasTraceOwner, primary: !hasTraceOwner })}
|
|
2626
|
+
${performanceButton('Export trace', 'trace-export', { disabled: !perf.lastTrace })}
|
|
2627
|
+
</div>
|
|
2628
|
+
${rendererNotice}
|
|
2629
|
+
${traceCaption}
|
|
2630
|
+
${renderPerformanceTimeline(perf.lastTrace)}
|
|
2631
|
+
${renderPerformanceSummary(perf.lastTrace)}
|
|
2632
|
+
</section>
|
|
2633
|
+
<details class="performance-navigation"${perf.navigationExpanded ? ' open' : ''}>
|
|
2634
|
+
<summary>Initial page-load milestones</summary>
|
|
2635
|
+
<div class="performance-caption">DOM ready ${escapeHtml(formatDuration(data.navigation?.domContentLoadedMs))} · Page load ${escapeHtml(formatDuration(data.navigation?.loadMs))} · Transferred ${escapeHtml(formatBytes(data.transferSize))}</div>
|
|
2636
|
+
${paints ? `<table class="performance-results-table"><tbody>${paints}</tbody></table>` : '<div class="empty-state">No paint milestones have been reported.</div>'}
|
|
2637
|
+
</details>
|
|
2638
|
+
`);
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
function buildPerformanceTraceExport(result) {
|
|
2642
|
+
const traces = Array.isArray(result?.traces) ? result.traces : [];
|
|
2643
|
+
const firstTimestamp = traces.reduce(
|
|
2644
|
+
(minimum, trace) => Math.min(minimum, Number(trace.startMicros)),
|
|
2645
|
+
Number(traces[0]?.startMicros || 0),
|
|
2646
|
+
);
|
|
2647
|
+
const threadIds = Array.from(new Set(traces.map(trace => Number(trace.threadId)))).slice(0, 256);
|
|
2648
|
+
const traceEvents = [
|
|
2649
|
+
{ args: { name: 'Valdi web preview' }, name: 'process_name', ph: 'M', pid: 1 },
|
|
2650
|
+
...threadIds.map(threadId => ({
|
|
2651
|
+
args: { name: `Thread ${threadId}` },
|
|
2652
|
+
name: 'thread_name',
|
|
2653
|
+
ph: 'M',
|
|
2654
|
+
pid: 1,
|
|
2655
|
+
tid: threadId,
|
|
2656
|
+
})),
|
|
2657
|
+
];
|
|
2658
|
+
for (const trace of traces) {
|
|
2659
|
+
const instant = trace.type === 1;
|
|
2660
|
+
const event = {
|
|
2661
|
+
cat: String(trace.trace || '').startsWith('Valdi.') ? 'valdi' : 'browser',
|
|
2662
|
+
name: String(trace.trace || ''),
|
|
2663
|
+
ph: instant ? 'i' : 'X',
|
|
2664
|
+
pid: 1,
|
|
2665
|
+
tid: Number(trace.threadId),
|
|
2666
|
+
ts: Number(trace.startMicros) - firstTimestamp,
|
|
2667
|
+
};
|
|
2668
|
+
if (instant) event.s = 't';
|
|
2669
|
+
else event.dur = Math.max(0, Number(trace.endMicros) - Number(trace.startMicros));
|
|
2670
|
+
traceEvents.push(event);
|
|
2671
|
+
}
|
|
2672
|
+
return {
|
|
2673
|
+
displayTimeUnit: 'ms',
|
|
2674
|
+
metadata: result?.perfettoMetadata || {},
|
|
2675
|
+
traceEvents,
|
|
2676
|
+
};
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
function downloadPerformanceTrace(result) {
|
|
2680
|
+
const blob = new Blob([JSON.stringify(buildPerformanceTraceExport(result), null, 2)], {
|
|
2681
|
+
type: 'application/json',
|
|
2682
|
+
});
|
|
2683
|
+
const artifactUrl = URL.createObjectURL(blob);
|
|
2684
|
+
const link = document.createElement('a');
|
|
2685
|
+
link.href = artifactUrl;
|
|
2686
|
+
link.download = `valdi-web-preview-${Date.now()}.trace.json`;
|
|
2687
|
+
link.click();
|
|
2688
|
+
window.setTimeout(() => URL.revokeObjectURL(artifactUrl), 1000);
|
|
2689
|
+
}
|
|
2690
|
+
|
|
2691
|
+
async function refreshPerformance(options = {}) {
|
|
2692
|
+
if (options.silent && performancePollingInputIsFocused()) return;
|
|
2693
|
+
if (
|
|
2694
|
+
!state.target ||
|
|
2695
|
+
!targetSupports('performance') ||
|
|
2696
|
+
state.performance.pending ||
|
|
2697
|
+
state.performance.snapshotPending
|
|
2698
|
+
) {
|
|
2699
|
+
return;
|
|
2700
|
+
}
|
|
2701
|
+
const perf = state.performance;
|
|
2702
|
+
const identity = performanceIdentity();
|
|
2703
|
+
const targetGeneration = state.targetGeneration;
|
|
2704
|
+
const requestGeneration = ++perf.requestGeneration;
|
|
2705
|
+
const requestIsCurrent = () =>
|
|
2706
|
+
targetGeneration === state.targetGeneration &&
|
|
2707
|
+
requestGeneration === perf.requestGeneration &&
|
|
2708
|
+
performanceIdentityIsCurrent(identity);
|
|
2709
|
+
perf.snapshotPending = true;
|
|
2710
|
+
if (!options.silent && !perf.data) renderPerformance();
|
|
2711
|
+
try {
|
|
2712
|
+
const [data, status] = await Promise.all([
|
|
2713
|
+
requestJson('/api/devtools/performance/snapshot', identity, {}),
|
|
2714
|
+
requestJson('/api/devtools/performance/trace/status', identity, {}),
|
|
2715
|
+
]);
|
|
2716
|
+
if (status.completionError) {
|
|
2717
|
+
try {
|
|
2718
|
+
await requestJson('/api/devtools/performance/trace/stop', identity, { body: {} });
|
|
2719
|
+
} catch {
|
|
2720
|
+
// Stop surfaces the retained completion error after clearing it on the server.
|
|
2721
|
+
}
|
|
2722
|
+
if (requestIsCurrent() && (!perf.ownerIdentity || samePerformanceIdentity(perf.ownerIdentity, identity))) {
|
|
2723
|
+
perf.traceActive = false;
|
|
2724
|
+
perf.ownerIdentity = null;
|
|
2725
|
+
}
|
|
2726
|
+
throw new Error(status.completionError);
|
|
2727
|
+
}
|
|
2728
|
+
let completedTrace = null;
|
|
2729
|
+
if (status.completedRecordingAvailable) {
|
|
2730
|
+
completedTrace = await requestJson('/api/devtools/performance/trace/stop', identity, { body: {} });
|
|
2731
|
+
}
|
|
2732
|
+
if (!requestIsCurrent()) return;
|
|
2733
|
+
perf.data = data;
|
|
2734
|
+
if (!perf.ownerIdentity || samePerformanceIdentity(perf.ownerIdentity, identity)) {
|
|
2735
|
+
perf.traceActive = Boolean(status.recording);
|
|
2736
|
+
perf.ownerIdentity = perf.traceActive ? identity : null;
|
|
2737
|
+
}
|
|
2738
|
+
perf.rendererTracingEnabled = Boolean(data.rendererTracingEnabled || status.rendererTracingEnabled);
|
|
2739
|
+
if (completedTrace) {
|
|
2740
|
+
perf.traceActive = false;
|
|
2741
|
+
perf.ownerIdentity = null;
|
|
2742
|
+
perf.lastTrace = completedTrace;
|
|
2743
|
+
}
|
|
2744
|
+
perf.error = null;
|
|
2745
|
+
renderPerformance(data);
|
|
2746
|
+
} catch (error) {
|
|
2747
|
+
if (requestIsCurrent()) {
|
|
2748
|
+
perf.error = error instanceof Error ? error.message : String(error);
|
|
2749
|
+
renderPerformance(perf.data);
|
|
2750
|
+
}
|
|
2751
|
+
} finally {
|
|
2752
|
+
if (requestIsCurrent()) perf.snapshotPending = false;
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
|
|
2756
|
+
function retainStalePerformanceOwnerAfterCleanupFailure(identity, cleanupError, operationGeneration) {
|
|
2757
|
+
const perf = state.performance;
|
|
2758
|
+
if (perf.ownerIdentity) {
|
|
2759
|
+
const ownerDescription = samePerformanceIdentity(perf.ownerIdentity, identity)
|
|
2760
|
+
? 'the same recording is already retained by a newer operation'
|
|
2761
|
+
: 'a different recording is already owned by a newer operation';
|
|
2762
|
+
console.warn(`Unable to retain a stale Performance recording because ${ownerDescription}.`, cleanupError);
|
|
2763
|
+
return;
|
|
2764
|
+
}
|
|
2765
|
+
if (operationGeneration !== perf.operationGeneration && perf.pending) {
|
|
2766
|
+
console.warn('Unable to retain a stale Performance recording while a newer operation is pending.', cleanupError);
|
|
2767
|
+
return;
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2770
|
+
// Exact cleanup failed. Claim a fresh repair generation only when no newer
|
|
2771
|
+
// operation or owner needs the state, then retain the orphaned exact owner.
|
|
2772
|
+
const repairGeneration =
|
|
2773
|
+
operationGeneration === perf.operationGeneration ? operationGeneration : ++perf.operationGeneration;
|
|
2774
|
+
if (repairGeneration !== perf.operationGeneration) return;
|
|
2775
|
+
perf.traceActive = true;
|
|
2776
|
+
perf.ownerIdentity = identity;
|
|
2777
|
+
perf.error = `The previous web preview still owns a performance recording: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`;
|
|
2778
|
+
updateCapabilityUi();
|
|
2779
|
+
if (state.activeSection === 'performance') renderPerformance(perf.data);
|
|
2780
|
+
}
|
|
2781
|
+
|
|
2782
|
+
async function runPerformanceAction(action) {
|
|
2783
|
+
const perf = state.performance;
|
|
2784
|
+
if (action === 'refresh') {
|
|
2785
|
+
await refreshPerformance();
|
|
2786
|
+
return;
|
|
2787
|
+
}
|
|
2788
|
+
if (action === 'trace-export') {
|
|
2789
|
+
if (perf.lastTrace) downloadPerformanceTrace(perf.lastTrace);
|
|
2790
|
+
return;
|
|
2791
|
+
}
|
|
2792
|
+
const stoppingPreviousOwner = action === 'trace-stop' && perf.ownerIdentity;
|
|
2793
|
+
if (perf.pending || (!stoppingPreviousOwner && (!state.target || !targetSupports('performance')))) return;
|
|
2794
|
+
if (['enable-tracing', 'trace-capture', 'trace-start'].includes(action) && (perf.traceActive || perf.ownerIdentity)) {
|
|
2795
|
+
return;
|
|
2796
|
+
}
|
|
2797
|
+
if (
|
|
2798
|
+
action === 'enable-tracing' &&
|
|
2799
|
+
!window.confirm('Enable Valdi renderer events? This reloads the inspected page and can reset page state.')
|
|
2800
|
+
) {
|
|
2801
|
+
return;
|
|
2802
|
+
}
|
|
2803
|
+
|
|
2804
|
+
const selectedIdentity = state.target && targetSupports('performance') ? performanceIdentity() : null;
|
|
2805
|
+
const targetGeneration = state.targetGeneration;
|
|
2806
|
+
const identity = stoppingPreviousOwner ? perf.ownerIdentity : selectedIdentity;
|
|
2807
|
+
if (!identity) return;
|
|
2808
|
+
perf.requestGeneration++;
|
|
2809
|
+
perf.snapshotPending = false;
|
|
2810
|
+
const operationGeneration = ++perf.operationGeneration;
|
|
2811
|
+
const operationIsCurrent = () => operationGeneration === perf.operationGeneration;
|
|
2812
|
+
const selectedTargetIsCurrent = () =>
|
|
2813
|
+
operationIsCurrent() &&
|
|
2814
|
+
selectedIdentity !== null &&
|
|
2815
|
+
targetGeneration === state.targetGeneration &&
|
|
2816
|
+
performanceIdentityIsCurrent(selectedIdentity);
|
|
2817
|
+
const operationOwnsTrace = () => samePerformanceIdentity(perf.ownerIdentity, identity);
|
|
2818
|
+
let refreshSelectedTarget = false;
|
|
2819
|
+
perf.pending = true;
|
|
2820
|
+
perf.error = null;
|
|
2821
|
+
renderPerformance(perf.data);
|
|
2822
|
+
try {
|
|
2823
|
+
if (action === 'enable-tracing') {
|
|
2824
|
+
await requestJson('/api/devtools/performance/trace/enable', identity, { body: {} });
|
|
2825
|
+
if (!selectedTargetIsCurrent()) return;
|
|
2826
|
+
perf.rendererTracingEnabled = true;
|
|
2827
|
+
addConsoleEntry('info', 'Reloaded the inspected page with Valdi renderer events enabled.');
|
|
2828
|
+
} else {
|
|
2829
|
+
const operation = action.slice('trace-'.length);
|
|
2830
|
+
const durationMs = Math.round(Math.max(0.1, Math.min(15, Number(perf.durationSeconds) || 3)) * 1000);
|
|
2831
|
+
if (operation === 'capture') {
|
|
2832
|
+
perf.traceActive = true;
|
|
2833
|
+
perf.ownerIdentity = identity;
|
|
2834
|
+
renderPerformance(perf.data);
|
|
2835
|
+
}
|
|
2836
|
+
const result = await requestJson(`/api/devtools/performance/trace/${operation}`, identity, {
|
|
2837
|
+
body: operation === 'capture' ? { durationMs } : {},
|
|
2838
|
+
});
|
|
2839
|
+
if (operation === 'start') {
|
|
2840
|
+
if (!selectedTargetIsCurrent()) {
|
|
2841
|
+
if (result.recording) {
|
|
2842
|
+
try {
|
|
2843
|
+
await requestJson('/api/devtools/performance/trace/stop', identity, { body: {} });
|
|
2844
|
+
} catch (cleanupError) {
|
|
2845
|
+
retainStalePerformanceOwnerAfterCleanupFailure(identity, cleanupError, operationGeneration);
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
return;
|
|
2849
|
+
}
|
|
2850
|
+
perf.traceActive = Boolean(result.recording);
|
|
2851
|
+
perf.ownerIdentity = perf.traceActive ? identity : null;
|
|
2852
|
+
refreshSelectedTarget = true;
|
|
2853
|
+
} else {
|
|
2854
|
+
if (!operationIsCurrent()) return;
|
|
2855
|
+
const completedOwnedTrace = ['capture', 'stop'].includes(operation) && operationOwnsTrace();
|
|
2856
|
+
const completedPreviousOwner = completedOwnedTrace && !samePerformanceIdentity(identity, selectedIdentity);
|
|
2857
|
+
if (completedOwnedTrace) {
|
|
2858
|
+
perf.traceActive = false;
|
|
2859
|
+
perf.ownerIdentity = null;
|
|
2860
|
+
}
|
|
2861
|
+
if (completedPreviousOwner) {
|
|
2862
|
+
perf.data = null;
|
|
2863
|
+
perf.lastTrace = null;
|
|
2864
|
+
perf.rendererTracingEnabled = false;
|
|
2865
|
+
perf.samples = [];
|
|
2866
|
+
}
|
|
2867
|
+
if (selectedTargetIsCurrent() && !completedPreviousOwner) {
|
|
2868
|
+
perf.traceActive = false;
|
|
2869
|
+
perf.ownerIdentity = null;
|
|
2870
|
+
perf.lastTrace = result;
|
|
2871
|
+
}
|
|
2872
|
+
refreshSelectedTarget = selectedTargetIsCurrent();
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
} catch (error) {
|
|
2876
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2877
|
+
if (action === 'trace-capture' && selectedTargetIsCurrent()) refreshSelectedTarget = true;
|
|
2878
|
+
if (operationIsCurrent() && (selectedTargetIsCurrent() || operationOwnsTrace())) {
|
|
2879
|
+
perf.error = message;
|
|
2880
|
+
if (state.activeSection === 'performance') renderPerformance(perf.data);
|
|
2881
|
+
} else {
|
|
2882
|
+
console.warn('Ignoring a stale web preview performance action error.', error);
|
|
2883
|
+
}
|
|
2884
|
+
} finally {
|
|
2885
|
+
if (operationIsCurrent()) {
|
|
2886
|
+
perf.pending = false;
|
|
2887
|
+
if (state.activeSection === 'performance') renderPerformance(perf.data);
|
|
2888
|
+
updateCapabilityUi();
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
if (refreshSelectedTarget && selectedTargetIsCurrent() && state.target) {
|
|
2892
|
+
await refreshPerformance({ silent: true });
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
|
|
2896
|
+
function setActiveSection(section) {
|
|
2897
|
+
const activeSection = sectionIsAvailable(section) ? section : 'elements';
|
|
2898
|
+
state.activeSection = activeSection;
|
|
2899
|
+
for (const tab of elements.mainTabs) {
|
|
2900
|
+
const selected = tab.dataset.section === activeSection;
|
|
2901
|
+
tab.classList.toggle('selected', selected);
|
|
2902
|
+
tab.setAttribute('aria-selected', String(selected));
|
|
2903
|
+
tab.tabIndex = selected ? 0 : -1;
|
|
2904
|
+
}
|
|
2905
|
+
for (const panel of elements.sections) {
|
|
2906
|
+
const selected = panel.dataset.panel === activeSection;
|
|
2907
|
+
panel.classList.toggle('selected', selected);
|
|
2908
|
+
panel.hidden = !selected;
|
|
2909
|
+
}
|
|
2910
|
+
if (activeSection === 'console') elements.consoleInput.focus();
|
|
2911
|
+
if (activeSection === 'elements') void refreshSnapshot();
|
|
2912
|
+
if (activeSection === 'state') {
|
|
2913
|
+
renderRuntimeStateSection();
|
|
2914
|
+
void refreshSnapshot();
|
|
2915
|
+
}
|
|
2916
|
+
if (activeSection === 'performance') {
|
|
2917
|
+
renderPerformance();
|
|
2918
|
+
void refreshPerformance();
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
|
|
2922
|
+
function handleMainTabNavigation(event) {
|
|
2923
|
+
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
|
2924
|
+
const tabs = elements.mainTabs.filter(tab => !tab.disabled);
|
|
2925
|
+
if (!tabs.length) return;
|
|
2926
|
+
event.preventDefault();
|
|
2927
|
+
const currentIndex = Math.max(0, tabs.indexOf(event.currentTarget));
|
|
2928
|
+
const nextIndex =
|
|
2929
|
+
event.key === 'Home'
|
|
2930
|
+
? 0
|
|
2931
|
+
: event.key === 'End'
|
|
2932
|
+
? tabs.length - 1
|
|
2933
|
+
: (currentIndex + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
|
|
2934
|
+
const nextTab = tabs[nextIndex];
|
|
2935
|
+
setActiveSection(nextTab.dataset.section);
|
|
2936
|
+
nextTab.focus();
|
|
2937
|
+
}
|
|
2938
|
+
|
|
2939
|
+
function setActiveDetail(detail) {
|
|
2940
|
+
state.activeDetail = detail;
|
|
2941
|
+
for (const tab of elements.detailTabs) {
|
|
2942
|
+
const selected = tab.dataset.detail === detail;
|
|
2943
|
+
tab.classList.toggle('selected', selected);
|
|
2944
|
+
tab.setAttribute('aria-selected', String(selected));
|
|
2945
|
+
tab.tabIndex = selected ? 0 : -1;
|
|
2946
|
+
if (selected && tab.id) elements.inspector.setAttribute('aria-labelledby', tab.id);
|
|
2947
|
+
}
|
|
2948
|
+
renderInspector();
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2951
|
+
function handleDetailTabNavigation(event) {
|
|
2952
|
+
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
|
2953
|
+
const tabs = elements.detailTabs.filter(tab => !tab.disabled);
|
|
2954
|
+
if (!tabs.length) return;
|
|
2955
|
+
event.preventDefault();
|
|
2956
|
+
const currentIndex = Math.max(0, tabs.indexOf(event.currentTarget));
|
|
2957
|
+
const nextIndex =
|
|
2958
|
+
event.key === 'Home'
|
|
2959
|
+
? 0
|
|
2960
|
+
: event.key === 'End'
|
|
2961
|
+
? tabs.length - 1
|
|
2962
|
+
: (currentIndex + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
|
|
2963
|
+
const nextTab = tabs[nextIndex];
|
|
2964
|
+
setActiveDetail(nextTab.dataset.detail);
|
|
2965
|
+
nextTab.focus();
|
|
2966
|
+
}
|
|
2967
|
+
|
|
2968
|
+
function stopConsoleStream() {
|
|
2969
|
+
if (state.consoleStream) state.consoleStream.close();
|
|
2970
|
+
state.consoleStream = null;
|
|
2971
|
+
state.consoleStreamTargetKey = null;
|
|
2972
|
+
}
|
|
2973
|
+
|
|
2974
|
+
function startConsoleStream() {
|
|
2975
|
+
if (!state.target || !state.autoRefresh || !targetSupports('console')) {
|
|
2976
|
+
stopConsoleStream();
|
|
2977
|
+
return;
|
|
2978
|
+
}
|
|
2979
|
+
const target = state.target;
|
|
2980
|
+
const targetGeneration = state.targetGeneration;
|
|
2981
|
+
const identity = targetIdentityParameters(target);
|
|
2982
|
+
const targetKey = `${targetGeneration}:${targetIdentityKey(target)}`;
|
|
2983
|
+
if (state.consoleStream && state.consoleStreamTargetKey === targetKey) return;
|
|
2984
|
+
stopConsoleStream();
|
|
2985
|
+
|
|
2986
|
+
const url = new URL('/api/devtools/console/stream', window.location.origin);
|
|
2987
|
+
for (const [key, value] of Object.entries(identity)) url.searchParams.set(key, String(value));
|
|
2988
|
+
const stream = new EventSource(debuggerEventSourceUrl(url.toString()));
|
|
2989
|
+
state.consoleStream = stream;
|
|
2990
|
+
state.consoleStreamTargetKey = targetKey;
|
|
2991
|
+
|
|
2992
|
+
stream.addEventListener('console', event => {
|
|
2993
|
+
if (state.consoleStream !== stream || state.targetGeneration !== targetGeneration || state.target?.id !== target.id)
|
|
2994
|
+
return;
|
|
2995
|
+
let entry;
|
|
2996
|
+
try {
|
|
2997
|
+
entry = JSON.parse(event.data);
|
|
2998
|
+
} catch (error) {
|
|
2999
|
+
console.warn('[Valdi DevTools] Ignoring a malformed Chromium console event.', error);
|
|
3000
|
+
return;
|
|
3001
|
+
}
|
|
3002
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return;
|
|
3003
|
+
if (!targetEventMatches(target, entry) || typeof entry.message !== 'string') {
|
|
3004
|
+
return;
|
|
3005
|
+
}
|
|
3006
|
+
addConsoleEntry(entry.level, entry.message, entry.timestamp, entry.source);
|
|
3007
|
+
});
|
|
3008
|
+
|
|
3009
|
+
stream.addEventListener('stream-error', event => {
|
|
3010
|
+
if (state.consoleStream !== stream || state.targetGeneration !== targetGeneration || state.target?.id !== target.id)
|
|
3011
|
+
return;
|
|
3012
|
+
try {
|
|
3013
|
+
const payload = JSON.parse(event.data);
|
|
3014
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return;
|
|
3015
|
+
if (targetEventMatches(target, payload) && typeof payload.error === 'string') {
|
|
3016
|
+
addConsoleEntry('error', payload.error);
|
|
3017
|
+
}
|
|
3018
|
+
} catch (error) {
|
|
3019
|
+
console.warn('[Valdi DevTools] Ignoring a malformed Chromium console stream error.', error);
|
|
3020
|
+
}
|
|
3021
|
+
});
|
|
3022
|
+
|
|
3023
|
+
stream.addEventListener('stream-warning', event => {
|
|
3024
|
+
if (state.consoleStream !== stream || state.targetGeneration !== targetGeneration || state.target?.id !== target.id)
|
|
3025
|
+
return;
|
|
3026
|
+
try {
|
|
3027
|
+
const payload = JSON.parse(event.data);
|
|
3028
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return;
|
|
3029
|
+
if (targetEventMatches(target, payload) && typeof payload.message === 'string') {
|
|
3030
|
+
addConsoleEntry('warn', payload.message);
|
|
3031
|
+
}
|
|
3032
|
+
} catch (error) {
|
|
3033
|
+
console.warn('[Valdi DevTools] Ignoring a malformed Chromium console stream warning.', error);
|
|
3034
|
+
}
|
|
3035
|
+
});
|
|
3036
|
+
}
|
|
3037
|
+
|
|
3038
|
+
function addConsoleEntry(kind, value, timestamp, source) {
|
|
3039
|
+
const normalizedKind = ['debug', 'error', 'info', 'input', 'log', 'result', 'warn'].includes(kind) ? kind : 'log';
|
|
3040
|
+
const text = String(value);
|
|
3041
|
+
const boundedValue =
|
|
3042
|
+
text.length > MAX_CONSOLE_ENTRY_CHARACTERS ? `${text.slice(0, MAX_CONSOLE_ENTRY_CHARACTERS - 1)}…` : text;
|
|
3043
|
+
const key = timestamp === undefined ? null : `${timestamp}:${normalizedKind}:${String(source ?? '')}:${boundedValue}`;
|
|
3044
|
+
if (key !== null) {
|
|
3045
|
+
if (state.consoleEntryKeys.has(key)) return;
|
|
3046
|
+
state.consoleEntryKeys.add(key);
|
|
3047
|
+
}
|
|
3048
|
+
state.consoleEntries.push({ key, kind: normalizedKind, value: boundedValue });
|
|
3049
|
+
if (state.consoleEntries.length > MAX_CONSOLE_ENTRIES) {
|
|
3050
|
+
const discarded = state.consoleEntries.splice(0, state.consoleEntries.length - MAX_CONSOLE_ENTRIES);
|
|
3051
|
+
for (const entry of discarded) {
|
|
3052
|
+
if (entry.key !== null) state.consoleEntryKeys.delete(entry.key);
|
|
3053
|
+
}
|
|
3054
|
+
}
|
|
3055
|
+
elements.consoleMessages.innerHTML = state.consoleEntries
|
|
3056
|
+
.map(
|
|
3057
|
+
entry =>
|
|
3058
|
+
`<div class="console-entry ${escapeHtml(entry.kind)}"><span class="console-chevron">${entry.kind === 'input' ? '›' : entry.kind === 'error' ? '×' : entry.kind === 'warn' ? '!' : '‹'}</span><pre>${escapeHtml(entry.value)}</pre></div>`,
|
|
3059
|
+
)
|
|
3060
|
+
.join('');
|
|
3061
|
+
elements.consoleMessages.scrollTop = elements.consoleMessages.scrollHeight;
|
|
3062
|
+
}
|
|
3063
|
+
|
|
3064
|
+
function clearConsole() {
|
|
3065
|
+
state.consoleEntries = [];
|
|
3066
|
+
state.consoleEntryKeys.clear();
|
|
3067
|
+
elements.consoleMessages.innerHTML = '';
|
|
3068
|
+
}
|
|
3069
|
+
|
|
3070
|
+
async function evaluateConsoleExpression(expression) {
|
|
3071
|
+
if (!state.target || !targetSupports('console')) return;
|
|
3072
|
+
const target = state.target;
|
|
3073
|
+
const targetGeneration = state.targetGeneration;
|
|
3074
|
+
const identity = targetIdentityParameters(target);
|
|
3075
|
+
const requestIsCurrent = () => state.targetGeneration === targetGeneration && state.target?.id === target.id;
|
|
3076
|
+
addConsoleEntry('input', expression);
|
|
3077
|
+
try {
|
|
3078
|
+
const result = await requestJson(
|
|
3079
|
+
'/api/devtools/evaluate',
|
|
3080
|
+
{},
|
|
3081
|
+
{
|
|
3082
|
+
body: {
|
|
3083
|
+
expression,
|
|
3084
|
+
...identity,
|
|
3085
|
+
},
|
|
3086
|
+
},
|
|
3087
|
+
);
|
|
3088
|
+
if (!requestIsCurrent()) return;
|
|
3089
|
+
const serialized = result.type === 'undefined' ? undefined : JSON.stringify(result.value, null, 2);
|
|
3090
|
+
const value = result.type === 'undefined' ? 'undefined' : (serialized ?? String(result.value));
|
|
3091
|
+
addConsoleEntry('result', value);
|
|
3092
|
+
} catch (error) {
|
|
3093
|
+
if (requestIsCurrent()) addConsoleEntry('error', error instanceof Error ? error.message : String(error));
|
|
3094
|
+
}
|
|
3095
|
+
}
|
|
3096
|
+
|
|
3097
|
+
function startSplitResize(event) {
|
|
3098
|
+
event.preventDefault();
|
|
3099
|
+
const bounds = elements.elementsSection.getBoundingClientRect();
|
|
3100
|
+
function resize(moveEvent) {
|
|
3101
|
+
const treeHeight = Math.max(120, Math.min(bounds.height - 200, moveEvent.clientY - bounds.top));
|
|
3102
|
+
elements.elementsSection.style.gridTemplateRows = `${treeHeight}px 5px minmax(170px, 1fr) 24px`;
|
|
3103
|
+
}
|
|
3104
|
+
function stopResize() {
|
|
3105
|
+
window.removeEventListener('pointermove', resize);
|
|
3106
|
+
window.removeEventListener('pointerup', stopResize);
|
|
3107
|
+
}
|
|
3108
|
+
window.addEventListener('pointermove', resize);
|
|
3109
|
+
window.addEventListener('pointerup', stopResize);
|
|
3110
|
+
}
|
|
3111
|
+
|
|
3112
|
+
function wireEvents() {
|
|
3113
|
+
for (const tab of elements.mainTabs) {
|
|
3114
|
+
tab.addEventListener('click', () => setActiveSection(tab.dataset.section));
|
|
3115
|
+
tab.addEventListener('keydown', handleMainTabNavigation);
|
|
3116
|
+
}
|
|
3117
|
+
for (const tab of elements.detailTabs) {
|
|
3118
|
+
tab.addEventListener('click', () => setActiveDetail(tab.dataset.detail));
|
|
3119
|
+
tab.addEventListener('keydown', handleDetailTabNavigation);
|
|
3120
|
+
}
|
|
3121
|
+
elements.targetSelect.addEventListener('change', () => {
|
|
3122
|
+
if (!isDirectMode()) return;
|
|
3123
|
+
const targetId = elements.targetSelect.value;
|
|
3124
|
+
if (!targetId) {
|
|
3125
|
+
applyDirectTargetSelection(null);
|
|
3126
|
+
return;
|
|
3127
|
+
}
|
|
3128
|
+
const target = state.registryTargets.find(candidate => candidate.id === targetId);
|
|
3129
|
+
if (!target || !isSelectableDirectTarget(target)) {
|
|
3130
|
+
state.targetSwitchMessage = target
|
|
3131
|
+
? directTargetUnavailableReason(target)
|
|
3132
|
+
: 'The requested target is unavailable.';
|
|
3133
|
+
renderTargetPicker();
|
|
3134
|
+
return;
|
|
3135
|
+
}
|
|
3136
|
+
state.unavailableTargetId = null;
|
|
3137
|
+
applyDirectTargetSelection(target);
|
|
3138
|
+
});
|
|
3139
|
+
elements.refreshButton.addEventListener('click', () => {
|
|
3140
|
+
if (isDirectMode()) void refreshTargetRegistry();
|
|
3141
|
+
if (state.activeSection === 'performance') void refreshPerformance();
|
|
3142
|
+
else void refreshSnapshot();
|
|
3143
|
+
});
|
|
3144
|
+
for (const button of document.querySelectorAll('.section-header [data-performance-action]')) {
|
|
3145
|
+
button.addEventListener('click', () => void runPerformanceAction(button.dataset.performanceAction));
|
|
3146
|
+
}
|
|
3147
|
+
elements.performanceContent.addEventListener('click', event => {
|
|
3148
|
+
const scope = event.target.closest('[data-performance-scope]');
|
|
3149
|
+
if (scope) {
|
|
3150
|
+
state.performance.traceScope = scope.dataset.performanceScope;
|
|
3151
|
+
renderPerformance();
|
|
3152
|
+
return;
|
|
3153
|
+
}
|
|
3154
|
+
const button = event.target.closest('[data-performance-action]');
|
|
3155
|
+
if (button && !button.disabled) void runPerformanceAction(button.dataset.performanceAction);
|
|
3156
|
+
});
|
|
3157
|
+
elements.performanceContent.addEventListener('input', event => {
|
|
3158
|
+
if (event.target.id === 'performanceDurationInput') {
|
|
3159
|
+
state.performance.durationSeconds = Math.max(0.1, Math.min(15, Number(event.target.value) || 3));
|
|
3160
|
+
return;
|
|
3161
|
+
}
|
|
3162
|
+
if (event.target.id !== 'performanceTraceFilter') return;
|
|
3163
|
+
const selectionStart = event.target.selectionStart;
|
|
3164
|
+
const selectionEnd = event.target.selectionEnd;
|
|
3165
|
+
state.performance.traceSearch = event.target.value;
|
|
3166
|
+
renderPerformance();
|
|
3167
|
+
const filter = document.getElementById('performanceTraceFilter');
|
|
3168
|
+
filter?.focus();
|
|
3169
|
+
if (selectionStart !== null && selectionEnd !== null) filter?.setSelectionRange(selectionStart, selectionEnd);
|
|
3170
|
+
});
|
|
3171
|
+
elements.performanceContent.addEventListener(
|
|
3172
|
+
'toggle',
|
|
3173
|
+
event => {
|
|
3174
|
+
if (event.target?.tagName === 'DETAILS' && event.target.classList.contains('performance-navigation')) {
|
|
3175
|
+
state.performance.navigationExpanded = event.target.open;
|
|
3176
|
+
}
|
|
3177
|
+
},
|
|
3178
|
+
true,
|
|
3179
|
+
);
|
|
3180
|
+
elements.autoRefreshToggle.addEventListener('change', () => {
|
|
3181
|
+
state.autoRefresh = elements.autoRefreshToggle.checked;
|
|
3182
|
+
if (state.autoRefresh) {
|
|
3183
|
+
startConsoleStream();
|
|
3184
|
+
} else {
|
|
3185
|
+
stopConsoleStream();
|
|
3186
|
+
}
|
|
3187
|
+
});
|
|
3188
|
+
elements.treeFilter.addEventListener('input', () => {
|
|
3189
|
+
state.search = elements.treeFilter.value;
|
|
3190
|
+
renderTree();
|
|
3191
|
+
});
|
|
3192
|
+
elements.stateFilter.addEventListener('input', () => {
|
|
3193
|
+
state.runtimeState.search = elements.stateFilter.value;
|
|
3194
|
+
renderRuntimeStateSection();
|
|
3195
|
+
});
|
|
3196
|
+
elements.stateContent.addEventListener('click', event => {
|
|
3197
|
+
const button = event.target.closest?.('[data-runtime-state-inspect]');
|
|
3198
|
+
if (!button) return;
|
|
3199
|
+
event.preventDefault();
|
|
3200
|
+
event.stopPropagation();
|
|
3201
|
+
inspectRuntimeStateBinding(runtimeStateInspectBindings.get(button));
|
|
3202
|
+
});
|
|
3203
|
+
elements.stateContent.addEventListener('toggle', event => updateRuntimeStateDisclosure(event.target), true);
|
|
3204
|
+
elements.expandButton.addEventListener('click', () => {
|
|
3205
|
+
expandUsefulNodes(state.snapshot?.tree);
|
|
3206
|
+
if (state.selectedNodeId) revealPath(state.selectedNodeId);
|
|
3207
|
+
renderTree();
|
|
3208
|
+
});
|
|
3209
|
+
elements.tree.addEventListener('keydown', handleTreeNavigation);
|
|
3210
|
+
elements.tree.addEventListener('click', event => {
|
|
3211
|
+
const toggle = event.target.closest('[data-toggle-id]');
|
|
3212
|
+
if (toggle) {
|
|
3213
|
+
elements.tree.focus({ preventScroll: true });
|
|
3214
|
+
const id = toggle.dataset.toggleId;
|
|
3215
|
+
if (state.expandedNodeIds.has(id)) {
|
|
3216
|
+
state.expandedNodeIds.delete(id);
|
|
3217
|
+
} else {
|
|
3218
|
+
state.expandedNodeIds.add(id);
|
|
3219
|
+
}
|
|
3220
|
+
renderTree();
|
|
3221
|
+
return;
|
|
3222
|
+
}
|
|
3223
|
+
const row = event.target.closest('[data-node-id]');
|
|
3224
|
+
if (row) {
|
|
3225
|
+
elements.tree.focus({ preventScroll: true });
|
|
3226
|
+
selectNode(row.dataset.nodeId);
|
|
3227
|
+
}
|
|
3228
|
+
});
|
|
3229
|
+
elements.tree.addEventListener('pointerover', event => {
|
|
3230
|
+
const row = event.target.closest('[data-node-id]');
|
|
3231
|
+
if (row) queueHighlight(inspectedNodeId(findNode(row.dataset.nodeId)));
|
|
3232
|
+
});
|
|
3233
|
+
elements.tree.addEventListener('pointerleave', () => queueHighlight(null));
|
|
3234
|
+
elements.inspector.addEventListener('focusin', event => {
|
|
3235
|
+
if (event.target.closest?.('[data-component-property-editor]')) {
|
|
3236
|
+
state.componentPropertyEdit.focused = true;
|
|
3237
|
+
}
|
|
3238
|
+
});
|
|
3239
|
+
elements.inspector.addEventListener('focusout', () => {
|
|
3240
|
+
window.setTimeout(() => {
|
|
3241
|
+
state.componentPropertyEdit.focused = Boolean(
|
|
3242
|
+
document.activeElement?.closest?.('[data-component-property-editor]'),
|
|
3243
|
+
);
|
|
3244
|
+
}, 0);
|
|
3245
|
+
});
|
|
3246
|
+
elements.inspector.addEventListener('submit', event => {
|
|
3247
|
+
const form = event.target.closest?.('[data-component-property-editor]');
|
|
3248
|
+
if (!form) return;
|
|
3249
|
+
event.preventDefault();
|
|
3250
|
+
const binding = componentPropertyEditorBindings.get(form);
|
|
3251
|
+
const editor = form.querySelector('[data-component-property-input]');
|
|
3252
|
+
const value = editor && binding ? readComponentPropertyEditorValue(editor, binding.valueType) : undefined;
|
|
3253
|
+
if (
|
|
3254
|
+
!binding ||
|
|
3255
|
+
value === undefined ||
|
|
3256
|
+
!Number.isSafeInteger(binding.snapshotRevision) ||
|
|
3257
|
+
binding.snapshotRevision <= 0 ||
|
|
3258
|
+
!COMPONENT_PROPERTY_TOKEN_PATTERN.test(binding.componentToken)
|
|
3259
|
+
) {
|
|
3260
|
+
state.componentPropertyEdit.error = 'Enter a valid scalar value before applying this property.';
|
|
3261
|
+
state.componentPropertyEdit.focused = false;
|
|
3262
|
+
renderInspector();
|
|
3263
|
+
return;
|
|
3264
|
+
}
|
|
3265
|
+
void submitComponentPropertyEdit(
|
|
3266
|
+
binding.componentId,
|
|
3267
|
+
binding.propertyName,
|
|
3268
|
+
binding.componentToken,
|
|
3269
|
+
binding.snapshotRevision,
|
|
3270
|
+
value,
|
|
3271
|
+
);
|
|
3272
|
+
});
|
|
3273
|
+
elements.inspector.addEventListener('toggle', event => updateRuntimeStateDisclosure(event.target), true);
|
|
3274
|
+
elements.breadcrumbs.addEventListener('click', event => {
|
|
3275
|
+
const button = event.target.closest('[data-breadcrumb-id]');
|
|
3276
|
+
if (button) selectNode(button.dataset.breadcrumbId);
|
|
3277
|
+
});
|
|
3278
|
+
elements.copyNodeButton.addEventListener('click', async () => {
|
|
3279
|
+
const json = selectedNodeProjectionJson();
|
|
3280
|
+
if (json) await navigator.clipboard.writeText(json);
|
|
3281
|
+
});
|
|
3282
|
+
elements.splitHandle.addEventListener('pointerdown', startSplitResize);
|
|
3283
|
+
elements.clearConsoleButton.addEventListener('click', clearConsole);
|
|
3284
|
+
elements.consoleForm.addEventListener('submit', event => {
|
|
3285
|
+
event.preventDefault();
|
|
3286
|
+
const expression = elements.consoleInput.value.trim();
|
|
3287
|
+
if (!expression || !state.target || !targetSupports('console')) return;
|
|
3288
|
+
state.consoleHistory.push(expression);
|
|
3289
|
+
if (state.consoleHistory.length > MAX_CONSOLE_HISTORY_ENTRIES) {
|
|
3290
|
+
state.consoleHistory.splice(0, state.consoleHistory.length - MAX_CONSOLE_HISTORY_ENTRIES);
|
|
3291
|
+
}
|
|
3292
|
+
state.consoleHistoryIndex = state.consoleHistory.length;
|
|
3293
|
+
elements.consoleInput.value = '';
|
|
3294
|
+
void evaluateConsoleExpression(expression);
|
|
3295
|
+
});
|
|
3296
|
+
elements.consoleInput.addEventListener('keydown', event => {
|
|
3297
|
+
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
|
|
3298
|
+
event.preventDefault();
|
|
3299
|
+
state.consoleHistoryIndex = Math.max(
|
|
3300
|
+
0,
|
|
3301
|
+
Math.min(state.consoleHistory.length, state.consoleHistoryIndex + (event.key === 'ArrowUp' ? -1 : 1)),
|
|
3302
|
+
);
|
|
3303
|
+
elements.consoleInput.value = state.consoleHistory[state.consoleHistoryIndex] || '';
|
|
3304
|
+
});
|
|
3305
|
+
window.addEventListener('message', event => {
|
|
3306
|
+
if (
|
|
3307
|
+
event.source === window.parent &&
|
|
3308
|
+
event.origin.startsWith('chrome-extension://') &&
|
|
3309
|
+
event.data?.channel === 'valdi-devtools-theme'
|
|
3310
|
+
) {
|
|
3311
|
+
applyTheme(event.data.theme);
|
|
3312
|
+
}
|
|
3313
|
+
});
|
|
3314
|
+
window.addEventListener('pagehide', () => {
|
|
3315
|
+
stopConsoleStream();
|
|
3316
|
+
stopPerformanceOnPageHide();
|
|
3317
|
+
});
|
|
3318
|
+
document.addEventListener('visibilitychange', () => {
|
|
3319
|
+
if (!document.hidden && isDirectMode()) void refreshTargetRegistry();
|
|
3320
|
+
if (!document.hidden && (state.activeSection === 'elements' || state.activeSection === 'state')) {
|
|
3321
|
+
void refreshSnapshot();
|
|
3322
|
+
}
|
|
3323
|
+
if (!document.hidden && state.activeSection === 'performance') void refreshPerformance({ silent: true });
|
|
3324
|
+
});
|
|
3325
|
+
}
|
|
3326
|
+
|
|
3327
|
+
applyTheme(query.get('theme'));
|
|
3328
|
+
wireEvents();
|
|
3329
|
+
void connectToInspectedApplication();
|