@snap/valdi 1.1.7 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.metadata/.bazelrc.template +9 -7
- package/.metadata/AGENTS.md.template +7 -0
- package/.metadata/MODULE.bazel.template +47 -3
- package/.metadata/README.md.template +2 -2
- package/.metadata/bzl/patches/rules_python/1.9.0/BUILD.bazel.template +1 -0
- package/.metadata/bzl/patches/rules_python/1.9.0/remove_setuptools_spaces.patch.template +96 -0
- package/.metadata/skill-tests-README.md.template +1 -1
- package/README.md +47 -14
- package/bundled-skills/registry.json +2 -1
- package/bundled-skills/skills/valdi-animations/skill.md +49 -0
- package/bundled-skills/skills/valdi-async/skill.md +3 -2
- package/bundled-skills/skills/valdi-async/tests/README.md +1 -1
- package/bundled-skills/skills/valdi-bazel/skill.md +2 -6
- package/bundled-skills/skills/valdi-component-tests/tests/README.md +1 -1
- package/bundled-skills/skills/valdi-cpp-runtime/skill.md +18 -0
- package/bundled-skills/skills/valdi-custom-view/skill.md +1 -1
- package/bundled-skills/skills/valdi-error-handling/skill.md +1 -1
- package/bundled-skills/skills/valdi-gestures/skill.md +3 -3
- package/bundled-skills/skills/valdi-migrate/skill.md +2 -1
- package/bundled-skills/skills/valdi-migrate/tests/README.md +2 -2
- package/bundled-skills/skills/valdi-mock-breakdown/skill.md +4 -4
- package/bundled-skills/skills/valdi-mock-to-module/skill.md +9 -6
- package/bundled-skills/skills/valdi-overview/skill.md +2 -1
- package/bundled-skills/skills/valdi-perf/skill.md +121 -5
- package/bundled-skills/skills/valdi-perf/tests/README.md +1 -1
- package/bundled-skills/skills/valdi-pr-review/skill.md +189 -0
- package/bundled-skills/skills/valdi-profile/skill.md +5 -3
- package/bundled-skills/skills/valdi-setup/skill.md +3 -6
- package/bundled-skills/skills/valdi-testing/skill.md +1 -1
- package/bundled-skills/skills/valdi-tsx/skill.md +47 -11
- package/bundled-skills/skills/valdi-tsx/tests/README.md +1 -1
- package/debugger/README.md +356 -0
- package/debugger/debugger-actions.js +373 -0
- package/debugger/debugger-api.js +225 -0
- package/debugger/debugger-bootstrap.js +295 -0
- package/debugger/debugger-model.js +790 -0
- package/debugger/debugger-performance.js +573 -0
- package/debugger/debugger-preview-html.js +676 -0
- package/debugger/debugger-providers.js +389 -0
- package/debugger/debugger-render.js +529 -0
- package/debugger/debugger-runtime.js +387 -0
- package/debugger/debugger-session.js +188 -0
- package/debugger/debugger-settings.js +209 -0
- package/debugger/debugger-state.js +221 -0
- package/debugger/debugger-tree-model.js +539 -0
- package/debugger/debugger.css +1865 -0
- package/debugger/devtools-panel.css +1318 -0
- package/debugger/devtools-panel.html +273 -0
- package/debugger/devtools-panel.js +3329 -0
- package/debugger/index.html +279 -0
- package/dist/commands/bootstrap.js +7 -6
- package/dist/commands/build.js +7 -1
- package/dist/commands/debugger.js +163 -0
- package/dist/commands/doctor.js +3 -62
- package/dist/commands/export.js +47 -16
- package/dist/commands/hotreload.js +247 -27
- package/dist/commands/inspect.js +5 -2
- package/dist/commands/inspect_commands/input.js +176 -0
- package/dist/commands/inspect_commands/snapshot.js +1 -1
- package/dist/commands/inspect_commands/tree.js +1 -1
- package/dist/commands/install.js +79 -2
- package/dist/commands/projectsync.js +15 -0
- package/dist/commands/webHotreload.js +31 -0
- package/dist/core/constants.js +34 -7
- package/dist/debugger/chromiumConsole.js +279 -0
- package/dist/debugger/inputClient.js +473 -0
- package/dist/debugger/server.js +3801 -0
- package/dist/debugger/targetRegistry.js +436 -0
- package/dist/debugger/webPreviewPerformance.js +864 -0
- package/dist/index.js +0 -0
- package/dist/utils/BazelClient.js +34 -5
- package/dist/utils/applicationUtils.js +20 -2
- package/dist/utils/buildInfo.js +5 -1
- package/dist/utils/chromiumDevToolsClient.js +350 -0
- package/dist/utils/cliUtils.js +2 -2
- package/dist/utils/daemonClient.js +364 -44
- package/dist/utils/directorySync.js +153 -0
- package/dist/utils/githubUtils.js +1 -1
- package/dist/utils/hermesClient.js +82 -176
- package/dist/utils/loopbackHost.js +14 -0
- package/dist/utils/owlCdpClient.js +282 -0
- package/dist/utils/owlDevToolsExtension.js +142 -0
- package/dist/utils/processUtils.js +14 -0
- package/dist/utils/stringUtils.js +13 -1
- package/dist/utils/webApplicationSession.js +58 -0
- package/dist/utils/webHotReloadSession.js +212 -0
- package/dist/utils/webServerUtils.js +195 -0
- package/dist/utils/zipUtils.js +20 -2
- package/package.json +4 -2
- package/dist/commands/inspect_commands/snapshot.spec.js +0 -105
- package/dist/core/packageFiles.spec.js +0 -29
- package/dist/preview/previewGenerator.spec.js +0 -203
- package/dist/preview/viewModelParser.spec.js +0 -171
- package/dist/utils/linuxDistro.spec.js +0 -122
- package/dist/utils/skillsAdapters.spec.js +0 -141
- package/dist/utils/stringUtils.spec.js +0 -81
|
@@ -0,0 +1,864 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WebPreviewPerformanceController = exports.WebPreviewTraceRecorder = exports.WebPreviewTraceNormalizer = exports.WebPreviewTraceLifecycleError = exports.WEB_PREVIEW_TRACE_RESULT_TTL_MS = exports.WEB_PREVIEW_TRACE_WATCHDOG_MS = exports.MAX_WEB_PREVIEW_TRACE_NAME_BYTES = exports.MAX_WEB_PREVIEW_TRACE_EVENTS = void 0;
|
|
4
|
+
exports.saturatingWebPreviewTraceEventCount = saturatingWebPreviewTraceEventCount;
|
|
5
|
+
exports.normalizeWebPreviewPerformanceMetrics = normalizeWebPreviewPerformanceMetrics;
|
|
6
|
+
exports.isWebPreviewPerformanceTargetPresent = isWebPreviewPerformanceTargetPresent;
|
|
7
|
+
exports.readWebPreviewPerformanceSnapshot = readWebPreviewPerformanceSnapshot;
|
|
8
|
+
exports.enableWebPreviewRendererTracing = enableWebPreviewRendererTracing;
|
|
9
|
+
exports.createWebPreviewPerformanceController = createWebPreviewPerformanceController;
|
|
10
|
+
const chromiumDevToolsClient_1 = require("../utils/chromiumDevToolsClient");
|
|
11
|
+
const owlCdpClient_1 = require("../utils/owlCdpClient");
|
|
12
|
+
const CHROMIUM_COMMAND_TIMEOUT_MS = 10_000;
|
|
13
|
+
const TRACE_COMPLETION_TIMEOUT_MS = 10_000;
|
|
14
|
+
const RECORDED_TRACE_TYPE_INSTANT = 1;
|
|
15
|
+
const MIN_BROWSER_TASK_DURATION_MICROS = 100;
|
|
16
|
+
const MAX_ACTIVE_TRACE_PAIRS = 10_000;
|
|
17
|
+
const MAX_TRACE_PAIR_ID_BYTES = 256;
|
|
18
|
+
const MAX_PAINT_ENTRIES = 16;
|
|
19
|
+
const MAX_PAINT_NAME_BYTES = 256;
|
|
20
|
+
const CHROMIUM_METRIC_NAMES = new Set([
|
|
21
|
+
'TaskDuration',
|
|
22
|
+
'ScriptDuration',
|
|
23
|
+
'LayoutDuration',
|
|
24
|
+
'LayoutCount',
|
|
25
|
+
'RecalcStyleCount',
|
|
26
|
+
'JSHeapUsedSize',
|
|
27
|
+
'JSHeapTotalSize',
|
|
28
|
+
]);
|
|
29
|
+
const TRACE_CATEGORIES = [
|
|
30
|
+
'devtools.timeline',
|
|
31
|
+
'blink.user_timing',
|
|
32
|
+
'blink.console',
|
|
33
|
+
'disabled-by-default-devtools.timeline',
|
|
34
|
+
].join(',');
|
|
35
|
+
exports.MAX_WEB_PREVIEW_TRACE_EVENTS = 10_000;
|
|
36
|
+
exports.MAX_WEB_PREVIEW_TRACE_NAME_BYTES = 2048;
|
|
37
|
+
exports.WEB_PREVIEW_TRACE_WATCHDOG_MS = 15_000;
|
|
38
|
+
exports.WEB_PREVIEW_TRACE_RESULT_TTL_MS = 60_000;
|
|
39
|
+
class WebPreviewTraceLifecycleError extends Error {
|
|
40
|
+
traceEnded;
|
|
41
|
+
recorder;
|
|
42
|
+
constructor(message, traceEnded, recorder) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.traceEnded = traceEnded;
|
|
45
|
+
this.recorder = recorder;
|
|
46
|
+
this.name = 'WebPreviewTraceLifecycleError';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
exports.WebPreviewTraceLifecycleError = WebPreviewTraceLifecycleError;
|
|
50
|
+
const BROWSER_TRACE_NAMES = new Map([
|
|
51
|
+
['RunTask', 'Browser.MainThread.Task'],
|
|
52
|
+
['FunctionCall', 'Browser.JavaScript.FunctionCall'],
|
|
53
|
+
['EvaluateScript', 'Browser.JavaScript.EvaluateScript'],
|
|
54
|
+
['EventDispatch', 'Browser.JavaScript.EventDispatch'],
|
|
55
|
+
['TimerFire', 'Browser.JavaScript.TimerFire'],
|
|
56
|
+
['FireAnimationFrame', 'Browser.JavaScript.AnimationFrame'],
|
|
57
|
+
['UpdateLayoutTree', 'Browser.Layout.UpdateLayoutTree'],
|
|
58
|
+
['Layout', 'Browser.Layout.Layout'],
|
|
59
|
+
['RecalculateStyles', 'Browser.Layout.RecalculateStyles'],
|
|
60
|
+
['ScheduleStyleRecalculation', 'Browser.Layout.ScheduleStyleRecalculation'],
|
|
61
|
+
['Paint', 'Browser.Paint.Paint'],
|
|
62
|
+
['PrePaint', 'Browser.Paint.PrePaint'],
|
|
63
|
+
['Layerize', 'Browser.Paint.Layerize'],
|
|
64
|
+
['RasterTask', 'Browser.Paint.RasterTask'],
|
|
65
|
+
['CompositeLayers', 'Browser.Paint.CompositeLayers'],
|
|
66
|
+
['BeginFrame', 'Browser.Frames.BeginFrame'],
|
|
67
|
+
['DrawFrame', 'Browser.Frames.DrawFrame'],
|
|
68
|
+
['AnimationFrame', 'Browser.Frames.AnimationFrame'],
|
|
69
|
+
['AnimationFrame::Render', 'Browser.Frames.Render'],
|
|
70
|
+
['Commit', 'Browser.Frames.Commit'],
|
|
71
|
+
['MinorGC', 'Browser.GC.Minor'],
|
|
72
|
+
['MajorGC', 'Browser.GC.Major'],
|
|
73
|
+
]);
|
|
74
|
+
const PERFORMANCE_SNAPSHOT_EXPRESSION = `(() => {
|
|
75
|
+
const resources = globalThis.performance.getEntriesByType('resource');
|
|
76
|
+
const navigation = globalThis.performance.getEntriesByType('navigation')[0];
|
|
77
|
+
const paints = globalThis.performance.getEntriesByType('paint').slice(0, ${MAX_PAINT_ENTRIES});
|
|
78
|
+
const parameters = new URLSearchParams(globalThis.location.search);
|
|
79
|
+
return {
|
|
80
|
+
navigation: navigation ? {
|
|
81
|
+
domContentLoadedMs: navigation.domContentLoadedEventEnd,
|
|
82
|
+
loadMs: navigation.loadEventEnd,
|
|
83
|
+
} : {},
|
|
84
|
+
paints: paints.map(entry => ({ name: String(entry.name), startTime: entry.startTime })),
|
|
85
|
+
rendererTracingEnabled:
|
|
86
|
+
parameters.getAll('valdiDevTools').length === 1 && parameters.get('valdiDevTools') === '1' &&
|
|
87
|
+
parameters.getAll('valdiTrace').length === 1 && parameters.get('valdiTrace') === 'chrome',
|
|
88
|
+
resourceCount: resources.length,
|
|
89
|
+
transferSize: resources.reduce((total, entry) => total + (Number(entry.transferSize) || 0), 0),
|
|
90
|
+
uptimeMs: globalThis.performance.now(),
|
|
91
|
+
};
|
|
92
|
+
})()`;
|
|
93
|
+
function asRecord(value) {
|
|
94
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
95
|
+
? value
|
|
96
|
+
: undefined;
|
|
97
|
+
}
|
|
98
|
+
function boundedSafeInteger(value) {
|
|
99
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
|
|
100
|
+
return undefined;
|
|
101
|
+
const rounded = Math.round(value);
|
|
102
|
+
return Number.isSafeInteger(rounded) ? rounded : undefined;
|
|
103
|
+
}
|
|
104
|
+
function finiteNonNegativeNumber(value) {
|
|
105
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
106
|
+
}
|
|
107
|
+
function traceName(value) {
|
|
108
|
+
return typeof value === 'string' &&
|
|
109
|
+
value.length > 0 &&
|
|
110
|
+
Buffer.byteLength(value, 'utf8') <= exports.MAX_WEB_PREVIEW_TRACE_NAME_BYTES
|
|
111
|
+
? value
|
|
112
|
+
: undefined;
|
|
113
|
+
}
|
|
114
|
+
function normalizedTraceName(value) {
|
|
115
|
+
const name = traceName(value);
|
|
116
|
+
if (name === undefined)
|
|
117
|
+
return undefined;
|
|
118
|
+
if (name.startsWith('Valdi.'))
|
|
119
|
+
return name;
|
|
120
|
+
return BROWSER_TRACE_NAMES.get(name);
|
|
121
|
+
}
|
|
122
|
+
function tracePairId(value) {
|
|
123
|
+
if (value === undefined)
|
|
124
|
+
return '';
|
|
125
|
+
if (typeof value !== 'string' && typeof value !== 'number')
|
|
126
|
+
return undefined;
|
|
127
|
+
const serialized = String(value);
|
|
128
|
+
return Buffer.byteLength(serialized, 'utf8') <= MAX_TRACE_PAIR_ID_BYTES ? serialized : undefined;
|
|
129
|
+
}
|
|
130
|
+
function saturatingWebPreviewTraceEventCount(left, right) {
|
|
131
|
+
return left >= Number.MAX_SAFE_INTEGER - right ? Number.MAX_SAFE_INTEGER : left + right;
|
|
132
|
+
}
|
|
133
|
+
class WebPreviewTraceNormalizer {
|
|
134
|
+
activePairs = new Map();
|
|
135
|
+
activePairCount = 0;
|
|
136
|
+
droppedTraceEventCount = 0;
|
|
137
|
+
finalized = false;
|
|
138
|
+
traces = [];
|
|
139
|
+
accept(value) {
|
|
140
|
+
if (this.finalized)
|
|
141
|
+
return;
|
|
142
|
+
const event = asRecord(value);
|
|
143
|
+
if (event === undefined)
|
|
144
|
+
return;
|
|
145
|
+
const timestampTrace = this.normalizeTimestamp(event);
|
|
146
|
+
if (timestampTrace !== undefined) {
|
|
147
|
+
this.append(timestampTrace);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const instantOrDuration = this.normalizeInstantOrDuration(event);
|
|
151
|
+
if (instantOrDuration !== undefined) {
|
|
152
|
+
this.append(instantOrDuration);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const name = normalizedTraceName(event['name']);
|
|
156
|
+
const timestamp = boundedSafeInteger(event['ts']);
|
|
157
|
+
const pairId = tracePairId(event['id']);
|
|
158
|
+
if (name === undefined || timestamp === undefined || pairId === undefined)
|
|
159
|
+
return;
|
|
160
|
+
const threadId = boundedSafeInteger(event['tid']) ?? 0;
|
|
161
|
+
const key = JSON.stringify([threadId, name, pairId]);
|
|
162
|
+
if (event['ph'] === 'B' || event['ph'] === 'b') {
|
|
163
|
+
if (this.activePairCount >= MAX_ACTIVE_TRACE_PAIRS) {
|
|
164
|
+
this.incrementDropped();
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const active = this.activePairs.get(key) ?? [];
|
|
168
|
+
active.push({ name, startMicros: timestamp, threadId });
|
|
169
|
+
this.activePairs.set(key, active);
|
|
170
|
+
this.activePairCount++;
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (event['ph'] !== 'E' && event['ph'] !== 'e')
|
|
174
|
+
return;
|
|
175
|
+
const active = this.activePairs.get(key);
|
|
176
|
+
const start = active?.pop();
|
|
177
|
+
if (start === undefined)
|
|
178
|
+
return;
|
|
179
|
+
this.activePairCount--;
|
|
180
|
+
if (active?.length === 0)
|
|
181
|
+
this.activePairs.delete(key);
|
|
182
|
+
this.append({
|
|
183
|
+
endMicros: Math.max(start.startMicros, timestamp),
|
|
184
|
+
startMicros: start.startMicros,
|
|
185
|
+
threadId: start.threadId,
|
|
186
|
+
trace: start.name,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
dataLossOccurred() {
|
|
190
|
+
if (this.finalized)
|
|
191
|
+
return;
|
|
192
|
+
this.incrementDropped();
|
|
193
|
+
}
|
|
194
|
+
result() {
|
|
195
|
+
if (!this.finalized) {
|
|
196
|
+
this.droppedTraceEventCount = saturatingWebPreviewTraceEventCount(this.droppedTraceEventCount, this.activePairCount);
|
|
197
|
+
this.activePairs.clear();
|
|
198
|
+
this.activePairCount = 0;
|
|
199
|
+
this.finalized = true;
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
droppedTraceEventCount: this.droppedTraceEventCount,
|
|
203
|
+
traces: [...this.traces].sort((left, right) => left.startMicros - right.startMicros || right.endMicros - left.endMicros),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
append(trace) {
|
|
207
|
+
if (this.traces.length >= exports.MAX_WEB_PREVIEW_TRACE_EVENTS) {
|
|
208
|
+
this.incrementDropped();
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
this.traces.push(trace);
|
|
212
|
+
}
|
|
213
|
+
incrementDropped() {
|
|
214
|
+
this.droppedTraceEventCount = saturatingWebPreviewTraceEventCount(this.droppedTraceEventCount, 1);
|
|
215
|
+
}
|
|
216
|
+
normalizeTimestamp(event) {
|
|
217
|
+
if (event['name'] !== 'TimeStamp')
|
|
218
|
+
return undefined;
|
|
219
|
+
const data = asRecord(asRecord(event['args'])?.['data']);
|
|
220
|
+
const name = traceName(data?.['name']) ?? traceName(data?.['message']);
|
|
221
|
+
if (name === undefined || !name.startsWith('Valdi.'))
|
|
222
|
+
return undefined;
|
|
223
|
+
const timestamp = boundedSafeInteger(event['ts']);
|
|
224
|
+
const startMicros = boundedSafeInteger(data?.['start']) ?? timestamp;
|
|
225
|
+
const endMicros = boundedSafeInteger(data?.['end']) ?? startMicros;
|
|
226
|
+
if (startMicros === undefined || endMicros === undefined)
|
|
227
|
+
return undefined;
|
|
228
|
+
return {
|
|
229
|
+
endMicros: Math.max(startMicros, endMicros),
|
|
230
|
+
startMicros,
|
|
231
|
+
threadId: boundedSafeInteger(event['tid']) ?? 0,
|
|
232
|
+
trace: name,
|
|
233
|
+
...(startMicros === endMicros ? { type: RECORDED_TRACE_TYPE_INSTANT } : {}),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
normalizeInstantOrDuration(event) {
|
|
237
|
+
const name = normalizedTraceName(event['name']);
|
|
238
|
+
const phase = String(event['ph']);
|
|
239
|
+
const startMicros = boundedSafeInteger(event['ts']);
|
|
240
|
+
if (name === undefined || startMicros === undefined || !['X', 'I', 'i', 'R'].includes(phase)) {
|
|
241
|
+
return undefined;
|
|
242
|
+
}
|
|
243
|
+
const durationMicros = boundedSafeInteger(event['dur']) ?? 0;
|
|
244
|
+
if (event['name'] === 'RunTask' && durationMicros < MIN_BROWSER_TASK_DURATION_MICROS)
|
|
245
|
+
return undefined;
|
|
246
|
+
if (durationMicros > Number.MAX_SAFE_INTEGER - startMicros)
|
|
247
|
+
return undefined;
|
|
248
|
+
return {
|
|
249
|
+
endMicros: startMicros + durationMicros,
|
|
250
|
+
startMicros,
|
|
251
|
+
threadId: boundedSafeInteger(event['tid']) ?? 0,
|
|
252
|
+
trace: name,
|
|
253
|
+
...(phase === 'X' ? {} : { type: RECORDED_TRACE_TYPE_INSTANT }),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
exports.WebPreviewTraceNormalizer = WebPreviewTraceNormalizer;
|
|
258
|
+
function normalizeWebPreviewPerformanceMetrics(result) {
|
|
259
|
+
const metrics = asRecord(result)?.metrics;
|
|
260
|
+
const normalized = Object.create(null);
|
|
261
|
+
if (!Array.isArray(metrics))
|
|
262
|
+
return normalized;
|
|
263
|
+
for (const metric of metrics) {
|
|
264
|
+
if (typeof metric?.name === 'string' &&
|
|
265
|
+
CHROMIUM_METRIC_NAMES.has(metric.name) &&
|
|
266
|
+
typeof metric.value === 'number' &&
|
|
267
|
+
Number.isFinite(metric.value)) {
|
|
268
|
+
normalized[metric.name] = metric.value;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return normalized;
|
|
272
|
+
}
|
|
273
|
+
function metricDifferences(start, end) {
|
|
274
|
+
const result = Object.create(null);
|
|
275
|
+
for (const name of ['TaskDuration', 'ScriptDuration', 'LayoutDuration']) {
|
|
276
|
+
if (end[name] !== undefined)
|
|
277
|
+
result[`${name}Ms`] = Math.max(0, end[name] - (start[name] ?? 0)) * 1000;
|
|
278
|
+
}
|
|
279
|
+
for (const name of ['LayoutCount', 'RecalcStyleCount']) {
|
|
280
|
+
if (end[name] !== undefined)
|
|
281
|
+
result[name] = Math.max(0, end[name] - (start[name] ?? 0));
|
|
282
|
+
}
|
|
283
|
+
return result;
|
|
284
|
+
}
|
|
285
|
+
function rendererTracingEnabled(inspectedUrl) {
|
|
286
|
+
try {
|
|
287
|
+
const parameters = new URL(inspectedUrl).searchParams;
|
|
288
|
+
return (parameters.getAll('valdiDevTools').length === 1 &&
|
|
289
|
+
parameters.get('valdiDevTools') === '1' &&
|
|
290
|
+
parameters.getAll('valdiTrace').length === 1 &&
|
|
291
|
+
parameters.get('valdiTrace') === 'chrome');
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
function identitiesMatch(left, right) {
|
|
298
|
+
return (left.sessionId === right.sessionId &&
|
|
299
|
+
left.inspectedUrl === right.inspectedUrl &&
|
|
300
|
+
left.targetNonce === right.targetNonce);
|
|
301
|
+
}
|
|
302
|
+
async function isWebPreviewPerformanceTargetPresent(identity) {
|
|
303
|
+
const targets = await (0, owlCdpClient_1.listOwlChromiumTargets)(identity.debuggingPort);
|
|
304
|
+
const candidates = targets.filter(target => target.type === 'page' && (0, owlCdpClient_1.matchesOwlApplicationUrl)(target.url, identity.applicationUrl));
|
|
305
|
+
let probeError;
|
|
306
|
+
for (const candidate of candidates) {
|
|
307
|
+
let connection;
|
|
308
|
+
try {
|
|
309
|
+
connection = await owlCdpClient_1.OwlChromiumConnection.connect(candidate.webSocketDebuggerUrl);
|
|
310
|
+
if (!(await connection.matchesTarget(identity.applicationUrl, identity.targetNonce)))
|
|
311
|
+
continue;
|
|
312
|
+
const currentUrl = await connection.evaluate('String(globalThis.location.href)');
|
|
313
|
+
if (typeof currentUrl !== 'string') {
|
|
314
|
+
throw new TypeError('The previous inspected web preview returned an invalid current URL.');
|
|
315
|
+
}
|
|
316
|
+
if (new URL(currentUrl).toString() === new URL(identity.inspectedUrl).toString())
|
|
317
|
+
return true;
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
probeError = error instanceof Error ? error : new Error(String(error));
|
|
321
|
+
}
|
|
322
|
+
finally {
|
|
323
|
+
connection?.close();
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (probeError) {
|
|
327
|
+
throw new Error(`Could not verify whether the previous inspected web preview is still present: ${probeError.message}`);
|
|
328
|
+
}
|
|
329
|
+
return false;
|
|
330
|
+
}
|
|
331
|
+
function createTransitionGate() {
|
|
332
|
+
let resolveGate;
|
|
333
|
+
const promise = new Promise(resolve => {
|
|
334
|
+
resolveGate = resolve;
|
|
335
|
+
});
|
|
336
|
+
if (!resolveGate)
|
|
337
|
+
throw new Error('Could not initialize the web preview performance transition gate.');
|
|
338
|
+
return { promise, resolve: resolveGate };
|
|
339
|
+
}
|
|
340
|
+
async function assertCurrentTarget(connection, identity) {
|
|
341
|
+
if (!(await connection.matchesTarget(identity.applicationUrl, identity.targetNonce))) {
|
|
342
|
+
throw new Error('The inspected web preview changed while the performance request was running.');
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
async function assertInspectedUrl(connection, identity) {
|
|
346
|
+
const currentUrl = await connection.evaluate('String(globalThis.location.href)');
|
|
347
|
+
if (typeof currentUrl !== 'string' || new URL(currentUrl).toString() !== new URL(identity.inspectedUrl).toString()) {
|
|
348
|
+
throw new Error('The inspected web preview URL changed while the performance request was running.');
|
|
349
|
+
}
|
|
350
|
+
return currentUrl;
|
|
351
|
+
}
|
|
352
|
+
class WebPreviewTraceRecorder {
|
|
353
|
+
connection;
|
|
354
|
+
identity;
|
|
355
|
+
startMetrics;
|
|
356
|
+
rendererTracing;
|
|
357
|
+
startedAtEpochMs;
|
|
358
|
+
completionReject;
|
|
359
|
+
completionResolve;
|
|
360
|
+
completionTimer;
|
|
361
|
+
normalizer = new WebPreviewTraceNormalizer();
|
|
362
|
+
stopped = false;
|
|
363
|
+
unsubscribeClose;
|
|
364
|
+
unsubscribeEvents;
|
|
365
|
+
constructor(connection, identity, startMetrics, rendererTracing, startedAtEpochMs) {
|
|
366
|
+
this.connection = connection;
|
|
367
|
+
this.identity = identity;
|
|
368
|
+
this.startMetrics = startMetrics;
|
|
369
|
+
this.rendererTracing = rendererTracing;
|
|
370
|
+
this.startedAtEpochMs = startedAtEpochMs;
|
|
371
|
+
this.unsubscribeEvents = connection.onEvent(event => {
|
|
372
|
+
if (event.method === 'Tracing.dataCollected') {
|
|
373
|
+
const values = event.params['value'];
|
|
374
|
+
if (!Array.isArray(values))
|
|
375
|
+
return;
|
|
376
|
+
for (const value of values)
|
|
377
|
+
this.normalizer.accept(value);
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
if (event.method === 'Tracing.tracingComplete') {
|
|
381
|
+
if (event.params['dataLossOccurred'] === true)
|
|
382
|
+
this.normalizer.dataLossOccurred();
|
|
383
|
+
this.completionResolve?.();
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
this.unsubscribeClose = connection.onClose(error => this.completionReject?.(error));
|
|
387
|
+
}
|
|
388
|
+
static async start(identity) {
|
|
389
|
+
const connection = await (0, owlCdpClient_1.connectToOwlApplication)(identity.debuggingPort, identity.applicationUrl, identity.targetNonce);
|
|
390
|
+
try {
|
|
391
|
+
await assertCurrentTarget(connection, identity);
|
|
392
|
+
const currentUrl = await assertInspectedUrl(connection, identity);
|
|
393
|
+
await connection.call('Performance.enable', {}, CHROMIUM_COMMAND_TIMEOUT_MS);
|
|
394
|
+
const startMetrics = normalizeWebPreviewPerformanceMetrics(await connection.call('Performance.getMetrics', {}, CHROMIUM_COMMAND_TIMEOUT_MS));
|
|
395
|
+
const recorder = new WebPreviewTraceRecorder(connection, identity, startMetrics, rendererTracingEnabled(currentUrl), Date.now());
|
|
396
|
+
try {
|
|
397
|
+
await connection.call('Tracing.start', {
|
|
398
|
+
categories: TRACE_CATEGORIES,
|
|
399
|
+
options: 'record-as-much-as-possible',
|
|
400
|
+
transferMode: 'ReportEvents',
|
|
401
|
+
}, CHROMIUM_COMMAND_TIMEOUT_MS);
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
const startError = error instanceof Error ? error : new Error(String(error));
|
|
405
|
+
if (startError instanceof chromiumDevToolsClient_1.ChromiumDevToolsProtocolError) {
|
|
406
|
+
recorder.close();
|
|
407
|
+
throw startError;
|
|
408
|
+
}
|
|
409
|
+
let cleanupError;
|
|
410
|
+
try {
|
|
411
|
+
await recorder.stopForRecovery();
|
|
412
|
+
}
|
|
413
|
+
catch (error_) {
|
|
414
|
+
cleanupError = error_ instanceof Error ? error_ : new Error(String(error_));
|
|
415
|
+
}
|
|
416
|
+
if (cleanupError) {
|
|
417
|
+
throw new WebPreviewTraceLifecycleError(`${startError.message} Best-effort Chromium trace cleanup also failed: ${cleanupError.message}`, false, recorder);
|
|
418
|
+
}
|
|
419
|
+
throw new WebPreviewTraceLifecycleError(startError.message, true, null);
|
|
420
|
+
}
|
|
421
|
+
return recorder;
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
connection.close();
|
|
425
|
+
throw error;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
status(nowMs) {
|
|
429
|
+
return {
|
|
430
|
+
completedRecordingAvailable: false,
|
|
431
|
+
elapsedMs: Math.max(0, nowMs - this.startedAtEpochMs),
|
|
432
|
+
recording: true,
|
|
433
|
+
rendererTracingEnabled: this.rendererTracing,
|
|
434
|
+
startedAtEpochMs: this.startedAtEpochMs,
|
|
435
|
+
tracingSupported: true,
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
async stop(timedOut) {
|
|
439
|
+
if (this.stopped)
|
|
440
|
+
throw new Error('The web preview performance trace has already stopped.');
|
|
441
|
+
this.stopped = true;
|
|
442
|
+
let traceEnded = false;
|
|
443
|
+
try {
|
|
444
|
+
await this.endTracing();
|
|
445
|
+
traceEnded = true;
|
|
446
|
+
await assertCurrentTarget(this.connection, this.identity);
|
|
447
|
+
await assertInspectedUrl(this.connection, this.identity);
|
|
448
|
+
const endMetrics = normalizeWebPreviewPerformanceMetrics(await this.connection.call('Performance.getMetrics', {}, CHROMIUM_COMMAND_TIMEOUT_MS));
|
|
449
|
+
const normalized = this.normalizer.result();
|
|
450
|
+
return {
|
|
451
|
+
browserMetrics: metricDifferences(this.startMetrics, endMetrics),
|
|
452
|
+
droppedTraceEventCount: normalized.droppedTraceEventCount,
|
|
453
|
+
elapsedMs: Math.max(0, Date.now() - this.startedAtEpochMs),
|
|
454
|
+
rendererTracingEnabled: this.rendererTracing,
|
|
455
|
+
startedAtEpochMs: this.startedAtEpochMs,
|
|
456
|
+
timedOut,
|
|
457
|
+
traces: normalized.traces,
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
catch (error) {
|
|
461
|
+
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
462
|
+
throw new WebPreviewTraceLifecycleError(normalized.message, traceEnded, null);
|
|
463
|
+
}
|
|
464
|
+
finally {
|
|
465
|
+
this.close();
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async stopForRecovery() {
|
|
469
|
+
if (this.stopped)
|
|
470
|
+
throw new Error('The web preview performance trace has already stopped.');
|
|
471
|
+
this.stopped = true;
|
|
472
|
+
try {
|
|
473
|
+
await this.endTracing();
|
|
474
|
+
}
|
|
475
|
+
catch (error) {
|
|
476
|
+
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
477
|
+
throw new WebPreviewTraceLifecycleError(normalized.message, false, null);
|
|
478
|
+
}
|
|
479
|
+
finally {
|
|
480
|
+
this.close();
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
close() {
|
|
484
|
+
if (this.completionTimer !== undefined) {
|
|
485
|
+
clearTimeout(this.completionTimer);
|
|
486
|
+
this.completionTimer = undefined;
|
|
487
|
+
}
|
|
488
|
+
this.completionResolve = undefined;
|
|
489
|
+
this.completionReject = undefined;
|
|
490
|
+
this.unsubscribeEvents();
|
|
491
|
+
this.unsubscribeClose();
|
|
492
|
+
this.connection.close();
|
|
493
|
+
}
|
|
494
|
+
async endTracing() {
|
|
495
|
+
const completed = new Promise((resolve, reject) => {
|
|
496
|
+
this.completionResolve = resolve;
|
|
497
|
+
this.completionReject = reject;
|
|
498
|
+
this.completionTimer = setTimeout(() => {
|
|
499
|
+
reject(new Error('Timed out waiting for the Chromium performance trace to finish.'));
|
|
500
|
+
}, TRACE_COMPLETION_TIMEOUT_MS);
|
|
501
|
+
});
|
|
502
|
+
const completionError = completed.then(() => null, error => (error instanceof Error ? error : new Error(String(error))));
|
|
503
|
+
await this.connection.call('Tracing.end', {}, CHROMIUM_COMMAND_TIMEOUT_MS);
|
|
504
|
+
const error = await completionError;
|
|
505
|
+
if (error)
|
|
506
|
+
throw error;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
exports.WebPreviewTraceRecorder = WebPreviewTraceRecorder;
|
|
510
|
+
function normalizedSnapshotData(value) {
|
|
511
|
+
const record = asRecord(value) ?? {};
|
|
512
|
+
const navigation = asRecord(record['navigation']) ?? {};
|
|
513
|
+
const rawPaints = Array.isArray(record['paints']) ? record['paints'] : [];
|
|
514
|
+
const paints = [];
|
|
515
|
+
for (const item of rawPaints.slice(0, MAX_PAINT_ENTRIES)) {
|
|
516
|
+
const paint = asRecord(item);
|
|
517
|
+
const name = typeof paint?.['name'] === 'string' ? paint['name'] : undefined;
|
|
518
|
+
const startTime = finiteNonNegativeNumber(paint?.['startTime']);
|
|
519
|
+
if (name !== undefined && Buffer.byteLength(name, 'utf8') <= MAX_PAINT_NAME_BYTES && startTime !== undefined) {
|
|
520
|
+
paints.push({ name, startTime });
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
const domContentLoadedMs = finiteNonNegativeNumber(navigation['domContentLoadedMs']);
|
|
524
|
+
const loadMs = finiteNonNegativeNumber(navigation['loadMs']);
|
|
525
|
+
return {
|
|
526
|
+
navigation: {
|
|
527
|
+
...(domContentLoadedMs === undefined ? {} : { domContentLoadedMs }),
|
|
528
|
+
...(loadMs === undefined ? {} : { loadMs }),
|
|
529
|
+
},
|
|
530
|
+
paints,
|
|
531
|
+
rendererTracingEnabled: record['rendererTracingEnabled'] === true,
|
|
532
|
+
resourceCount: boundedSafeInteger(record['resourceCount']) ?? 0,
|
|
533
|
+
transferSize: finiteNonNegativeNumber(record['transferSize']) ?? 0,
|
|
534
|
+
uptimeMs: finiteNonNegativeNumber(record['uptimeMs']) ?? 0,
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
async function readWebPreviewPerformanceSnapshot(identity) {
|
|
538
|
+
const connection = await (0, owlCdpClient_1.connectToOwlApplication)(identity.debuggingPort, identity.applicationUrl, identity.targetNonce);
|
|
539
|
+
try {
|
|
540
|
+
await assertCurrentTarget(connection, identity);
|
|
541
|
+
await assertInspectedUrl(connection, identity);
|
|
542
|
+
await connection.call('Performance.enable', {}, CHROMIUM_COMMAND_TIMEOUT_MS);
|
|
543
|
+
const [snapshotValue, metricsValue] = await Promise.all([
|
|
544
|
+
connection.evaluate(PERFORMANCE_SNAPSHOT_EXPRESSION),
|
|
545
|
+
connection.call('Performance.getMetrics', {}, CHROMIUM_COMMAND_TIMEOUT_MS),
|
|
546
|
+
]);
|
|
547
|
+
await assertCurrentTarget(connection, identity);
|
|
548
|
+
await assertInspectedUrl(connection, identity);
|
|
549
|
+
const snapshot = normalizedSnapshotData(snapshotValue);
|
|
550
|
+
const metrics = normalizeWebPreviewPerformanceMetrics(metricsValue);
|
|
551
|
+
const heapUsedBytes = finiteNonNegativeNumber(metrics['JSHeapUsedSize']);
|
|
552
|
+
const heapTotalBytes = finiteNonNegativeNumber(metrics['JSHeapTotalSize']);
|
|
553
|
+
return {
|
|
554
|
+
...snapshot,
|
|
555
|
+
mainThread: {
|
|
556
|
+
...(finiteNonNegativeNumber(metrics['TaskDuration']) === undefined
|
|
557
|
+
? {}
|
|
558
|
+
: { taskDurationMs: (metrics['TaskDuration'] ?? 0) * 1000 }),
|
|
559
|
+
...(finiteNonNegativeNumber(metrics['ScriptDuration']) === undefined
|
|
560
|
+
? {}
|
|
561
|
+
: { scriptDurationMs: (metrics['ScriptDuration'] ?? 0) * 1000 }),
|
|
562
|
+
...(finiteNonNegativeNumber(metrics['LayoutDuration']) === undefined
|
|
563
|
+
? {}
|
|
564
|
+
: { layoutDurationMs: (metrics['LayoutDuration'] ?? 0) * 1000 }),
|
|
565
|
+
},
|
|
566
|
+
memory: heapUsedBytes === undefined && heapTotalBytes === undefined
|
|
567
|
+
? null
|
|
568
|
+
: {
|
|
569
|
+
...(heapUsedBytes === undefined ? {} : { usedBytes: heapUsedBytes }),
|
|
570
|
+
...(heapTotalBytes === undefined ? {} : { totalBytes: heapTotalBytes }),
|
|
571
|
+
},
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
finally {
|
|
575
|
+
connection.close();
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
async function enableWebPreviewRendererTracing(identity) {
|
|
579
|
+
const connection = await (0, owlCdpClient_1.connectToOwlApplication)(identity.debuggingPort, identity.applicationUrl, identity.targetNonce);
|
|
580
|
+
try {
|
|
581
|
+
await assertCurrentTarget(connection, identity);
|
|
582
|
+
const currentUrl = await assertInspectedUrl(connection, identity);
|
|
583
|
+
const nextUrl = new URL(currentUrl);
|
|
584
|
+
nextUrl.searchParams.set('valdiDevTools', '1');
|
|
585
|
+
nextUrl.searchParams.set('valdiTrace', 'chrome');
|
|
586
|
+
await assertCurrentTarget(connection, identity);
|
|
587
|
+
await connection.call('Page.navigate', { url: nextUrl.toString() }, CHROMIUM_COMMAND_TIMEOUT_MS);
|
|
588
|
+
return nextUrl.toString();
|
|
589
|
+
}
|
|
590
|
+
finally {
|
|
591
|
+
connection.close();
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
function defaultDependencies() {
|
|
595
|
+
return {
|
|
596
|
+
clearTimer: timer => clearTimeout(timer),
|
|
597
|
+
enableTracing: enableWebPreviewRendererTracing,
|
|
598
|
+
now: () => Date.now(),
|
|
599
|
+
readSnapshot: readWebPreviewPerformanceSnapshot,
|
|
600
|
+
setTimer: (callback, durationMs) => {
|
|
601
|
+
const timer = setTimeout(callback, durationMs);
|
|
602
|
+
timer.unref();
|
|
603
|
+
return timer;
|
|
604
|
+
},
|
|
605
|
+
startRecorder: identity => WebPreviewTraceRecorder.start(identity),
|
|
606
|
+
targetPresent: isWebPreviewPerformanceTargetPresent,
|
|
607
|
+
wait: async (durationMs) => await new Promise(resolve => {
|
|
608
|
+
setTimeout(resolve, durationMs);
|
|
609
|
+
}),
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
class WebPreviewPerformanceController {
|
|
613
|
+
dependencies;
|
|
614
|
+
activeTrace;
|
|
615
|
+
completion;
|
|
616
|
+
completionExpiryTimer;
|
|
617
|
+
transitionTail = Promise.resolve();
|
|
618
|
+
constructor(dependencies) {
|
|
619
|
+
this.dependencies = dependencies;
|
|
620
|
+
}
|
|
621
|
+
async snapshot(identity) {
|
|
622
|
+
return await this.dependencies.readSnapshot(identity);
|
|
623
|
+
}
|
|
624
|
+
async enableTracing(identity) {
|
|
625
|
+
return await this.runExclusive(async () => {
|
|
626
|
+
this.expireCompletion();
|
|
627
|
+
await this.recoverMissingOwner(identity);
|
|
628
|
+
if (this.activeTrace || (this.completion && !this.completion.delivered)) {
|
|
629
|
+
throw new Error('Stop the current web preview performance trace before enabling renderer events.');
|
|
630
|
+
}
|
|
631
|
+
return this.dependencies.enableTracing(identity);
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
async status(identity) {
|
|
635
|
+
return await this.runExclusive(async () => {
|
|
636
|
+
this.expireCompletion();
|
|
637
|
+
await this.recoverMissingOwner(identity);
|
|
638
|
+
if (this.activeTrace) {
|
|
639
|
+
this.assertIdentity(this.activeTrace.identity, identity);
|
|
640
|
+
if (this.activeTrace.cleanupError)
|
|
641
|
+
throw this.activeTrace.cleanupError;
|
|
642
|
+
return this.activeTrace.recorder.status(this.dependencies.now());
|
|
643
|
+
}
|
|
644
|
+
if (this.completion && !this.completion.delivered) {
|
|
645
|
+
this.assertIdentity(this.completion.identity, identity);
|
|
646
|
+
return {
|
|
647
|
+
completedRecordingAvailable: this.completion.capture !== undefined,
|
|
648
|
+
...(this.completion.error ? { completionError: this.completion.error.message } : {}),
|
|
649
|
+
recording: false,
|
|
650
|
+
rendererTracingEnabled: rendererTracingEnabled(identity.inspectedUrl),
|
|
651
|
+
tracingSupported: true,
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
return {
|
|
655
|
+
completedRecordingAvailable: false,
|
|
656
|
+
recording: false,
|
|
657
|
+
rendererTracingEnabled: rendererTracingEnabled(identity.inspectedUrl),
|
|
658
|
+
tracingSupported: true,
|
|
659
|
+
};
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
async start(identity) {
|
|
663
|
+
return await this.runExclusive(async () => await this.startTrace(identity, true));
|
|
664
|
+
}
|
|
665
|
+
async stop(identity) {
|
|
666
|
+
return await this.runExclusive(async () => {
|
|
667
|
+
this.expireCompletion();
|
|
668
|
+
await this.recoverMissingOwner(identity);
|
|
669
|
+
if (this.activeTrace) {
|
|
670
|
+
this.assertIdentity(this.activeTrace.identity, identity);
|
|
671
|
+
if (this.activeTrace.cleanupError)
|
|
672
|
+
throw this.activeTrace.cleanupError;
|
|
673
|
+
return await this.finishActiveTrace(false, true);
|
|
674
|
+
}
|
|
675
|
+
if (this.completion) {
|
|
676
|
+
this.assertIdentity(this.completion.identity, identity);
|
|
677
|
+
if (this.completion.error) {
|
|
678
|
+
const error = this.completion.error;
|
|
679
|
+
this.clearCompletion();
|
|
680
|
+
throw error;
|
|
681
|
+
}
|
|
682
|
+
if (!this.completion.capture)
|
|
683
|
+
throw new Error('The completed Chromium trace is unavailable.');
|
|
684
|
+
this.completion.delivered = true;
|
|
685
|
+
return this.completion.capture;
|
|
686
|
+
}
|
|
687
|
+
throw new Error('No Chromium performance trace is available for the inspected web preview.');
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
async capture(identity, durationMs) {
|
|
691
|
+
await this.runExclusive(async () => await this.startTrace(identity, false));
|
|
692
|
+
try {
|
|
693
|
+
await this.dependencies.wait(durationMs);
|
|
694
|
+
}
|
|
695
|
+
catch (error) {
|
|
696
|
+
try {
|
|
697
|
+
await this.stop(identity);
|
|
698
|
+
}
|
|
699
|
+
catch (cleanupError) {
|
|
700
|
+
throw new Error(`${error instanceof Error ? error.message : String(error)} Best-effort Chromium trace cleanup also failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
|
|
701
|
+
}
|
|
702
|
+
throw error;
|
|
703
|
+
}
|
|
704
|
+
return await this.stop(identity);
|
|
705
|
+
}
|
|
706
|
+
async close() {
|
|
707
|
+
await this.runExclusive(async () => {
|
|
708
|
+
let closeError;
|
|
709
|
+
if (this.activeTrace) {
|
|
710
|
+
const active = this.activeTrace;
|
|
711
|
+
this.activeTrace = undefined;
|
|
712
|
+
this.clearWatchdog(active.watchdog);
|
|
713
|
+
try {
|
|
714
|
+
await active.recorder.stop(false);
|
|
715
|
+
}
|
|
716
|
+
catch (error) {
|
|
717
|
+
closeError = error instanceof Error ? error : new Error(String(error));
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
this.clearCompletion();
|
|
721
|
+
if (closeError)
|
|
722
|
+
throw closeError;
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
assertIdentity(expected, actual) {
|
|
726
|
+
if (!identitiesMatch(expected, actual)) {
|
|
727
|
+
throw new Error('Another inspected web preview owns the current Chromium performance trace.');
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
async finishActiveTrace(timedOut, delivered) {
|
|
731
|
+
const active = this.activeTrace;
|
|
732
|
+
if (!active)
|
|
733
|
+
throw new Error('No Chromium performance trace is recording.');
|
|
734
|
+
this.clearWatchdog(active.watchdog);
|
|
735
|
+
active.watchdog = undefined;
|
|
736
|
+
try {
|
|
737
|
+
const capture = await active.recorder.stop(timedOut);
|
|
738
|
+
if (this.activeTrace === active)
|
|
739
|
+
this.activeTrace = undefined;
|
|
740
|
+
this.retainCompletion({ capture, delivered, identity: active.identity });
|
|
741
|
+
return capture;
|
|
742
|
+
}
|
|
743
|
+
catch (error) {
|
|
744
|
+
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
745
|
+
if (error instanceof WebPreviewTraceLifecycleError && error.traceEnded) {
|
|
746
|
+
if (this.activeTrace === active)
|
|
747
|
+
this.activeTrace = undefined;
|
|
748
|
+
this.retainCompletion({ delivered, error: normalized, identity: active.identity });
|
|
749
|
+
}
|
|
750
|
+
else {
|
|
751
|
+
active.cleanupError = normalized;
|
|
752
|
+
}
|
|
753
|
+
throw normalized;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
async startTrace(identity, armWatchdog) {
|
|
757
|
+
this.expireCompletion();
|
|
758
|
+
await this.recoverMissingOwner(identity);
|
|
759
|
+
if (this.activeTrace) {
|
|
760
|
+
if (this.activeTrace.cleanupError)
|
|
761
|
+
throw this.activeTrace.cleanupError;
|
|
762
|
+
throw new Error('A Chromium performance trace is already recording.');
|
|
763
|
+
}
|
|
764
|
+
if (this.completion && !this.completion.delivered) {
|
|
765
|
+
throw new Error('Retrieve the completed Chromium performance trace before starting another recording.');
|
|
766
|
+
}
|
|
767
|
+
this.clearCompletion();
|
|
768
|
+
let recorder;
|
|
769
|
+
try {
|
|
770
|
+
recorder = await this.dependencies.startRecorder(identity);
|
|
771
|
+
}
|
|
772
|
+
catch (error) {
|
|
773
|
+
if (error instanceof WebPreviewTraceLifecycleError && !error.traceEnded && error.recorder) {
|
|
774
|
+
this.activeTrace = {
|
|
775
|
+
cleanupError: error,
|
|
776
|
+
identity,
|
|
777
|
+
recorder: error.recorder,
|
|
778
|
+
watchdog: undefined,
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
throw error;
|
|
782
|
+
}
|
|
783
|
+
const watchdog = armWatchdog
|
|
784
|
+
? this.dependencies.setTimer(() => {
|
|
785
|
+
void this.runExclusive(async () => {
|
|
786
|
+
if (!this.activeTrace || this.activeTrace.recorder !== recorder)
|
|
787
|
+
return;
|
|
788
|
+
await this.finishActiveTrace(true, false);
|
|
789
|
+
}).catch(error => {
|
|
790
|
+
console.warn('[Valdi DevTools] Could not finalize the web preview performance trace.', error);
|
|
791
|
+
});
|
|
792
|
+
}, exports.WEB_PREVIEW_TRACE_WATCHDOG_MS)
|
|
793
|
+
: undefined;
|
|
794
|
+
this.activeTrace = { identity, recorder, watchdog };
|
|
795
|
+
return recorder.status(this.dependencies.now());
|
|
796
|
+
}
|
|
797
|
+
clearWatchdog(watchdog) {
|
|
798
|
+
if (watchdog !== undefined)
|
|
799
|
+
this.dependencies.clearTimer(watchdog);
|
|
800
|
+
}
|
|
801
|
+
async recoverMissingOwner(identity) {
|
|
802
|
+
const owner = this.activeTrace?.identity ??
|
|
803
|
+
(this.completion && !this.completion.delivered ? this.completion.identity : undefined);
|
|
804
|
+
if (!owner || identitiesMatch(owner, identity))
|
|
805
|
+
return;
|
|
806
|
+
if (await this.dependencies.targetPresent(owner)) {
|
|
807
|
+
throw new Error('Another inspected web preview owns the current Chromium performance trace.');
|
|
808
|
+
}
|
|
809
|
+
if (this.activeTrace) {
|
|
810
|
+
const active = this.activeTrace;
|
|
811
|
+
if (active.cleanupError)
|
|
812
|
+
throw active.cleanupError;
|
|
813
|
+
this.clearWatchdog(active.watchdog);
|
|
814
|
+
try {
|
|
815
|
+
await active.recorder.stopForRecovery();
|
|
816
|
+
}
|
|
817
|
+
catch (error) {
|
|
818
|
+
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
819
|
+
active.cleanupError = new Error(`Could not end the previous web preview performance trace after its inspected target disappeared: ${normalized.message}`);
|
|
820
|
+
throw active.cleanupError;
|
|
821
|
+
}
|
|
822
|
+
if (this.activeTrace === active)
|
|
823
|
+
this.activeTrace = undefined;
|
|
824
|
+
}
|
|
825
|
+
this.clearCompletion();
|
|
826
|
+
}
|
|
827
|
+
retainCompletion(value) {
|
|
828
|
+
this.clearCompletion();
|
|
829
|
+
const expiresAtMs = this.dependencies.now() + exports.WEB_PREVIEW_TRACE_RESULT_TTL_MS;
|
|
830
|
+
this.completion = { ...value, expiresAtMs };
|
|
831
|
+
this.completionExpiryTimer = this.dependencies.setTimer(() => {
|
|
832
|
+
void this.runExclusive(() => this.expireCompletion()).catch(error => {
|
|
833
|
+
console.warn('[Valdi DevTools] Could not expire the web preview performance result.', error);
|
|
834
|
+
});
|
|
835
|
+
}, exports.WEB_PREVIEW_TRACE_RESULT_TTL_MS);
|
|
836
|
+
}
|
|
837
|
+
expireCompletion() {
|
|
838
|
+
if (this.completion && this.completion.expiresAtMs <= this.dependencies.now())
|
|
839
|
+
this.clearCompletion();
|
|
840
|
+
}
|
|
841
|
+
clearCompletion() {
|
|
842
|
+
if (this.completionExpiryTimer !== undefined) {
|
|
843
|
+
this.dependencies.clearTimer(this.completionExpiryTimer);
|
|
844
|
+
this.completionExpiryTimer = undefined;
|
|
845
|
+
}
|
|
846
|
+
this.completion = undefined;
|
|
847
|
+
}
|
|
848
|
+
async runExclusive(operation) {
|
|
849
|
+
const previous = this.transitionTail;
|
|
850
|
+
const gate = createTransitionGate();
|
|
851
|
+
this.transitionTail = gate.promise;
|
|
852
|
+
await previous;
|
|
853
|
+
try {
|
|
854
|
+
return await operation();
|
|
855
|
+
}
|
|
856
|
+
finally {
|
|
857
|
+
gate.resolve();
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
exports.WebPreviewPerformanceController = WebPreviewPerformanceController;
|
|
862
|
+
function createWebPreviewPerformanceController() {
|
|
863
|
+
return new WebPreviewPerformanceController(defaultDependencies());
|
|
864
|
+
}
|