@react-perfscope/core 0.1.1 → 0.3.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/README.md +2 -6
- package/dist/index.cjs +52 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -3
- package/dist/index.d.ts +26 -3
- package/dist/index.js +50 -10
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @react-perfscope/core
|
|
2
2
|
|
|
3
|
-
Core recording engine for `react-perfscope`. Provides a `Recorder` and pluggable `Collector`s that emit normalized performance signals (forced-reflow, long-
|
|
3
|
+
Core recording engine for `react-perfscope`. Provides a `Recorder` and pluggable `Collector`s that emit normalized performance signals (forced-reflow, long-task, layout-shift, network, web-vital, interaction).
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -18,7 +18,6 @@ import {
|
|
|
18
18
|
createLayoutShiftCollector,
|
|
19
19
|
createNetworkCollector,
|
|
20
20
|
createWebVitalsCollector,
|
|
21
|
-
createPaintCollector,
|
|
22
21
|
} from '@react-perfscope/core'
|
|
23
22
|
|
|
24
23
|
const recorder = createRecorder()
|
|
@@ -27,7 +26,6 @@ recorder.use(createLongTasksCollector())
|
|
|
27
26
|
recorder.use(createLayoutShiftCollector())
|
|
28
27
|
recorder.use(createNetworkCollector())
|
|
29
28
|
recorder.use(createWebVitalsCollector())
|
|
30
|
-
recorder.use(createPaintCollector())
|
|
31
29
|
|
|
32
30
|
recorder.start()
|
|
33
31
|
// ... user interaction ...
|
|
@@ -53,7 +51,7 @@ const original = await resolver.resolve(parsedFrame)
|
|
|
53
51
|
|
|
54
52
|
# 한국어
|
|
55
53
|
|
|
56
|
-
`react-perfscope`의 핵심 레코딩 엔진. `Recorder`와 플러그인 방식의 `Collector`를 제공해서 정규화된 성능 신호(forced-reflow, long-
|
|
54
|
+
`react-perfscope`의 핵심 레코딩 엔진. `Recorder`와 플러그인 방식의 `Collector`를 제공해서 정규화된 성능 신호(forced-reflow, long-task, layout-shift, network, web-vital, interaction)를 내보낸다.
|
|
57
55
|
|
|
58
56
|
## 설치
|
|
59
57
|
|
|
@@ -71,7 +69,6 @@ import {
|
|
|
71
69
|
createLayoutShiftCollector,
|
|
72
70
|
createNetworkCollector,
|
|
73
71
|
createWebVitalsCollector,
|
|
74
|
-
createPaintCollector,
|
|
75
72
|
} from '@react-perfscope/core'
|
|
76
73
|
|
|
77
74
|
const recorder = createRecorder()
|
|
@@ -80,7 +77,6 @@ recorder.use(createLongTasksCollector())
|
|
|
80
77
|
recorder.use(createLayoutShiftCollector())
|
|
81
78
|
recorder.use(createNetworkCollector())
|
|
82
79
|
recorder.use(createWebVitalsCollector())
|
|
83
|
-
recorder.use(createPaintCollector())
|
|
84
80
|
|
|
85
81
|
recorder.start()
|
|
86
82
|
// ... 유저 인터랙션 ...
|
package/dist/index.cjs
CHANGED
|
@@ -36,7 +36,9 @@ __export(index_exports, {
|
|
|
36
36
|
createSelfProfilingCollector: () => createSelfProfilingCollector,
|
|
37
37
|
createSourceMapResolver: () => createSourceMapResolver,
|
|
38
38
|
createWebVitalsCollector: () => createWebVitalsCollector,
|
|
39
|
+
isSelfRequest: () => isSelfRequest,
|
|
39
40
|
isUserResource: () => isUserResource,
|
|
41
|
+
markSelfRequest: () => markSelfRequest,
|
|
40
42
|
parseStack: () => parseStack,
|
|
41
43
|
resolveFrame: () => resolveFrame
|
|
42
44
|
});
|
|
@@ -119,6 +121,17 @@ function createRecorder() {
|
|
|
119
121
|
|
|
120
122
|
// src/sourcemap.ts
|
|
121
123
|
var import_trace_mapping = require("@jridgewell/trace-mapping");
|
|
124
|
+
|
|
125
|
+
// src/self-requests.ts
|
|
126
|
+
var selfRequests = /* @__PURE__ */ new Set();
|
|
127
|
+
function markSelfRequest(url) {
|
|
128
|
+
selfRequests.add(url);
|
|
129
|
+
}
|
|
130
|
+
function isSelfRequest(url) {
|
|
131
|
+
return selfRequests.has(url);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/sourcemap.ts
|
|
122
135
|
var CHROME_FRAME = /^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/;
|
|
123
136
|
var FIREFOX_FRAME = /^(.*?)@(.+?):(\d+):(\d+)$/;
|
|
124
137
|
async function resolveFrame(frame, fetchMap) {
|
|
@@ -166,6 +179,7 @@ function createSourceMapResolver(opts = {}) {
|
|
|
166
179
|
if (existing) return existing;
|
|
167
180
|
const promise = (async () => {
|
|
168
181
|
try {
|
|
182
|
+
markSelfRequest(sourceUrl);
|
|
169
183
|
const res = await f(sourceUrl);
|
|
170
184
|
if (!res || !res.ok) return null;
|
|
171
185
|
const text = await res.text();
|
|
@@ -181,6 +195,7 @@ function createSourceMapResolver(opts = {}) {
|
|
|
181
195
|
return JSON.parse(decoded);
|
|
182
196
|
}
|
|
183
197
|
const mapUrl = new URL(ref, sourceUrl).href;
|
|
198
|
+
markSelfRequest(mapUrl);
|
|
184
199
|
const mapRes = await f(mapUrl);
|
|
185
200
|
if (!mapRes || !mapRes.ok) return null;
|
|
186
201
|
return await mapRes.json();
|
|
@@ -319,18 +334,47 @@ var LAYOUT_GETTERS = [
|
|
|
319
334
|
"scrollHeight"
|
|
320
335
|
];
|
|
321
336
|
var LAYOUT_METHODS = ["getBoundingClientRect", "getClientRects"];
|
|
337
|
+
var scheduleFlush = typeof queueMicrotask === "function" ? queueMicrotask : typeof Promise !== "undefined" ? (cb) => {
|
|
338
|
+
Promise.resolve().then(cb);
|
|
339
|
+
} : (cb) => cb();
|
|
322
340
|
function createForcedReflowCollector() {
|
|
323
341
|
let active = false;
|
|
324
342
|
let emit = () => {
|
|
325
343
|
};
|
|
326
344
|
const saved = [];
|
|
327
345
|
let mutationObserver = null;
|
|
346
|
+
let group = null;
|
|
328
347
|
function consumePendingMutations() {
|
|
329
348
|
if (!mutationObserver) {
|
|
330
349
|
return true;
|
|
331
350
|
}
|
|
332
351
|
return mutationObserver.takeRecords().length > 0;
|
|
333
352
|
}
|
|
353
|
+
function flush() {
|
|
354
|
+
if (!group) return;
|
|
355
|
+
const g = group;
|
|
356
|
+
group = null;
|
|
357
|
+
const signal = {
|
|
358
|
+
kind: "forced-reflow",
|
|
359
|
+
at: g.at,
|
|
360
|
+
duration: g.duration,
|
|
361
|
+
count: g.count
|
|
362
|
+
};
|
|
363
|
+
attachLazyStack(signal, g.rawStack, 1);
|
|
364
|
+
emit(signal);
|
|
365
|
+
}
|
|
366
|
+
function record(at, duration, rawStack) {
|
|
367
|
+
if (group) {
|
|
368
|
+
group.count++;
|
|
369
|
+
group.duration += duration;
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
group = { at, duration, count: 1, rawStack };
|
|
373
|
+
scheduleFlush(flush);
|
|
374
|
+
}
|
|
375
|
+
function needsStack() {
|
|
376
|
+
return group === null;
|
|
377
|
+
}
|
|
334
378
|
function patchGetter(proto, key) {
|
|
335
379
|
if (typeof proto !== "object" || proto === null) return;
|
|
336
380
|
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
@@ -344,13 +388,10 @@ function createForcedReflowCollector() {
|
|
|
344
388
|
if (!consumePendingMutations()) {
|
|
345
389
|
return originalGet.call(this);
|
|
346
390
|
}
|
|
391
|
+
const rawStack = needsStack() ? new Error().stack : void 0;
|
|
347
392
|
const at = performance.now();
|
|
348
|
-
const rawStack = new Error().stack;
|
|
349
393
|
const value = originalGet.call(this);
|
|
350
|
-
|
|
351
|
-
const signal = { kind: "forced-reflow", at, duration };
|
|
352
|
-
attachLazyStack(signal, rawStack, 1);
|
|
353
|
-
emit(signal);
|
|
394
|
+
record(at, performance.now() - at, rawStack);
|
|
354
395
|
return value;
|
|
355
396
|
}
|
|
356
397
|
return originalGet.call(this);
|
|
@@ -372,13 +413,10 @@ function createForcedReflowCollector() {
|
|
|
372
413
|
if (!consumePendingMutations()) {
|
|
373
414
|
return original.apply(this, args);
|
|
374
415
|
}
|
|
416
|
+
const rawStack = needsStack() ? new Error().stack : void 0;
|
|
375
417
|
const at = performance.now();
|
|
376
|
-
const rawStack = new Error().stack;
|
|
377
418
|
const value = original.apply(this, args);
|
|
378
|
-
|
|
379
|
-
const signal = { kind: "forced-reflow", at, duration };
|
|
380
|
-
attachLazyStack(signal, rawStack, 1);
|
|
381
|
-
emit(signal);
|
|
419
|
+
record(at, performance.now() - at, rawStack);
|
|
382
420
|
return value;
|
|
383
421
|
}
|
|
384
422
|
return original.apply(this, args);
|
|
@@ -420,6 +458,7 @@ function createForcedReflowCollector() {
|
|
|
420
458
|
deactivate() {
|
|
421
459
|
if (!active) return;
|
|
422
460
|
active = false;
|
|
461
|
+
flush();
|
|
423
462
|
if (mutationObserver) {
|
|
424
463
|
try {
|
|
425
464
|
mutationObserver.disconnect();
|
|
@@ -565,6 +604,7 @@ function createNetworkCollector() {
|
|
|
565
604
|
if (!active) return;
|
|
566
605
|
for (const raw of list.getEntries()) {
|
|
567
606
|
const entry = raw;
|
|
607
|
+
if (isSelfRequest(entry.name)) continue;
|
|
568
608
|
emit({
|
|
569
609
|
kind: "network",
|
|
570
610
|
url: entry.name,
|
|
@@ -1028,7 +1068,9 @@ function createSelfProfilingCollector() {
|
|
|
1028
1068
|
createSelfProfilingCollector,
|
|
1029
1069
|
createSourceMapResolver,
|
|
1030
1070
|
createWebVitalsCollector,
|
|
1071
|
+
isSelfRequest,
|
|
1031
1072
|
isUserResource,
|
|
1073
|
+
markSelfRequest,
|
|
1032
1074
|
parseStack,
|
|
1033
1075
|
resolveFrame
|
|
1034
1076
|
});
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/recorder.ts","../src/sourcemap.ts","../src/collectors/long-tasks.ts","../src/collectors/forced-reflow.ts","../src/collectors/layout-shift.ts","../src/collectors/network.ts","../src/collectors/web-vitals.ts","../src/collectors/heap.ts","../src/collectors/interaction.ts","../src/collectors/frames.ts","../src/collectors/self-profiling.ts"],"sourcesContent":["// Types\nexport * from './types'\n\n// Recorder\nexport { createRecorder } from './recorder'\n\n// Sourcemap utilities\nexport { parseStack, resolveFrame, attachLazyStack, createSourceMapResolver } from './sourcemap'\nexport type { FetchMap, SourceMapResolver, CreateSourceMapResolverOptions } from './sourcemap'\n\n// Collectors\nexport { createLongTasksCollector } from './collectors/long-tasks'\nexport { createForcedReflowCollector } from './collectors/forced-reflow'\nexport { createLayoutShiftCollector } from './collectors/layout-shift'\nexport { createNetworkCollector } from './collectors/network'\nexport { createWebVitalsCollector } from './collectors/web-vitals'\nexport { createHeapCollector, analyzeHeapTrend } from './collectors/heap'\nexport type { HeapCollector } from './collectors/heap'\nexport { createInteractionCollector } from './collectors/interaction'\nexport type { InteractionCollector } from './collectors/interaction'\nexport { createFrameCollector, analyzeFrames } from './collectors/frames'\nexport type { FrameCollector } from './collectors/frames'\nexport {\n createSelfProfilingCollector,\n attributeWindow,\n attributeLongTaskSignals,\n isUserResource,\n} from './collectors/self-profiling'\nexport type {\n ProfilerTrace,\n ProfilerFrame,\n ProfilerStack,\n ProfilerSample,\n} from './collectors/self-profiling'\n","import type { Collector, Recorder, RecordingResult, Signal } from './types'\n\nconst BUFFER_CAP = 10_000\n\nexport interface InternalRecorder extends Recorder {\n __push: (signal: Signal) => void\n}\n\nexport function createRecorder(): Recorder {\n let recording = false\n let startedAt = 0\n let buffer: Signal[] = []\n const subscribers = new Set<(s: Signal) => void>()\n const collectors: Collector[] = []\n\n function notify(signal: Signal) {\n for (const cb of subscribers) {\n try {\n cb(signal)\n } catch (err) {\n console.warn('[react-perfscope] subscriber threw:', err)\n }\n }\n }\n\n function push(signal: Signal) {\n if (!recording) return\n buffer.push(signal)\n if (buffer.length > BUFFER_CAP) {\n buffer.splice(0, buffer.length - BUFFER_CAP)\n }\n notify(signal)\n }\n\n const recorder: InternalRecorder = {\n start() {\n if (recording) return\n recording = true\n startedAt = performance.now()\n buffer = []\n for (const c of collectors) {\n try {\n c.activate(push)\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to activate:`, err)\n }\n }\n },\n stop(): RecordingResult {\n if (!recording) {\n return { signals: [], startedAt: 0, duration: 0 }\n }\n for (const c of collectors) {\n try {\n c.deactivate()\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to deactivate:`, err)\n }\n }\n const duration = performance.now() - startedAt\n const result: RecordingResult = {\n signals: buffer.slice(),\n startedAt,\n duration,\n }\n recording = false\n buffer = []\n return result\n },\n isRecording() {\n return recording\n },\n onSignal(cb) {\n subscribers.add(cb)\n return () => subscribers.delete(cb)\n },\n use(collector) {\n collectors.push(collector)\n },\n __push: push,\n }\n return recorder\n}\n","import { TraceMap, originalPositionFor, type SourceMapInput } from '@jridgewell/trace-mapping'\nimport type { StackFrame } from './types'\n\nconst CHROME_FRAME = /^\\s*at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/\nconst FIREFOX_FRAME = /^(.*?)@(.+?):(\\d+):(\\d+)$/\n\n/** A parsed source map (the JSON object), as returned by a FetchMap. */\nexport type RawSourceMap = SourceMapInput\n\nexport type FetchMap = (file: string) => Promise<RawSourceMap | null>\n\nexport async function resolveFrame(\n frame: StackFrame,\n fetchMap: FetchMap\n): Promise<StackFrame> {\n try {\n const map = await fetchMap(frame.file)\n if (!map) return frame\n // trace-mapping is pure JS (no wasm), so this works in the browser where\n // Mozilla's source-map SourceMapConsumer needs an explicitly-initialized\n // mappings.wasm. Columns are 0-based here, matching the captured frames.\n const tracer = new TraceMap(map)\n const pos = originalPositionFor(tracer, { line: frame.line, column: frame.col })\n if (pos.source == null || pos.line == null || pos.column == null) {\n return frame\n }\n const resolved: StackFrame = {\n file: pos.source,\n line: pos.line,\n col: pos.column,\n }\n if (pos.name) resolved.fnName = pos.name\n else if (frame.fnName) resolved.fnName = frame.fnName\n return resolved\n } catch (err) {\n console.warn('[react-perfscope] resolveFrame failed:', err)\n return frame\n }\n}\n\n/**\n * Attach a lazy `stack` getter to `target` that parses `raw` on first access\n * and memoizes the result. Use this from collectors to defer parseStack cost\n * until a consumer actually reads `signal.stack`.\n *\n * `skipTopFrames` drops the leading N parsed frames — useful for collectors\n * that wrap a patched function (the wrapper itself shows up as the topmost\n * frame, but it's noise from the user's perspective).\n */\nexport function attachLazyStack(\n target: object,\n raw: string | undefined,\n skipTopFrames = 0\n): void {\n let cached: StackFrame[] | null = null\n Object.defineProperty(target, 'stack', {\n enumerable: true,\n configurable: true,\n get() {\n if (cached === null) {\n const all = parseStack(raw)\n cached = skipTopFrames > 0 ? all.slice(skipTopFrames) : all\n }\n return cached\n },\n })\n}\n\nexport interface SourceMapResolver {\n /** Resolve a parsed StackFrame to its original source position. Falls back to the input frame on any failure. */\n resolve(frame: StackFrame): Promise<StackFrame>\n}\n\nexport interface CreateSourceMapResolverOptions {\n /** Override the global fetch. Useful for tests and non-browser environments. */\n fetch?: typeof globalThis.fetch\n}\n\n/**\n * Create a SourceMap resolver that fetches `.map` files from the live URL\n * referenced in each source file's `//# sourceMappingURL=` directive.\n * Caches the parsed source map per source URL so repeated resolves against\n * the same file are O(1) after the first.\n *\n * Returns the input frame on any failure (network error, missing map, etc.).\n */\nexport function createSourceMapResolver(opts: CreateSourceMapResolverOptions = {}): SourceMapResolver {\n const f = opts.fetch ?? (typeof fetch !== 'undefined' ? fetch.bind(globalThis) : null)\n const cache = new Map<string, Promise<RawSourceMap | null>>()\n\n function fetchMapFor(sourceUrl: string): Promise<RawSourceMap | null> {\n if (!f) return Promise.resolve(null)\n const existing = cache.get(sourceUrl)\n if (existing) return existing\n const promise = (async () => {\n try {\n const res = await f(sourceUrl)\n if (!res || !res.ok) return null\n const text = await res.text()\n const m = text.match(/\\/\\/[#@]\\s*sourceMappingURL=(.+?)\\s*$/m)\n if (!m) return null\n const ref = m[1]!.trim()\n if (ref.startsWith('data:')) {\n const commaIdx = ref.indexOf(',')\n if (commaIdx === -1) return null\n const header = ref.slice(0, commaIdx)\n const payload = ref.slice(commaIdx + 1)\n const decoded = header.includes('base64')\n ? typeof atob === 'function'\n ? atob(payload)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n : (globalThis as any).Buffer.from(payload, 'base64').toString('utf8')\n : decodeURIComponent(payload)\n return JSON.parse(decoded) as RawSourceMap\n }\n const mapUrl = new URL(ref, sourceUrl).href\n const mapRes = await f(mapUrl)\n if (!mapRes || !mapRes.ok) return null\n return (await mapRes.json()) as RawSourceMap\n } catch {\n return null\n }\n })()\n cache.set(sourceUrl, promise)\n return promise\n }\n\n return {\n async resolve(frame) {\n try {\n return await resolveFrame(frame, fetchMapFor)\n } catch {\n return frame\n }\n },\n }\n}\n\nexport function parseStack(raw: string | undefined): StackFrame[] {\n if (!raw) return []\n const frames: StackFrame[] = []\n for (const line of raw.split('\\n')) {\n const chromeMatch = line.match(CHROME_FRAME)\n if (chromeMatch) {\n const [, fnName, file, lineStr, colStr] = chromeMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n continue\n }\n const firefoxMatch = line.match(FIREFOX_FRAME)\n if (firefoxMatch) {\n const [, fnName, file, lineStr, colStr] = firefoxMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n }\n }\n return frames\n}\n","import type { Collector, LongTaskScript, Signal } from '../types'\n\nconst LOAF = 'long-animation-frame'\nconst LEGACY = 'longtask'\n\n/** A single script entry inside a Long Animation Frame. */\ninterface ScriptTiming {\n duration?: number\n invoker?: string\n invokerType?: string\n sourceURL?: string\n sourceFunctionName?: string\n sourceCharPosition?: number\n}\n\ninterface LoAFEntry extends PerformanceEntry {\n blockingDuration?: number\n scripts?: ScriptTiming[]\n}\n\nfunction supportsLoAF(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n return Array.isArray(types) && types.includes(LOAF)\n}\n\nfunction mapScripts(scripts: ScriptTiming[]): LongTaskScript[] {\n return scripts.map((s) => ({\n invokerType: s.invokerType ?? 'unknown',\n invoker: s.invoker ?? '',\n sourceURL: s.sourceURL ?? '',\n sourceFunctionName: s.sourceFunctionName ?? '',\n charPosition: typeof s.sourceCharPosition === 'number' ? s.sourceCharPosition : -1,\n duration: typeof s.duration === 'number' ? s.duration : 0,\n }))\n}\n\nexport function createLongTasksCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'long-task',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; long-tasks disabled')\n return\n }\n active = true\n const useLoAF = supportsLoAF()\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const entry of list.getEntries()) {\n if (useLoAF) {\n const loaf = entry as LoAFEntry\n const scripts = Array.isArray(loaf.scripts) ? mapScripts(loaf.scripts) : []\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n scripts,\n ...(typeof loaf.blockingDuration === 'number'\n ? { blockingDuration: loaf.blockingDuration }\n : {}),\n })\n } else {\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n })\n }\n }\n })\n observer.observe({ type: useLoAF ? LOAF : LEGACY, buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] long-tasks collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\nimport { attachLazyStack } from '../sourcemap'\n\nconst LAYOUT_GETTERS = [\n 'offsetWidth',\n 'offsetHeight',\n 'offsetLeft',\n 'offsetTop',\n 'clientWidth',\n 'clientHeight',\n 'scrollWidth',\n 'scrollHeight',\n] as const\n\nconst LAYOUT_METHODS = ['getBoundingClientRect', 'getClientRects'] as const\n\ntype SavedDescriptor = {\n proto: object\n key: string\n descriptor: PropertyDescriptor\n}\n\nexport function createForcedReflowCollector(): Collector {\n let active = false\n let emit: (s: Signal) => void = () => {}\n const saved: SavedDescriptor[] = []\n let mutationObserver: MutationObserver | null = null\n\n function consumePendingMutations(): boolean {\n if (!mutationObserver) {\n // Fallback when MutationObserver isn't available: always treat as dirty\n // (Phase 1 over-report behavior).\n return true\n }\n return mutationObserver.takeRecords().length > 0\n }\n\n function patchGetter(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || !desc.get) return\n saved.push({ proto, key, descriptor: desc })\n const originalGet = desc.get\n Object.defineProperty(proto, key, {\n configurable: true,\n get(this: unknown) {\n if (active) {\n if (!consumePendingMutations()) {\n return originalGet.call(this)\n }\n const at = performance.now()\n const rawStack = new Error().stack\n const value = originalGet.call(this)\n const duration = performance.now() - at\n const signal = { kind: 'forced-reflow' as const, at, duration } as unknown as Signal\n attachLazyStack(signal, rawStack, 1)\n emit(signal)\n return value\n }\n return originalGet.call(this)\n },\n set: desc.set,\n })\n }\n\n function patchMethod(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || typeof desc.value !== 'function') return\n saved.push({ proto, key, descriptor: desc })\n const original = desc.value as (...args: unknown[]) => unknown\n Object.defineProperty(proto, key, {\n configurable: true,\n writable: true,\n value: function patchedLayoutMethod(this: unknown, ...args: unknown[]) {\n if (active) {\n if (!consumePendingMutations()) {\n return original.apply(this, args)\n }\n const at = performance.now()\n const rawStack = new Error().stack\n const value = original.apply(this, args)\n const duration = performance.now() - at\n const signal = { kind: 'forced-reflow' as const, at, duration } as unknown as Signal\n attachLazyStack(signal, rawStack, 1)\n emit(signal)\n return value\n }\n return original.apply(this, args)\n },\n })\n }\n\n return {\n kind: 'forced-reflow',\n activate(emitFn) {\n if (active) return\n emit = emitFn\n active = true\n\n if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {\n try {\n mutationObserver = new MutationObserver(() => {})\n mutationObserver.observe(document, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: true,\n })\n } catch (err) {\n console.warn('[react-perfscope] forced-reflow MutationObserver failed:', err)\n mutationObserver = null\n }\n }\n\n if (typeof HTMLElement !== 'undefined') {\n for (const key of LAYOUT_GETTERS) {\n patchGetter(HTMLElement.prototype, key)\n }\n }\n if (typeof Element !== 'undefined') {\n for (const key of LAYOUT_METHODS) {\n patchMethod(Element.prototype, key)\n }\n }\n },\n deactivate() {\n if (!active) return\n active = false\n if (mutationObserver) {\n try {\n mutationObserver.disconnect()\n } catch {\n // ignore\n }\n mutationObserver = null\n }\n for (const { proto, key, descriptor } of saved) {\n Object.defineProperty(proto, key, descriptor)\n }\n saved.length = 0\n },\n }\n}\n","import type { Collector, Signal } from '../types'\n\ninterface LayoutShiftSource {\n currentRect: DOMRect\n previousRect?: DOMRect\n node?: Node | null\n}\n\ninterface LayoutShiftEntryLike extends PerformanceEntry {\n value: number\n hadRecentInput: boolean\n sources?: LayoutShiftSource[]\n}\n\nconst PERFSCOPE_HOST_ATTR = 'data-perfscope-host'\n\nfunction rectsOverlap(a: DOMRect, b: DOMRect, tolerance = 0): boolean {\n return !(\n a.x + a.width < b.x - tolerance ||\n b.x + b.width < a.x - tolerance ||\n a.y + a.height < b.y - tolerance ||\n b.y + b.height < a.y - tolerance\n )\n}\n\n/**\n * Returns true when every source in the entry is part of our floating\n * widget. We want to ignore shifts caused by the perfscope UI itself.\n *\n * Detection has two paths:\n * 1. Node-based: walk up `source.node` looking for `[data-perfscope-host]`.\n * Works when the node is in light DOM.\n * 2. Rect-based fallback: compare `source.currentRect` against every host\n * element's bounding rect. This catches the Shadow-DOM case where the\n * browser doesn't expose the inner node (Shadow root boundary).\n */\nfunction collectPerfscopeRects(): DOMRect[] {\n const hosts = Array.from(document.querySelectorAll(`[${PERFSCOPE_HOST_ATTR}]`))\n const rects: DOMRect[] = []\n for (const h of hosts) {\n // The light-DOM host element usually has height 0 because Shadow DOM\n // content isn't part of its layout. We need to peek inside the shadow\n // root and collect bounds of any positioned children.\n const sr = (h as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot\n if (sr) {\n for (const child of Array.from(sr.children)) {\n const r = (child as Element).getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n } else {\n const r = h.getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n }\n return rects\n}\n\nfunction entryIsOnlyFromPerfscope(sources: LayoutShiftSource[]): boolean {\n if (sources.length === 0) return false\n if (typeof document === 'undefined') return false\n\n const hostRects = collectPerfscopeRects()\n if (hostRects.length === 0) return false\n\n for (const src of sources) {\n let matched = false\n const node = src.node as (Node & { closest?: (sel: string) => Element | null }) | null | undefined\n if (node) {\n // Node-based check\n if (typeof (node as { closest?: unknown }).closest === 'function') {\n if ((node as Element).closest(`[${PERFSCOPE_HOST_ATTR}]`)) matched = true\n } else {\n let parent: (Element | null) = (node as Node).parentElement as Element | null\n while (parent) {\n if (parent.hasAttribute(PERFSCOPE_HOST_ATTR)) { matched = true; break }\n parent = parent.parentElement\n }\n }\n }\n // Rect-based fallback (shadow DOM): if source rect overlaps any of our\n // host rects, consider it our widget. Tolerance covers the case where\n // the widget changes size during the shift (its previous/current bounds\n // differ but both sit in the same screen corner).\n if (!matched) {\n for (const hostRect of hostRects) {\n if (rectsOverlap(src.currentRect, hostRect, 24)) {\n matched = true\n break\n }\n }\n }\n if (!matched) return false\n }\n return true\n}\n\nexport function createLayoutShiftCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'layout-shift',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; layout-shift disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as LayoutShiftEntryLike\n // Note: production CLS metrics exclude shifts with hadRecentInput\n // (user-initiated movements are considered intentional). For a\n // dev tool, the user explicitly WANTS to see what their clicks\n // caused — so we report these too.\n const sources = entry.sources ?? []\n if (entryIsOnlyFromPerfscope(sources)) continue\n // Convert viewport-relative rects to document-relative coords so\n // overlays stay anchored to the shifted DOM position when the\n // user scrolls. Filter above runs first on viewport coords (our\n // widget is position:fixed, lives in viewport space).\n const sx = (typeof window !== 'undefined' && window.scrollX) || 0\n const sy = (typeof window !== 'undefined' && window.scrollY) || 0\n const toDocRect = (r: DOMRect) =>\n new DOMRect(r.x + sx, r.y + sy, r.width, r.height)\n const rects = sources.map((s) => toDocRect(s.currentRect))\n // previousRect is undefined when the element was newly inserted.\n // An \"empty\" rect (w=0, h=0) likewise means there was no prior\n // box — treat both as `null` so the overlay can decide not to\n // draw an arrow for these.\n const prevRects: (DOMRect | null)[] = sources.map((s) => {\n const pr = s.previousRect\n if (!pr) return null\n if (pr.width === 0 && pr.height === 0) return null\n return toDocRect(pr)\n })\n emit({\n kind: 'layout-shift',\n at: entry.startTime,\n value: entry.value,\n sources: rects,\n previousSources: prevRects,\n })\n }\n })\n observer.observe({ type: 'layout-shift', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] layout-shift collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\n\ninterface ResourceTimingLike extends PerformanceEntry {\n transferSize?: number\n renderBlockingStatus?: 'blocking' | 'non-blocking'\n}\n\nexport function createNetworkCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'network',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; network disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as ResourceTimingLike\n emit({\n kind: 'network',\n url: entry.name,\n startedAt: entry.startTime,\n duration: entry.duration,\n size: entry.transferSize ?? 0,\n blocking: entry.renderBlockingStatus === 'blocking',\n })\n }\n })\n observer.observe({ type: 'resource', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] network collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import { onLCP, onINP, onCLS, onFCP, onTTFB, type Metric } from 'web-vitals'\nimport type { Collector, Signal, WebVitalSignal } from '../types'\n\ntype VitalName = WebVitalSignal['name']\n\nexport function createWebVitalsCollector(): Collector {\n let active = false\n let subscribed = false\n let emit: (signal: Signal) => void = () => {}\n\n function makeHandler(name: VitalName) {\n return (metric: Metric) => {\n if (!active) return\n emit({ kind: 'web-vital', name, value: metric.value })\n }\n }\n\n return {\n kind: 'web-vital',\n activate(emitFn) {\n emit = emitFn\n active = true\n if (subscribed) return\n try {\n onLCP(makeHandler('LCP'))\n onINP(makeHandler('INP'))\n onCLS(makeHandler('CLS'))\n onFCP(makeHandler('FCP'))\n onTTFB(makeHandler('TTFB'))\n subscribed = true\n } catch (err) {\n console.warn('[react-perfscope] web-vitals collector failed to subscribe:', err)\n active = false\n }\n },\n deactivate() {\n // The web-vitals library does not expose unsubscribe. We keep the\n // handlers attached and gate emission via `active`. Re-activating\n // updates `emit` without re-subscribing.\n active = false\n },\n }\n}\n","import type {\n Collector,\n HeapSample,\n HeapTrend,\n HeapTrendClass,\n RecordingResult,\n} from '../types'\n\n/** How often to read heap usage while recording. Reading performance.memory\n * is cheap, so we sample at 4Hz: a 1s cadence is too coarse — short spikes fall\n * between samples and the line, drawn straight between sparse points, smooths\n * them into a ramp. 250ms localizes spikes without meaningful overhead. */\nconst SAMPLE_INTERVAL_MS = 250\n/** Cap on retained samples so a multi-hour session can't grow the array\n * unbounded. At 250ms this is ~83 min; past that, oldest samples drop. */\nconst MAX_SAMPLES = 20_000\n\n/** Below this, a trend can't be estimated reliably. */\nconst MIN_SAMPLES = 4\n/** How many contiguous segments to split the series into when estimating the\n * floor. Each segment contributes its minimum (the post-GC trough). */\nconst FLOOR_SEGMENTS = 8\n\nconst MB = 1024 * 1024\n/** Floor-growth thresholds, in bytes per minute. */\nconst GROWING_SLOPE = 1 * MB\nconst LEAK_SLOPE = 5 * MB\n/** A rate alone isn't enough: over a short recording, a sub-megabyte wobble in\n * the floor extrapolates to a huge MB/min and would false-positive. Require the\n * floor to have actually risen by at least this much across the window before\n * calling anything growing/leaking. */\nconst MIN_NET_GROWTH = 2 * MB\n\ninterface MemoryInfo {\n usedJSHeapSize: number\n totalJSHeapSize: number\n jsHeapSizeLimit: number\n}\n\nfunction readMemory(): MemoryInfo | null {\n const perf = (globalThis as { performance?: { memory?: MemoryInfo } }).performance\n const mem = perf?.memory\n if (!mem || typeof mem.usedJSHeapSize !== 'number') return null\n return mem\n}\n\n/**\n * Least-squares slope of points (x, y). Returns 0 when x has no spread\n * (vertical / single distinct x) to avoid a divide-by-zero blow-up.\n */\nfunction slope(points: { x: number; y: number }[]): number {\n const n = points.length\n if (n < 2) return 0\n let sx = 0\n let sy = 0\n let sxy = 0\n let sxx = 0\n for (const { x, y } of points) {\n sx += x\n sy += y\n sxy += x * y\n sxx += x * x\n }\n const denom = n * sxx - sx * sx\n if (denom === 0) return 0\n return (n * sxy - sx * sy) / denom\n}\n\n/**\n * Estimate whether memory is being retained across the recording.\n *\n * GC makes raw heap usage a sawtooth, so the peak is noisy. The reliable\n * signal is the *floor* — the post-GC troughs. We split the series into\n * contiguous segments, take the minimum of each (its trough), and regress\n * those minima against time.\n *\n * A rising overall slope is necessary but NOT sufficient: a one-time step\n * (heap warms up early, then plateaus) also regresses to a positive slope, and\n * flagging that as a leak is a false positive — the classic \"idle recording\n * reads abnormal\" bug. A real leak keeps climbing, so we additionally require\n * the *recent* half of the floor to still be rising. We also gate on a minimum\n * net growth, since over a short window a sub-MB wobble extrapolates to a steep\n * per-minute slope.\n *\n * Returns null when there are too few samples to say anything.\n */\nexport function analyzeHeapTrend(samples: HeapSample[]): HeapTrend | null {\n if (samples.length < MIN_SAMPLES) return null\n const t0 = samples[0]!.at\n const segSize = Math.max(1, Math.ceil(samples.length / FLOOR_SEGMENTS))\n const floorPoints: { x: number; y: number }[] = []\n for (let i = 0; i < samples.length; i += segSize) {\n const seg = samples.slice(i, i + segSize)\n let min = Infinity\n for (const s of seg) min = Math.min(min, s.used)\n const mid = seg[Math.floor(seg.length / 2)]!\n floorPoints.push({ x: (mid.at - t0) / 60000, y: min })\n }\n const slopeBytesPerMin = slope(floorPoints)\n const spanMin = (samples[samples.length - 1]!.at - t0) / 60000\n const projectedGrowth = slopeBytesPerMin * spanMin\n // Recent trend: is the floor still climbing in the latter half? Distinguishes\n // a sustained leak from a one-time step that has since plateaued.\n const recent = floorPoints.slice(Math.floor(floorPoints.length / 2))\n const recentSlope = recent.length >= 2 ? slope(recent) : slopeBytesPerMin\n\n let classification: HeapTrendClass = 'stable'\n const sustained = projectedGrowth >= MIN_NET_GROWTH && recentSlope >= GROWING_SLOPE\n if (sustained) {\n classification =\n slopeBytesPerMin >= LEAK_SLOPE && recentSlope >= LEAK_SLOPE ? 'leak-suspected' : 'growing'\n }\n return { classification, slopeBytesPerMin }\n}\n\nexport interface HeapCollector extends Collector {\n /** Attach the sampled heap series to the recording result. Returns the\n * input untouched when nothing was sampled (unsupported browser). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Samples `performance.memory` on an interval for the duration of a recording\n * and attaches the series via `finalize`. It is a Collector so the recorder\n * drives its start/stop, but it emits no signals — the series is a separate\n * track (see RecordingResult.heapSamples), so a busy session's signal buffer\n * can't evict it. No-ops entirely when performance.memory is unavailable\n * (non-Chromium), leaving `heapSamples` absent so the UI can show a fallback.\n */\nexport function createHeapCollector(): HeapCollector {\n let samples: HeapSample[] = []\n let timer: ReturnType<typeof setInterval> | null = null\n\n function sample(): void {\n const mem = readMemory()\n if (!mem) return\n samples.push({ at: performance.now(), used: mem.usedJSHeapSize, total: mem.totalJSHeapSize })\n if (samples.length > MAX_SAMPLES) samples.splice(0, samples.length - MAX_SAMPLES)\n }\n\n return {\n kind: 'heap',\n activate() {\n samples = []\n if (!readMemory()) return // unsupported → never start the timer\n sample()\n timer = setInterval(sample, SAMPLE_INTERVAL_MS)\n },\n deactivate() {\n if (timer == null) return\n clearInterval(timer)\n timer = null\n sample() // one final reading at stop\n },\n finalize(result) {\n if (samples.length === 0) return result\n return { ...result, heapSamples: samples.slice() }\n },\n }\n}\n","import type { Collector, InteractionSignal, RecordingResult } from '../types'\n\n/** Event Timing only surfaces events at/over this duration (ms); 40ms keeps\n * trivial interactions out while still catching anything a user would feel. */\nconst DURATION_THRESHOLD = 40\n\ninterface EventTimingEntry extends PerformanceEntry {\n processingStart: number\n processingEnd: number\n interactionId?: number\n target?: unknown\n}\n\nfunction selectorFor(target: unknown): string | undefined {\n const el = target as { tagName?: string; id?: string; className?: unknown } | null\n if (!el || typeof el.tagName !== 'string') return undefined\n let s = el.tagName.toLowerCase()\n if (el.id) s += `#${el.id}`\n else if (typeof el.className === 'string' && el.className.trim()) {\n s += `.${el.className.trim().split(/\\s+/)[0]}`\n }\n return s\n}\n\nfunction supportsEventTiming(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n // happy-dom / older browsers may not expose supportedEntryTypes; if the\n // observer exists at all we still try, and observe() throwing is caught.\n return !types || types.includes('event')\n}\n\nexport interface InteractionCollector extends Collector {\n /** Group buffered Event Timing entries into one interaction each and append\n * them to the result. Returns the input untouched when none qualified. */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records Event Timing entries during a recording and, on finalize, turns each\n * user interaction (grouped by interactionId) into one signal carrying the INP\n * latency breakdown: input delay → processing → presentation. The longest\n * event in a group defines the interaction's latency (matching how INP is\n * attributed). Emits no live signals — interactions are assembled at finalize,\n * then the self-profiling collector attributes the processing window to the\n * developer's hot functions.\n */\nexport function createInteractionCollector(): InteractionCollector {\n let active = false\n let observer: PerformanceObserver | null = null\n let entries: EventTimingEntry[] = []\n\n return {\n kind: 'interaction',\n activate() {\n if (typeof PerformanceObserver === 'undefined' || !supportsEventTiming()) return\n active = true\n entries = []\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const e of list.getEntries()) entries.push(e as EventTimingEntry)\n })\n // `event` covers all interaction events; `first-input` guarantees the\n // first one even if it's under the duration threshold.\n observer.observe({ type: 'event', buffered: false, durationThreshold: DURATION_THRESHOLD } as PerformanceObserverInit)\n try {\n observer.observe({ type: 'first-input', buffered: false } as PerformanceObserverInit)\n } catch {\n // first-input not supported everywhere; the event stream is enough.\n }\n } catch (err) {\n console.warn('[react-perfscope] interaction collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n finalize(result) {\n const byId = new Map<number, EventTimingEntry[]>()\n for (const e of entries) {\n const id = e.interactionId\n if (!id) continue // 0 / undefined → not part of a discrete interaction\n const group = byId.get(id)\n if (group) group.push(e)\n else byId.set(id, [e])\n }\n const interactions: InteractionSignal[] = []\n for (const group of byId.values()) {\n // All events of one interaction (pointerdown/up/click) report the same\n // `duration` (the whole interaction latency), so the breakdown can't\n // come from a single event. Span the processing across the group:\n // earliest processingStart → latest processingEnd (matches web-vitals).\n // The \"defining\" event for label/target is the one with the most\n // processing — typically the click/keydown that actually ran handlers.\n let duration = 0\n let startTime = Infinity\n let processingStart = Infinity\n let processingEnd = -Infinity\n let defining = group[0]!\n let maxProcessing = -Infinity\n for (const e of group) {\n if (e.duration > duration) duration = e.duration\n if (e.startTime < startTime) startTime = e.startTime\n if (e.processingStart < processingStart) processingStart = e.processingStart\n if (e.processingEnd > processingEnd) processingEnd = e.processingEnd\n const proc = e.processingEnd - e.processingStart\n if (proc > maxProcessing) {\n maxProcessing = proc\n defining = e\n }\n }\n if (duration < DURATION_THRESHOLD) continue\n const inputDelay = Math.max(0, processingStart - startTime)\n const processing = Math.max(0, processingEnd - processingStart)\n const presentation = Math.max(0, startTime + duration - processingEnd)\n interactions.push({\n kind: 'interaction',\n at: startTime,\n eventType: defining.name,\n ...(selectorFor(defining.target) ? { target: selectorFor(defining.target) } : {}),\n duration,\n inputDelay,\n processing,\n presentation,\n })\n }\n if (interactions.length === 0) return result\n interactions.sort((a, b) => a.at - b.at)\n return { ...result, signals: [...result.signals, ...interactions] }\n },\n }\n}\n","import type { Collector, FpsSample, FrameStats, RecordingResult } from '../types'\n\n/** 60fps frame budget (ms). Gaps are scored against this to count drops. */\nconst FRAME_BUDGET = 1000 / 60\n/** Window for the FPS series; 500ms smooths per-frame noise while still showing\n * a scroll-jank dip. */\nconst BUCKET_MS = 500\n/** A trailing window shorter than this is too small to estimate FPS reliably. */\nconst MIN_BUCKET_SPAN = 100\n/** Below this we can't say anything useful. */\nconst MIN_FRAMES = 8\n/** Cap retained frames so a long session can't grow the array unbounded\n * (~5.5 min at 60fps); past that, oldest drop. */\nconst MAX_FRAMES = 20_000\n\n/**\n * Turn raw requestAnimationFrame timestamps into a frame-rate picture:\n * a windowed FPS series, the lowest sustained FPS, the worst single hitch,\n * and an approximate dropped-frame count. Long tasks (>50ms) show up here as\n * big gaps, but so does sustained scroll jank (30–50ms frames) that the\n * long-task collector's threshold misses.\n *\n * Returns null when there are too few frames to analyze.\n */\nexport function analyzeFrames(frames: number[]): FrameStats | null {\n if (frames.length < MIN_FRAMES) return null\n\n let longestFrameMs = 0\n let droppedFrames = 0\n for (let i = 1; i < frames.length; i++) {\n const gap = frames[i]! - frames[i - 1]!\n if (gap > longestFrameMs) longestFrameMs = gap\n const dropped = Math.round(gap / FRAME_BUDGET) - 1\n if (dropped > 0) droppedFrames += dropped\n }\n\n const t0 = frames[0]!\n const end = frames[frames.length - 1]!\n const series: FpsSample[] = []\n let minFps = Infinity\n let idx = 0\n for (let bStart = t0; bStart < end; bStart += BUCKET_MS) {\n const bEnd = Math.min(bStart + BUCKET_MS, end)\n const span = bEnd - bStart\n let count = 0\n while (idx < frames.length && frames[idx]! < bEnd) {\n count++\n idx++\n }\n if (span < MIN_BUCKET_SPAN) break // skip a tiny trailing window\n const fps = count / (span / 1000)\n series.push({ at: bStart + span / 2, fps })\n if (fps < minFps) minFps = fps\n }\n if (series.length === 0) return null\n return { series, minFps, longestFrameMs, droppedFrames }\n}\n\nexport interface FrameCollector extends Collector {\n /** Attach the captured frame timestamps to the result. Returns the input\n * untouched when too few frames were seen (or rAF was unavailable). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records requestAnimationFrame timestamps for the duration of a recording so\n * the UI can chart frame rate and surface jank. Emits no signals — the\n * timestamps are a side track attached at finalize. No-ops when\n * requestAnimationFrame is unavailable (non-DOM environments).\n */\nexport function createFrameCollector(): FrameCollector {\n let active = false\n let rafId: number | null = null\n let frames: number[] = []\n\n function loop(t: number): void {\n if (!active) return\n frames.push(t)\n if (frames.length > MAX_FRAMES) frames.splice(0, frames.length - MAX_FRAMES)\n rafId = requestAnimationFrame(loop)\n }\n\n return {\n kind: 'frame',\n activate() {\n if (typeof requestAnimationFrame === 'undefined') return\n active = true\n frames = []\n rafId = requestAnimationFrame(loop)\n },\n deactivate() {\n active = false\n if (rafId != null && typeof cancelAnimationFrame !== 'undefined') {\n try {\n cancelAnimationFrame(rafId)\n } catch {\n // ignore\n }\n }\n rafId = null\n },\n finalize(result) {\n if (frames.length < MIN_FRAMES) return result\n return { ...result, frames: frames.slice() }\n },\n }\n}\n","import type { Collector, LongTaskAttribution, RecordingResult, Signal, StackFrame } from '../types'\n\n/**\n * JS Self-Profiling API trace shape (the subset we consume).\n * @see https://wicg.github.io/js-self-profiling/\n */\nexport interface ProfilerFrame {\n name?: string\n resourceId?: number\n line?: number\n column?: number\n}\nexport interface ProfilerStack {\n frameId: number\n parentId?: number\n}\nexport interface ProfilerSample {\n /** DOMHighResTimeStamp, same clock as performance.now() / entry.startTime. */\n timestamp: number\n stackId?: number\n}\nexport interface ProfilerTrace {\n resources: string[]\n frames: ProfilerFrame[]\n stacks: ProfilerStack[]\n samples: ProfilerSample[]\n}\n\ninterface ProfilerInstance {\n stop(): Promise<ProfilerTrace>\n}\ninterface ProfilerCtor {\n new (opts: { sampleInterval: number; maxBufferSize: number }): ProfilerInstance\n}\n\n/** Default sampling cadence. The browser may coarsen this. */\nconst SAMPLE_INTERVAL_MS = 10\nconst MAX_BUFFER_SIZE = 100_000\n/** Keep the noisiest few; deeper tails rarely help the developer. */\nconst MAX_FRAMES_PER_TASK = 5\n\n/**\n * Whether a resource URL belongs to the developer's own source (vs. a\n * dependency or tooling shim). Dependency frames are noise when the question\n * is \"which of MY functions is slow\".\n */\nexport function isUserResource(url: string | undefined): boolean {\n if (!url) return false\n if (url.includes('/node_modules/')) return false\n // Vite/dev tooling virtual modules: /@vite/client, /@react-refresh, /@id/...\n try {\n const path = new URL(url).pathname\n if (path.startsWith('/@')) return false\n } catch {\n if (url.startsWith('/@')) return false\n }\n return true\n}\n\nfunction frameToStackFrame(trace: ProfilerTrace, frame: ProfilerFrame): StackFrame {\n const file = frame.resourceId != null ? (trace.resources[frame.resourceId] ?? '') : ''\n const sf: StackFrame = {\n file,\n line: frame.line ?? 0,\n col: frame.column ?? 0,\n }\n if (frame.name) sf.fnName = frame.name\n return sf\n}\n\n/**\n * Climb a sample's stack from the leaf toward the root, returning the first\n * (deepest) frame that lives in user source. That frame is where the\n * developer's own code was actually executing when the sample was taken.\n */\nfunction leafUserFrame(trace: ProfilerTrace, stackId: number | undefined): ProfilerFrame | null {\n let id = stackId\n let guard = 0\n while (id != null && guard++ < 1000) {\n const stack = trace.stacks[id]\n if (!stack) break\n const frame = trace.frames[stack.frameId]\n if (frame && isUserResource(trace.resources[frame.resourceId ?? -1])) {\n return frame\n }\n id = stack.parentId\n }\n return null\n}\n\n/**\n * Aggregate the hottest user-source frames among samples whose timestamp\n * falls in [start, end]. `selfRatio` is relative to ALL in-window samples\n * (including vendor-only ones), so it reflects the share of the task's\n * blocking time spent in that user function.\n */\nexport function attributeWindow(\n trace: ProfilerTrace,\n start: number,\n end: number\n): LongTaskAttribution[] {\n let total = 0\n const counts = new Map<string, { frame: StackFrame; count: number }>()\n for (const sample of trace.samples) {\n if (sample.timestamp < start || sample.timestamp > end) continue\n total++\n const frame = leafUserFrame(trace, sample.stackId)\n if (!frame) continue\n const sf = frameToStackFrame(trace, frame)\n const key = `${sf.file}:${sf.line}:${sf.col}:${sf.fnName ?? ''}`\n const entry = counts.get(key)\n if (entry) entry.count++\n else counts.set(key, { frame: sf, count: 1 })\n }\n if (total === 0) return []\n return [...counts.values()]\n .sort((a, b) => b.count - a.count)\n .slice(0, MAX_FRAMES_PER_TASK)\n .map(({ frame, count }) => ({ frame, selfRatio: count / total, sampleCount: count }))\n}\n\n/**\n * Return a copy of `signals` with each long-task signal enriched with the\n * hottest user frames sampled during its window. Long tasks with no in-window\n * user samples are left without `attribution`. Non-long-task signals pass\n * through by reference.\n */\nexport function attributeLongTaskSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'long-task') return signal\n const attribution = attributeWindow(trace, signal.at, signal.at + signal.duration)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\n/**\n * Like {@link attributeLongTaskSignals} but for interactions: attributes the\n * *processing* window (handlers running, `[at+inputDelay, +processing]`) to the\n * developer's hot functions — answering \"which of my code made this click\n * slow\". Input delay and presentation aren't JS-on-the-stack, so they're\n * excluded from the window.\n */\nexport function attributeInteractionSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'interaction') return signal\n const start = signal.at + signal.inputDelay\n const attribution = attributeWindow(trace, start, start + signal.processing)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\ninterface SelfProfilingCollector extends Collector {\n /** Stop the profiler (if running), await its trace, and return a result\n * with long-task signals enriched. Falls back to the input on any failure\n * or when the Profiler API / Document-Policy header is unavailable. */\n finalize(result: RecordingResult): Promise<RecordingResult>\n}\n\n/**\n * Collector that runs the JS Self-Profiling API across a recording and, on\n * finalize, attributes each long task to the developer's own hot functions —\n * something LoAF can't do for React-delegated events (it only sees React's\n * single root dispatcher).\n *\n * It reports `kind: 'long-task'` because it enriches that signal rather than\n * emitting its own. Requires Chromium + a `Document-Policy: js-profiling`\n * response header (the dev plugins inject it); degrades to a no-op otherwise.\n */\nexport function createSelfProfilingCollector(): SelfProfilingCollector {\n let profiler: ProfilerInstance | null = null\n let tracePromise: Promise<ProfilerTrace> | null = null\n\n return {\n kind: 'long-task',\n activate() {\n tracePromise = null\n const Ctor = (globalThis as { Profiler?: ProfilerCtor }).Profiler\n if (typeof Ctor !== 'function') return\n try {\n profiler = new Ctor({ sampleInterval: SAMPLE_INTERVAL_MS, maxBufferSize: MAX_BUFFER_SIZE })\n } catch (err) {\n // Thrown when the Document-Policy: js-profiling header is absent.\n console.warn(\n '[react-perfscope] self-profiling unavailable (needs Document-Policy: js-profiling header); long tasks keep LoAF-only attribution:',\n err\n )\n profiler = null\n }\n },\n deactivate() {\n if (!profiler) return\n try {\n tracePromise = profiler.stop()\n } catch (err) {\n console.warn('[react-perfscope] self-profiling stop failed:', err)\n tracePromise = null\n }\n profiler = null\n },\n async finalize(result: RecordingResult): Promise<RecordingResult> {\n if (!tracePromise) return result\n try {\n const trace = await tracePromise\n const signals = attributeInteractionSignals(trace, attributeLongTaskSignals(trace, result.signals))\n return { ...result, signals }\n } catch (err) {\n console.warn('[react-perfscope] self-profiling finalize failed:', err)\n return result\n } finally {\n tracePromise = null\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AAM,SAAS,QAAmD;AAChE,UAAI,CAAC,aAAc,QAAO;AAC1B,UAAI;AACF,cAAM,QAAQ,MAAM;AACpB,cAAM,UAAU,4BAA4B,OAAO,yBAAyB,OAAO,OAAO,OAAO,CAAC;AAClG,eAAO,EAAE,GAAG,QAAQ,QAAQ;AAAA,MAC9B,SAAS,KAAK;AACZ,gBAAQ,KAAK,qDAAqD,GAAG;AACrE,eAAO;AAAA,MACT,UAAE;AACA,uBAAe;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;","names":["SAMPLE_INTERVAL_MS"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/recorder.ts","../src/sourcemap.ts","../src/self-requests.ts","../src/collectors/long-tasks.ts","../src/collectors/forced-reflow.ts","../src/collectors/layout-shift.ts","../src/collectors/network.ts","../src/collectors/web-vitals.ts","../src/collectors/heap.ts","../src/collectors/interaction.ts","../src/collectors/frames.ts","../src/collectors/self-profiling.ts"],"sourcesContent":["// Types\nexport * from './types'\n\n// Recorder\nexport { createRecorder } from './recorder'\n\n// Sourcemap utilities\nexport { parseStack, resolveFrame, attachLazyStack, createSourceMapResolver } from './sourcemap'\nexport type { FetchMap, SourceMapResolver, CreateSourceMapResolverOptions } from './sourcemap'\n\n// Self-request registry (excludes the tool's own traffic from network signals)\nexport { markSelfRequest, isSelfRequest } from './self-requests'\n\n// Collectors\nexport { createLongTasksCollector } from './collectors/long-tasks'\nexport { createForcedReflowCollector } from './collectors/forced-reflow'\nexport { createLayoutShiftCollector } from './collectors/layout-shift'\nexport { createNetworkCollector } from './collectors/network'\nexport { createWebVitalsCollector } from './collectors/web-vitals'\nexport { createHeapCollector, analyzeHeapTrend } from './collectors/heap'\nexport type { HeapCollector } from './collectors/heap'\nexport { createInteractionCollector } from './collectors/interaction'\nexport type { InteractionCollector } from './collectors/interaction'\nexport { createFrameCollector, analyzeFrames } from './collectors/frames'\nexport type { FrameCollector } from './collectors/frames'\nexport {\n createSelfProfilingCollector,\n attributeWindow,\n attributeLongTaskSignals,\n isUserResource,\n} from './collectors/self-profiling'\nexport type {\n ProfilerTrace,\n ProfilerFrame,\n ProfilerStack,\n ProfilerSample,\n} from './collectors/self-profiling'\n","import type { Collector, Recorder, RecordingResult, Signal } from './types'\n\nconst BUFFER_CAP = 10_000\n\nexport interface InternalRecorder extends Recorder {\n __push: (signal: Signal) => void\n}\n\nexport function createRecorder(): Recorder {\n let recording = false\n let startedAt = 0\n let buffer: Signal[] = []\n const subscribers = new Set<(s: Signal) => void>()\n const collectors: Collector[] = []\n\n function notify(signal: Signal) {\n for (const cb of subscribers) {\n try {\n cb(signal)\n } catch (err) {\n console.warn('[react-perfscope] subscriber threw:', err)\n }\n }\n }\n\n function push(signal: Signal) {\n if (!recording) return\n buffer.push(signal)\n if (buffer.length > BUFFER_CAP) {\n buffer.splice(0, buffer.length - BUFFER_CAP)\n }\n notify(signal)\n }\n\n const recorder: InternalRecorder = {\n start() {\n if (recording) return\n recording = true\n startedAt = performance.now()\n buffer = []\n for (const c of collectors) {\n try {\n c.activate(push)\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to activate:`, err)\n }\n }\n },\n stop(): RecordingResult {\n if (!recording) {\n return { signals: [], startedAt: 0, duration: 0 }\n }\n for (const c of collectors) {\n try {\n c.deactivate()\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to deactivate:`, err)\n }\n }\n const duration = performance.now() - startedAt\n const result: RecordingResult = {\n signals: buffer.slice(),\n startedAt,\n duration,\n }\n recording = false\n buffer = []\n return result\n },\n isRecording() {\n return recording\n },\n onSignal(cb) {\n subscribers.add(cb)\n return () => subscribers.delete(cb)\n },\n use(collector) {\n collectors.push(collector)\n },\n __push: push,\n }\n return recorder\n}\n","import { TraceMap, originalPositionFor, type SourceMapInput } from '@jridgewell/trace-mapping'\nimport type { StackFrame } from './types'\nimport { markSelfRequest } from './self-requests'\n\nconst CHROME_FRAME = /^\\s*at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/\nconst FIREFOX_FRAME = /^(.*?)@(.+?):(\\d+):(\\d+)$/\n\n/** A parsed source map (the JSON object), as returned by a FetchMap. */\nexport type RawSourceMap = SourceMapInput\n\nexport type FetchMap = (file: string) => Promise<RawSourceMap | null>\n\nexport async function resolveFrame(\n frame: StackFrame,\n fetchMap: FetchMap\n): Promise<StackFrame> {\n try {\n const map = await fetchMap(frame.file)\n if (!map) return frame\n // trace-mapping is pure JS (no wasm), so this works in the browser where\n // Mozilla's source-map SourceMapConsumer needs an explicitly-initialized\n // mappings.wasm. Columns are 0-based here, matching the captured frames.\n const tracer = new TraceMap(map)\n const pos = originalPositionFor(tracer, { line: frame.line, column: frame.col })\n if (pos.source == null || pos.line == null || pos.column == null) {\n return frame\n }\n const resolved: StackFrame = {\n file: pos.source,\n line: pos.line,\n col: pos.column,\n }\n if (pos.name) resolved.fnName = pos.name\n else if (frame.fnName) resolved.fnName = frame.fnName\n return resolved\n } catch (err) {\n console.warn('[react-perfscope] resolveFrame failed:', err)\n return frame\n }\n}\n\n/**\n * Attach a lazy `stack` getter to `target` that parses `raw` on first access\n * and memoizes the result. Use this from collectors to defer parseStack cost\n * until a consumer actually reads `signal.stack`.\n *\n * `skipTopFrames` drops the leading N parsed frames — useful for collectors\n * that wrap a patched function (the wrapper itself shows up as the topmost\n * frame, but it's noise from the user's perspective).\n */\nexport function attachLazyStack(\n target: object,\n raw: string | undefined,\n skipTopFrames = 0\n): void {\n let cached: StackFrame[] | null = null\n Object.defineProperty(target, 'stack', {\n enumerable: true,\n configurable: true,\n get() {\n if (cached === null) {\n const all = parseStack(raw)\n cached = skipTopFrames > 0 ? all.slice(skipTopFrames) : all\n }\n return cached\n },\n })\n}\n\nexport interface SourceMapResolver {\n /** Resolve a parsed StackFrame to its original source position. Falls back to the input frame on any failure. */\n resolve(frame: StackFrame): Promise<StackFrame>\n}\n\nexport interface CreateSourceMapResolverOptions {\n /** Override the global fetch. Useful for tests and non-browser environments. */\n fetch?: typeof globalThis.fetch\n}\n\n/**\n * Create a SourceMap resolver that fetches `.map` files from the live URL\n * referenced in each source file's `//# sourceMappingURL=` directive.\n * Caches the parsed source map per source URL so repeated resolves against\n * the same file are O(1) after the first.\n *\n * Returns the input frame on any failure (network error, missing map, etc.).\n */\nexport function createSourceMapResolver(opts: CreateSourceMapResolverOptions = {}): SourceMapResolver {\n const f = opts.fetch ?? (typeof fetch !== 'undefined' ? fetch.bind(globalThis) : null)\n const cache = new Map<string, Promise<RawSourceMap | null>>()\n\n function fetchMapFor(sourceUrl: string): Promise<RawSourceMap | null> {\n if (!f) return Promise.resolve(null)\n const existing = cache.get(sourceUrl)\n if (existing) return existing\n const promise = (async () => {\n try {\n markSelfRequest(sourceUrl)\n const res = await f(sourceUrl)\n if (!res || !res.ok) return null\n const text = await res.text()\n const m = text.match(/\\/\\/[#@]\\s*sourceMappingURL=(.+?)\\s*$/m)\n if (!m) return null\n const ref = m[1]!.trim()\n if (ref.startsWith('data:')) {\n const commaIdx = ref.indexOf(',')\n if (commaIdx === -1) return null\n const header = ref.slice(0, commaIdx)\n const payload = ref.slice(commaIdx + 1)\n const decoded = header.includes('base64')\n ? typeof atob === 'function'\n ? atob(payload)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n : (globalThis as any).Buffer.from(payload, 'base64').toString('utf8')\n : decodeURIComponent(payload)\n return JSON.parse(decoded) as RawSourceMap\n }\n const mapUrl = new URL(ref, sourceUrl).href\n markSelfRequest(mapUrl)\n const mapRes = await f(mapUrl)\n if (!mapRes || !mapRes.ok) return null\n return (await mapRes.json()) as RawSourceMap\n } catch {\n return null\n }\n })()\n cache.set(sourceUrl, promise)\n return promise\n }\n\n return {\n async resolve(frame) {\n try {\n return await resolveFrame(frame, fetchMapFor)\n } catch {\n return frame\n }\n },\n }\n}\n\nexport function parseStack(raw: string | undefined): StackFrame[] {\n if (!raw) return []\n const frames: StackFrame[] = []\n for (const line of raw.split('\\n')) {\n const chromeMatch = line.match(CHROME_FRAME)\n if (chromeMatch) {\n const [, fnName, file, lineStr, colStr] = chromeMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n continue\n }\n const firefoxMatch = line.match(FIREFOX_FRAME)\n if (firefoxMatch) {\n const [, fnName, file, lineStr, colStr] = firefoxMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n }\n }\n return frames\n}\n","// Registry of URLs that react-perfscope itself fetched (source files and their\n// source maps, when resolving stack frames). The network collector consults\n// this so the tool's own traffic never shows up as one of the app's network\n// signals — measuring shouldn't report the measurer.\n\nconst selfRequests = new Set<string>()\n\n/** Record that react-perfscope is about to fetch `url`, so the network\n * collector can exclude its resource-timing entry. */\nexport function markSelfRequest(url: string): void {\n selfRequests.add(url)\n}\n\n/** True when `url` was fetched by react-perfscope itself. */\nexport function isSelfRequest(url: string): boolean {\n return selfRequests.has(url)\n}\n","import type { Collector, LongTaskScript, Signal } from '../types'\n\nconst LOAF = 'long-animation-frame'\nconst LEGACY = 'longtask'\n\n/** A single script entry inside a Long Animation Frame. */\ninterface ScriptTiming {\n duration?: number\n invoker?: string\n invokerType?: string\n sourceURL?: string\n sourceFunctionName?: string\n sourceCharPosition?: number\n}\n\ninterface LoAFEntry extends PerformanceEntry {\n blockingDuration?: number\n scripts?: ScriptTiming[]\n}\n\nfunction supportsLoAF(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n return Array.isArray(types) && types.includes(LOAF)\n}\n\nfunction mapScripts(scripts: ScriptTiming[]): LongTaskScript[] {\n return scripts.map((s) => ({\n invokerType: s.invokerType ?? 'unknown',\n invoker: s.invoker ?? '',\n sourceURL: s.sourceURL ?? '',\n sourceFunctionName: s.sourceFunctionName ?? '',\n charPosition: typeof s.sourceCharPosition === 'number' ? s.sourceCharPosition : -1,\n duration: typeof s.duration === 'number' ? s.duration : 0,\n }))\n}\n\nexport function createLongTasksCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'long-task',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; long-tasks disabled')\n return\n }\n active = true\n const useLoAF = supportsLoAF()\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const entry of list.getEntries()) {\n if (useLoAF) {\n const loaf = entry as LoAFEntry\n const scripts = Array.isArray(loaf.scripts) ? mapScripts(loaf.scripts) : []\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n scripts,\n ...(typeof loaf.blockingDuration === 'number'\n ? { blockingDuration: loaf.blockingDuration }\n : {}),\n })\n } else {\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n })\n }\n }\n })\n observer.observe({ type: useLoAF ? LOAF : LEGACY, buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] long-tasks collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\nimport { attachLazyStack } from '../sourcemap'\n\nconst LAYOUT_GETTERS = [\n 'offsetWidth',\n 'offsetHeight',\n 'offsetLeft',\n 'offsetTop',\n 'clientWidth',\n 'clientHeight',\n 'scrollWidth',\n 'scrollHeight',\n] as const\n\nconst LAYOUT_METHODS = ['getBoundingClientRect', 'getClientRects'] as const\n\ntype SavedDescriptor = {\n proto: object\n key: string\n descriptor: PropertyDescriptor\n}\n\ntype OpenGroup = {\n at: number\n duration: number\n count: number\n rawStack: string | undefined\n}\n\n// Close the coalescing window at the end of the current synchronous turn.\n// queueMicrotask runs after the running task drains, so a layout-thrash loop\n// (read offsetWidth N times in one turn) collapses into a single group.\nconst scheduleFlush: (cb: () => void) => void =\n typeof queueMicrotask === 'function'\n ? queueMicrotask\n : typeof Promise !== 'undefined'\n ? (cb) => {\n Promise.resolve().then(cb)\n }\n : (cb) => cb()\n\nexport function createForcedReflowCollector(): Collector {\n let active = false\n let emit: (s: Signal) => void = () => {}\n const saved: SavedDescriptor[] = []\n let mutationObserver: MutationObserver | null = null\n let group: OpenGroup | null = null\n\n function consumePendingMutations(): boolean {\n if (!mutationObserver) {\n // Fallback when MutationObserver isn't available: always treat as dirty\n // (Phase 1 over-report behavior).\n return true\n }\n return mutationObserver.takeRecords().length > 0\n }\n\n function flush() {\n if (!group) return\n const g = group\n group = null\n const signal = {\n kind: 'forced-reflow' as const,\n at: g.at,\n duration: g.duration,\n count: g.count,\n } as unknown as Signal\n attachLazyStack(signal, g.rawStack, 1)\n emit(signal)\n }\n\n // A layout read happened while recording and layout was dirty. Open a group\n // on the first such read of the turn, then just accumulate count/duration for\n // the rest of the turn. `rawStack` is captured by the caller (the patched\n // accessor) so the stack's top user frame stays at a fixed depth — passing it\n // through a helper would add a frame and misattribute the reflow to this file.\n function record(at: number, duration: number, rawStack: string | undefined) {\n if (group) {\n group.count++\n group.duration += duration\n return\n }\n group = { at, duration, count: 1, rawStack }\n scheduleFlush(flush)\n }\n\n // True when the next dirty read opens a fresh group and so needs a stack.\n // Lets the accessor skip `new Error().stack` (the dominant cost) on the\n // subsequent reads it coalesces into an already-open group.\n function needsStack(): boolean {\n return group === null\n }\n\n function patchGetter(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || !desc.get) return\n saved.push({ proto, key, descriptor: desc })\n const originalGet = desc.get\n Object.defineProperty(proto, key, {\n configurable: true,\n get(this: unknown) {\n if (active) {\n if (!consumePendingMutations()) {\n return originalGet.call(this)\n }\n const rawStack = needsStack() ? new Error().stack : undefined\n const at = performance.now()\n const value = originalGet.call(this)\n record(at, performance.now() - at, rawStack)\n return value\n }\n return originalGet.call(this)\n },\n set: desc.set,\n })\n }\n\n function patchMethod(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || typeof desc.value !== 'function') return\n saved.push({ proto, key, descriptor: desc })\n const original = desc.value as (...args: unknown[]) => unknown\n Object.defineProperty(proto, key, {\n configurable: true,\n writable: true,\n value: function patchedLayoutMethod(this: unknown, ...args: unknown[]) {\n if (active) {\n if (!consumePendingMutations()) {\n return original.apply(this, args)\n }\n const rawStack = needsStack() ? new Error().stack : undefined\n const at = performance.now()\n const value = original.apply(this, args)\n record(at, performance.now() - at, rawStack)\n return value\n }\n return original.apply(this, args)\n },\n })\n }\n\n return {\n kind: 'forced-reflow',\n activate(emitFn) {\n if (active) return\n emit = emitFn\n active = true\n\n if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {\n try {\n mutationObserver = new MutationObserver(() => {})\n mutationObserver.observe(document, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: true,\n })\n } catch (err) {\n console.warn('[react-perfscope] forced-reflow MutationObserver failed:', err)\n mutationObserver = null\n }\n }\n\n if (typeof HTMLElement !== 'undefined') {\n for (const key of LAYOUT_GETTERS) {\n patchGetter(HTMLElement.prototype, key)\n }\n }\n if (typeof Element !== 'undefined') {\n for (const key of LAYOUT_METHODS) {\n patchMethod(Element.prototype, key)\n }\n }\n },\n deactivate() {\n if (!active) return\n active = false\n // Emit any group still open before the scheduled microtask runs, so the\n // last burst isn't lost when stop() is called mid-turn.\n flush()\n if (mutationObserver) {\n try {\n mutationObserver.disconnect()\n } catch {\n // ignore\n }\n mutationObserver = null\n }\n for (const { proto, key, descriptor } of saved) {\n Object.defineProperty(proto, key, descriptor)\n }\n saved.length = 0\n },\n }\n}\n","import type { Collector, Signal } from '../types'\n\ninterface LayoutShiftSource {\n currentRect: DOMRect\n previousRect?: DOMRect\n node?: Node | null\n}\n\ninterface LayoutShiftEntryLike extends PerformanceEntry {\n value: number\n hadRecentInput: boolean\n sources?: LayoutShiftSource[]\n}\n\nconst PERFSCOPE_HOST_ATTR = 'data-perfscope-host'\n\nfunction rectsOverlap(a: DOMRect, b: DOMRect, tolerance = 0): boolean {\n return !(\n a.x + a.width < b.x - tolerance ||\n b.x + b.width < a.x - tolerance ||\n a.y + a.height < b.y - tolerance ||\n b.y + b.height < a.y - tolerance\n )\n}\n\n/**\n * Returns true when every source in the entry is part of our floating\n * widget. We want to ignore shifts caused by the perfscope UI itself.\n *\n * Detection has two paths:\n * 1. Node-based: walk up `source.node` looking for `[data-perfscope-host]`.\n * Works when the node is in light DOM.\n * 2. Rect-based fallback: compare `source.currentRect` against every host\n * element's bounding rect. This catches the Shadow-DOM case where the\n * browser doesn't expose the inner node (Shadow root boundary).\n */\nfunction collectPerfscopeRects(): DOMRect[] {\n const hosts = Array.from(document.querySelectorAll(`[${PERFSCOPE_HOST_ATTR}]`))\n const rects: DOMRect[] = []\n for (const h of hosts) {\n // The light-DOM host element usually has height 0 because Shadow DOM\n // content isn't part of its layout. We need to peek inside the shadow\n // root and collect bounds of any positioned children.\n const sr = (h as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot\n if (sr) {\n for (const child of Array.from(sr.children)) {\n const r = (child as Element).getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n } else {\n const r = h.getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n }\n return rects\n}\n\nfunction entryIsOnlyFromPerfscope(sources: LayoutShiftSource[]): boolean {\n if (sources.length === 0) return false\n if (typeof document === 'undefined') return false\n\n const hostRects = collectPerfscopeRects()\n if (hostRects.length === 0) return false\n\n for (const src of sources) {\n let matched = false\n const node = src.node as (Node & { closest?: (sel: string) => Element | null }) | null | undefined\n if (node) {\n // Node-based check\n if (typeof (node as { closest?: unknown }).closest === 'function') {\n if ((node as Element).closest(`[${PERFSCOPE_HOST_ATTR}]`)) matched = true\n } else {\n let parent: (Element | null) = (node as Node).parentElement as Element | null\n while (parent) {\n if (parent.hasAttribute(PERFSCOPE_HOST_ATTR)) { matched = true; break }\n parent = parent.parentElement\n }\n }\n }\n // Rect-based fallback (shadow DOM): if source rect overlaps any of our\n // host rects, consider it our widget. Tolerance covers the case where\n // the widget changes size during the shift (its previous/current bounds\n // differ but both sit in the same screen corner).\n if (!matched) {\n for (const hostRect of hostRects) {\n if (rectsOverlap(src.currentRect, hostRect, 24)) {\n matched = true\n break\n }\n }\n }\n if (!matched) return false\n }\n return true\n}\n\nexport function createLayoutShiftCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'layout-shift',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; layout-shift disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as LayoutShiftEntryLike\n // Note: production CLS metrics exclude shifts with hadRecentInput\n // (user-initiated movements are considered intentional). For a\n // dev tool, the user explicitly WANTS to see what their clicks\n // caused — so we report these too.\n const sources = entry.sources ?? []\n if (entryIsOnlyFromPerfscope(sources)) continue\n // Convert viewport-relative rects to document-relative coords so\n // overlays stay anchored to the shifted DOM position when the\n // user scrolls. Filter above runs first on viewport coords (our\n // widget is position:fixed, lives in viewport space).\n const sx = (typeof window !== 'undefined' && window.scrollX) || 0\n const sy = (typeof window !== 'undefined' && window.scrollY) || 0\n const toDocRect = (r: DOMRect) =>\n new DOMRect(r.x + sx, r.y + sy, r.width, r.height)\n const rects = sources.map((s) => toDocRect(s.currentRect))\n // previousRect is undefined when the element was newly inserted.\n // An \"empty\" rect (w=0, h=0) likewise means there was no prior\n // box — treat both as `null` so the overlay can decide not to\n // draw an arrow for these.\n const prevRects: (DOMRect | null)[] = sources.map((s) => {\n const pr = s.previousRect\n if (!pr) return null\n if (pr.width === 0 && pr.height === 0) return null\n return toDocRect(pr)\n })\n emit({\n kind: 'layout-shift',\n at: entry.startTime,\n value: entry.value,\n sources: rects,\n previousSources: prevRects,\n })\n }\n })\n observer.observe({ type: 'layout-shift', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] layout-shift collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\nimport { isSelfRequest } from '../self-requests'\n\ninterface ResourceTimingLike extends PerformanceEntry {\n transferSize?: number\n renderBlockingStatus?: 'blocking' | 'non-blocking'\n}\n\nexport function createNetworkCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'network',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; network disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as ResourceTimingLike\n // Skip react-perfscope's own traffic (source-map fetches).\n if (isSelfRequest(entry.name)) continue\n emit({\n kind: 'network',\n url: entry.name,\n startedAt: entry.startTime,\n duration: entry.duration,\n size: entry.transferSize ?? 0,\n blocking: entry.renderBlockingStatus === 'blocking',\n })\n }\n })\n observer.observe({ type: 'resource', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] network collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import { onLCP, onINP, onCLS, onFCP, onTTFB, type Metric } from 'web-vitals'\nimport type { Collector, Signal, WebVitalSignal } from '../types'\n\ntype VitalName = WebVitalSignal['name']\n\nexport function createWebVitalsCollector(): Collector {\n let active = false\n let subscribed = false\n let emit: (signal: Signal) => void = () => {}\n\n function makeHandler(name: VitalName) {\n return (metric: Metric) => {\n if (!active) return\n emit({ kind: 'web-vital', name, value: metric.value })\n }\n }\n\n return {\n kind: 'web-vital',\n activate(emitFn) {\n emit = emitFn\n active = true\n if (subscribed) return\n try {\n onLCP(makeHandler('LCP'))\n onINP(makeHandler('INP'))\n onCLS(makeHandler('CLS'))\n onFCP(makeHandler('FCP'))\n onTTFB(makeHandler('TTFB'))\n subscribed = true\n } catch (err) {\n console.warn('[react-perfscope] web-vitals collector failed to subscribe:', err)\n active = false\n }\n },\n deactivate() {\n // The web-vitals library does not expose unsubscribe. We keep the\n // handlers attached and gate emission via `active`. Re-activating\n // updates `emit` without re-subscribing.\n active = false\n },\n }\n}\n","import type {\n Collector,\n HeapSample,\n HeapTrend,\n HeapTrendClass,\n RecordingResult,\n} from '../types'\n\n/** How often to read heap usage while recording. Reading performance.memory\n * is cheap, so we sample at 4Hz: a 1s cadence is too coarse — short spikes fall\n * between samples and the line, drawn straight between sparse points, smooths\n * them into a ramp. 250ms localizes spikes without meaningful overhead. */\nconst SAMPLE_INTERVAL_MS = 250\n/** Cap on retained samples so a multi-hour session can't grow the array\n * unbounded. At 250ms this is ~83 min; past that, oldest samples drop. */\nconst MAX_SAMPLES = 20_000\n\n/** Below this, a trend can't be estimated reliably. */\nconst MIN_SAMPLES = 4\n/** How many contiguous segments to split the series into when estimating the\n * floor. Each segment contributes its minimum (the post-GC trough). */\nconst FLOOR_SEGMENTS = 8\n\nconst MB = 1024 * 1024\n/** Floor-growth thresholds, in bytes per minute. */\nconst GROWING_SLOPE = 1 * MB\nconst LEAK_SLOPE = 5 * MB\n/** A rate alone isn't enough: over a short recording, a sub-megabyte wobble in\n * the floor extrapolates to a huge MB/min and would false-positive. Require the\n * floor to have actually risen by at least this much across the window before\n * calling anything growing/leaking. */\nconst MIN_NET_GROWTH = 2 * MB\n\ninterface MemoryInfo {\n usedJSHeapSize: number\n totalJSHeapSize: number\n jsHeapSizeLimit: number\n}\n\nfunction readMemory(): MemoryInfo | null {\n const perf = (globalThis as { performance?: { memory?: MemoryInfo } }).performance\n const mem = perf?.memory\n if (!mem || typeof mem.usedJSHeapSize !== 'number') return null\n return mem\n}\n\n/**\n * Least-squares slope of points (x, y). Returns 0 when x has no spread\n * (vertical / single distinct x) to avoid a divide-by-zero blow-up.\n */\nfunction slope(points: { x: number; y: number }[]): number {\n const n = points.length\n if (n < 2) return 0\n let sx = 0\n let sy = 0\n let sxy = 0\n let sxx = 0\n for (const { x, y } of points) {\n sx += x\n sy += y\n sxy += x * y\n sxx += x * x\n }\n const denom = n * sxx - sx * sx\n if (denom === 0) return 0\n return (n * sxy - sx * sy) / denom\n}\n\n/**\n * Estimate whether memory is being retained across the recording.\n *\n * GC makes raw heap usage a sawtooth, so the peak is noisy. The reliable\n * signal is the *floor* — the post-GC troughs. We split the series into\n * contiguous segments, take the minimum of each (its trough), and regress\n * those minima against time.\n *\n * A rising overall slope is necessary but NOT sufficient: a one-time step\n * (heap warms up early, then plateaus) also regresses to a positive slope, and\n * flagging that as a leak is a false positive — the classic \"idle recording\n * reads abnormal\" bug. A real leak keeps climbing, so we additionally require\n * the *recent* half of the floor to still be rising. We also gate on a minimum\n * net growth, since over a short window a sub-MB wobble extrapolates to a steep\n * per-minute slope.\n *\n * Returns null when there are too few samples to say anything.\n */\nexport function analyzeHeapTrend(samples: HeapSample[]): HeapTrend | null {\n if (samples.length < MIN_SAMPLES) return null\n const t0 = samples[0]!.at\n const segSize = Math.max(1, Math.ceil(samples.length / FLOOR_SEGMENTS))\n const floorPoints: { x: number; y: number }[] = []\n for (let i = 0; i < samples.length; i += segSize) {\n const seg = samples.slice(i, i + segSize)\n let min = Infinity\n for (const s of seg) min = Math.min(min, s.used)\n const mid = seg[Math.floor(seg.length / 2)]!\n floorPoints.push({ x: (mid.at - t0) / 60000, y: min })\n }\n const slopeBytesPerMin = slope(floorPoints)\n const spanMin = (samples[samples.length - 1]!.at - t0) / 60000\n const projectedGrowth = slopeBytesPerMin * spanMin\n // Recent trend: is the floor still climbing in the latter half? Distinguishes\n // a sustained leak from a one-time step that has since plateaued.\n const recent = floorPoints.slice(Math.floor(floorPoints.length / 2))\n const recentSlope = recent.length >= 2 ? slope(recent) : slopeBytesPerMin\n\n let classification: HeapTrendClass = 'stable'\n const sustained = projectedGrowth >= MIN_NET_GROWTH && recentSlope >= GROWING_SLOPE\n if (sustained) {\n classification =\n slopeBytesPerMin >= LEAK_SLOPE && recentSlope >= LEAK_SLOPE ? 'leak-suspected' : 'growing'\n }\n return { classification, slopeBytesPerMin }\n}\n\nexport interface HeapCollector extends Collector {\n /** Attach the sampled heap series to the recording result. Returns the\n * input untouched when nothing was sampled (unsupported browser). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Samples `performance.memory` on an interval for the duration of a recording\n * and attaches the series via `finalize`. It is a Collector so the recorder\n * drives its start/stop, but it emits no signals — the series is a separate\n * track (see RecordingResult.heapSamples), so a busy session's signal buffer\n * can't evict it. No-ops entirely when performance.memory is unavailable\n * (non-Chromium), leaving `heapSamples` absent so the UI can show a fallback.\n */\nexport function createHeapCollector(): HeapCollector {\n let samples: HeapSample[] = []\n let timer: ReturnType<typeof setInterval> | null = null\n\n function sample(): void {\n const mem = readMemory()\n if (!mem) return\n samples.push({ at: performance.now(), used: mem.usedJSHeapSize, total: mem.totalJSHeapSize })\n if (samples.length > MAX_SAMPLES) samples.splice(0, samples.length - MAX_SAMPLES)\n }\n\n return {\n kind: 'heap',\n activate() {\n samples = []\n if (!readMemory()) return // unsupported → never start the timer\n sample()\n timer = setInterval(sample, SAMPLE_INTERVAL_MS)\n },\n deactivate() {\n if (timer == null) return\n clearInterval(timer)\n timer = null\n sample() // one final reading at stop\n },\n finalize(result) {\n if (samples.length === 0) return result\n return { ...result, heapSamples: samples.slice() }\n },\n }\n}\n","import type { Collector, InteractionSignal, RecordingResult } from '../types'\n\n/** Event Timing only surfaces events at/over this duration (ms); 40ms keeps\n * trivial interactions out while still catching anything a user would feel. */\nconst DURATION_THRESHOLD = 40\n\ninterface EventTimingEntry extends PerformanceEntry {\n processingStart: number\n processingEnd: number\n interactionId?: number\n target?: unknown\n}\n\nfunction selectorFor(target: unknown): string | undefined {\n const el = target as { tagName?: string; id?: string; className?: unknown } | null\n if (!el || typeof el.tagName !== 'string') return undefined\n let s = el.tagName.toLowerCase()\n if (el.id) s += `#${el.id}`\n else if (typeof el.className === 'string' && el.className.trim()) {\n s += `.${el.className.trim().split(/\\s+/)[0]}`\n }\n return s\n}\n\nfunction supportsEventTiming(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n // happy-dom / older browsers may not expose supportedEntryTypes; if the\n // observer exists at all we still try, and observe() throwing is caught.\n return !types || types.includes('event')\n}\n\nexport interface InteractionCollector extends Collector {\n /** Group buffered Event Timing entries into one interaction each and append\n * them to the result. Returns the input untouched when none qualified. */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records Event Timing entries during a recording and, on finalize, turns each\n * user interaction (grouped by interactionId) into one signal carrying the INP\n * latency breakdown: input delay → processing → presentation. The longest\n * event in a group defines the interaction's latency (matching how INP is\n * attributed). Emits no live signals — interactions are assembled at finalize,\n * then the self-profiling collector attributes the processing window to the\n * developer's hot functions.\n */\nexport function createInteractionCollector(): InteractionCollector {\n let active = false\n let observer: PerformanceObserver | null = null\n let entries: EventTimingEntry[] = []\n\n return {\n kind: 'interaction',\n activate() {\n if (typeof PerformanceObserver === 'undefined' || !supportsEventTiming()) return\n active = true\n entries = []\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const e of list.getEntries()) entries.push(e as EventTimingEntry)\n })\n // `event` covers all interaction events; `first-input` guarantees the\n // first one even if it's under the duration threshold.\n observer.observe({ type: 'event', buffered: false, durationThreshold: DURATION_THRESHOLD } as PerformanceObserverInit)\n try {\n observer.observe({ type: 'first-input', buffered: false } as PerformanceObserverInit)\n } catch {\n // first-input not supported everywhere; the event stream is enough.\n }\n } catch (err) {\n console.warn('[react-perfscope] interaction collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n finalize(result) {\n const byId = new Map<number, EventTimingEntry[]>()\n for (const e of entries) {\n const id = e.interactionId\n if (!id) continue // 0 / undefined → not part of a discrete interaction\n const group = byId.get(id)\n if (group) group.push(e)\n else byId.set(id, [e])\n }\n const interactions: InteractionSignal[] = []\n for (const group of byId.values()) {\n // All events of one interaction (pointerdown/up/click) report the same\n // `duration` (the whole interaction latency), so the breakdown can't\n // come from a single event. Span the processing across the group:\n // earliest processingStart → latest processingEnd (matches web-vitals).\n // The \"defining\" event for label/target is the one with the most\n // processing — typically the click/keydown that actually ran handlers.\n let duration = 0\n let startTime = Infinity\n let processingStart = Infinity\n let processingEnd = -Infinity\n let defining = group[0]!\n let maxProcessing = -Infinity\n for (const e of group) {\n if (e.duration > duration) duration = e.duration\n if (e.startTime < startTime) startTime = e.startTime\n if (e.processingStart < processingStart) processingStart = e.processingStart\n if (e.processingEnd > processingEnd) processingEnd = e.processingEnd\n const proc = e.processingEnd - e.processingStart\n if (proc > maxProcessing) {\n maxProcessing = proc\n defining = e\n }\n }\n if (duration < DURATION_THRESHOLD) continue\n const inputDelay = Math.max(0, processingStart - startTime)\n const processing = Math.max(0, processingEnd - processingStart)\n const presentation = Math.max(0, startTime + duration - processingEnd)\n interactions.push({\n kind: 'interaction',\n at: startTime,\n eventType: defining.name,\n ...(selectorFor(defining.target) ? { target: selectorFor(defining.target) } : {}),\n duration,\n inputDelay,\n processing,\n presentation,\n })\n }\n if (interactions.length === 0) return result\n interactions.sort((a, b) => a.at - b.at)\n return { ...result, signals: [...result.signals, ...interactions] }\n },\n }\n}\n","import type { Collector, FpsSample, FrameStats, RecordingResult } from '../types'\n\n/** 60fps frame budget (ms). Gaps are scored against this to count drops. */\nconst FRAME_BUDGET = 1000 / 60\n/** Window for the FPS series; 500ms smooths per-frame noise while still showing\n * a scroll-jank dip. */\nconst BUCKET_MS = 500\n/** A trailing window shorter than this is too small to estimate FPS reliably. */\nconst MIN_BUCKET_SPAN = 100\n/** Below this we can't say anything useful. */\nconst MIN_FRAMES = 8\n/** Cap retained frames so a long session can't grow the array unbounded\n * (~5.5 min at 60fps); past that, oldest drop. */\nconst MAX_FRAMES = 20_000\n\n/**\n * Turn raw requestAnimationFrame timestamps into a frame-rate picture:\n * a windowed FPS series, the lowest sustained FPS, the worst single hitch,\n * and an approximate dropped-frame count. Long tasks (>50ms) show up here as\n * big gaps, but so does sustained scroll jank (30–50ms frames) that the\n * long-task collector's threshold misses.\n *\n * Returns null when there are too few frames to analyze.\n */\nexport function analyzeFrames(frames: number[]): FrameStats | null {\n if (frames.length < MIN_FRAMES) return null\n\n let longestFrameMs = 0\n let droppedFrames = 0\n for (let i = 1; i < frames.length; i++) {\n const gap = frames[i]! - frames[i - 1]!\n if (gap > longestFrameMs) longestFrameMs = gap\n const dropped = Math.round(gap / FRAME_BUDGET) - 1\n if (dropped > 0) droppedFrames += dropped\n }\n\n const t0 = frames[0]!\n const end = frames[frames.length - 1]!\n const series: FpsSample[] = []\n let minFps = Infinity\n let idx = 0\n for (let bStart = t0; bStart < end; bStart += BUCKET_MS) {\n const bEnd = Math.min(bStart + BUCKET_MS, end)\n const span = bEnd - bStart\n let count = 0\n while (idx < frames.length && frames[idx]! < bEnd) {\n count++\n idx++\n }\n if (span < MIN_BUCKET_SPAN) break // skip a tiny trailing window\n const fps = count / (span / 1000)\n series.push({ at: bStart + span / 2, fps })\n if (fps < minFps) minFps = fps\n }\n if (series.length === 0) return null\n return { series, minFps, longestFrameMs, droppedFrames }\n}\n\nexport interface FrameCollector extends Collector {\n /** Attach the captured frame timestamps to the result. Returns the input\n * untouched when too few frames were seen (or rAF was unavailable). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records requestAnimationFrame timestamps for the duration of a recording so\n * the UI can chart frame rate and surface jank. Emits no signals — the\n * timestamps are a side track attached at finalize. No-ops when\n * requestAnimationFrame is unavailable (non-DOM environments).\n */\nexport function createFrameCollector(): FrameCollector {\n let active = false\n let rafId: number | null = null\n let frames: number[] = []\n\n function loop(t: number): void {\n if (!active) return\n frames.push(t)\n if (frames.length > MAX_FRAMES) frames.splice(0, frames.length - MAX_FRAMES)\n rafId = requestAnimationFrame(loop)\n }\n\n return {\n kind: 'frame',\n activate() {\n if (typeof requestAnimationFrame === 'undefined') return\n active = true\n frames = []\n rafId = requestAnimationFrame(loop)\n },\n deactivate() {\n active = false\n if (rafId != null && typeof cancelAnimationFrame !== 'undefined') {\n try {\n cancelAnimationFrame(rafId)\n } catch {\n // ignore\n }\n }\n rafId = null\n },\n finalize(result) {\n if (frames.length < MIN_FRAMES) return result\n return { ...result, frames: frames.slice() }\n },\n }\n}\n","import type { Collector, LongTaskAttribution, RecordingResult, Signal, StackFrame } from '../types'\n\n/**\n * JS Self-Profiling API trace shape (the subset we consume).\n * @see https://wicg.github.io/js-self-profiling/\n */\nexport interface ProfilerFrame {\n name?: string\n resourceId?: number\n line?: number\n column?: number\n}\nexport interface ProfilerStack {\n frameId: number\n parentId?: number\n}\nexport interface ProfilerSample {\n /** DOMHighResTimeStamp, same clock as performance.now() / entry.startTime. */\n timestamp: number\n stackId?: number\n}\nexport interface ProfilerTrace {\n resources: string[]\n frames: ProfilerFrame[]\n stacks: ProfilerStack[]\n samples: ProfilerSample[]\n}\n\ninterface ProfilerInstance {\n stop(): Promise<ProfilerTrace>\n}\ninterface ProfilerCtor {\n new (opts: { sampleInterval: number; maxBufferSize: number }): ProfilerInstance\n}\n\n/** Default sampling cadence. The browser may coarsen this. */\nconst SAMPLE_INTERVAL_MS = 10\nconst MAX_BUFFER_SIZE = 100_000\n/** Keep the noisiest few; deeper tails rarely help the developer. */\nconst MAX_FRAMES_PER_TASK = 5\n\n/**\n * Whether a resource URL belongs to the developer's own source (vs. a\n * dependency or tooling shim). Dependency frames are noise when the question\n * is \"which of MY functions is slow\".\n */\nexport function isUserResource(url: string | undefined): boolean {\n if (!url) return false\n if (url.includes('/node_modules/')) return false\n // Vite/dev tooling virtual modules: /@vite/client, /@react-refresh, /@id/...\n try {\n const path = new URL(url).pathname\n if (path.startsWith('/@')) return false\n } catch {\n if (url.startsWith('/@')) return false\n }\n return true\n}\n\nfunction frameToStackFrame(trace: ProfilerTrace, frame: ProfilerFrame): StackFrame {\n const file = frame.resourceId != null ? (trace.resources[frame.resourceId] ?? '') : ''\n const sf: StackFrame = {\n file,\n line: frame.line ?? 0,\n col: frame.column ?? 0,\n }\n if (frame.name) sf.fnName = frame.name\n return sf\n}\n\n/**\n * Climb a sample's stack from the leaf toward the root, returning the first\n * (deepest) frame that lives in user source. That frame is where the\n * developer's own code was actually executing when the sample was taken.\n */\nfunction leafUserFrame(trace: ProfilerTrace, stackId: number | undefined): ProfilerFrame | null {\n let id = stackId\n let guard = 0\n while (id != null && guard++ < 1000) {\n const stack = trace.stacks[id]\n if (!stack) break\n const frame = trace.frames[stack.frameId]\n if (frame && isUserResource(trace.resources[frame.resourceId ?? -1])) {\n return frame\n }\n id = stack.parentId\n }\n return null\n}\n\n/**\n * Aggregate the hottest user-source frames among samples whose timestamp\n * falls in [start, end]. `selfRatio` is relative to ALL in-window samples\n * (including vendor-only ones), so it reflects the share of the task's\n * blocking time spent in that user function.\n */\nexport function attributeWindow(\n trace: ProfilerTrace,\n start: number,\n end: number\n): LongTaskAttribution[] {\n let total = 0\n const counts = new Map<string, { frame: StackFrame; count: number }>()\n for (const sample of trace.samples) {\n if (sample.timestamp < start || sample.timestamp > end) continue\n total++\n const frame = leafUserFrame(trace, sample.stackId)\n if (!frame) continue\n const sf = frameToStackFrame(trace, frame)\n const key = `${sf.file}:${sf.line}:${sf.col}:${sf.fnName ?? ''}`\n const entry = counts.get(key)\n if (entry) entry.count++\n else counts.set(key, { frame: sf, count: 1 })\n }\n if (total === 0) return []\n return [...counts.values()]\n .sort((a, b) => b.count - a.count)\n .slice(0, MAX_FRAMES_PER_TASK)\n .map(({ frame, count }) => ({ frame, selfRatio: count / total, sampleCount: count }))\n}\n\n/**\n * Return a copy of `signals` with each long-task signal enriched with the\n * hottest user frames sampled during its window. Long tasks with no in-window\n * user samples are left without `attribution`. Non-long-task signals pass\n * through by reference.\n */\nexport function attributeLongTaskSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'long-task') return signal\n const attribution = attributeWindow(trace, signal.at, signal.at + signal.duration)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\n/**\n * Like {@link attributeLongTaskSignals} but for interactions: attributes the\n * *processing* window (handlers running, `[at+inputDelay, +processing]`) to the\n * developer's hot functions — answering \"which of my code made this click\n * slow\". Input delay and presentation aren't JS-on-the-stack, so they're\n * excluded from the window.\n */\nexport function attributeInteractionSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'interaction') return signal\n const start = signal.at + signal.inputDelay\n const attribution = attributeWindow(trace, start, start + signal.processing)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\ninterface SelfProfilingCollector extends Collector {\n /** Stop the profiler (if running), await its trace, and return a result\n * with long-task signals enriched. Falls back to the input on any failure\n * or when the Profiler API / Document-Policy header is unavailable. */\n finalize(result: RecordingResult): Promise<RecordingResult>\n}\n\n/**\n * Collector that runs the JS Self-Profiling API across a recording and, on\n * finalize, attributes each long task to the developer's own hot functions —\n * something LoAF can't do for React-delegated events (it only sees React's\n * single root dispatcher).\n *\n * It reports `kind: 'long-task'` because it enriches that signal rather than\n * emitting its own. Requires Chromium + a `Document-Policy: js-profiling`\n * response header (the dev plugins inject it); degrades to a no-op otherwise.\n */\nexport function createSelfProfilingCollector(): SelfProfilingCollector {\n let profiler: ProfilerInstance | null = null\n let tracePromise: Promise<ProfilerTrace> | null = null\n\n return {\n kind: 'long-task',\n activate() {\n tracePromise = null\n const Ctor = (globalThis as { Profiler?: ProfilerCtor }).Profiler\n if (typeof Ctor !== 'function') return\n try {\n profiler = new Ctor({ sampleInterval: SAMPLE_INTERVAL_MS, maxBufferSize: MAX_BUFFER_SIZE })\n } catch (err) {\n // Thrown when the Document-Policy: js-profiling header is absent.\n console.warn(\n '[react-perfscope] self-profiling unavailable (needs Document-Policy: js-profiling header); long tasks keep LoAF-only attribution:',\n err\n )\n profiler = null\n }\n },\n deactivate() {\n if (!profiler) return\n try {\n tracePromise = profiler.stop()\n } catch (err) {\n console.warn('[react-perfscope] self-profiling stop failed:', err)\n tracePromise = null\n }\n profiler = null\n },\n async finalize(result: RecordingResult): Promise<RecordingResult> {\n if (!tracePromise) return result\n try {\n const trace = await tracePromise\n const signals = attributeInteractionSignals(trace, attributeLongTaskSignals(trace, result.signals))\n return { ...result, signals }\n } catch (err) {\n console.warn('[react-perfscope] self-profiling finalize failed:', err)\n return result\n } finally {\n tracePromise = null\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,IAAM,aAAa;AAMZ,SAAS,iBAA2B;AACzC,MAAI,YAAY;AAChB,MAAI,YAAY;AAChB,MAAI,SAAmB,CAAC;AACxB,QAAM,cAAc,oBAAI,IAAyB;AACjD,QAAM,aAA0B,CAAC;AAEjC,WAAS,OAAO,QAAgB;AAC9B,eAAW,MAAM,aAAa;AAC5B,UAAI;AACF,WAAG,MAAM;AAAA,MACX,SAAS,KAAK;AACZ,gBAAQ,KAAK,uCAAuC,GAAG;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AAEA,WAAS,KAAK,QAAgB;AAC5B,QAAI,CAAC,UAAW;AAChB,WAAO,KAAK,MAAM;AAClB,QAAI,OAAO,SAAS,YAAY;AAC9B,aAAO,OAAO,GAAG,OAAO,SAAS,U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Aa;AACX,UAAI,CAAC,SAAU;AACf,UAAI;AACF,uBAAe,SAAS,KAAK;AAAA,MAC/B,SAAS,KAAK;AACZ,gBAAQ,KAAK,iDAAiD,GAAG;AACjE,uBAAe;AAAA,MACjB;AACA,iBAAW;AAAA,IACb;AAAA,IACA,MAAM,SAAS,QAAmD;AAChE,UAAI,CAAC,aAAc,QAAO;AAC1B,UAAI;AACF,cAAM,QAAQ,MAAM;AACpB,cAAM,UAAU,4BAA4B,OAAO,yBAAyB,OAAO,OAAO,OAAO,CAAC;AAClG,eAAO,EAAE,GAAG,QAAQ,QAAQ;AAAA,MAC9B,SAAS,KAAK;AACZ,gBAAQ,KAAK,qDAAqD,GAAG;AACrE,eAAO;AAAA,MACT,UAAE;AACA,uBAAe;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;","names":["SAMPLE_INTERVAL_MS"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -11,9 +11,16 @@ type StackFrame = {
|
|
|
11
11
|
};
|
|
12
12
|
type ForcedReflowSignal = {
|
|
13
13
|
kind: 'forced-reflow';
|
|
14
|
+
/** Time of the first layout read in the coalesced group. */
|
|
14
15
|
at: number;
|
|
16
|
+
/** Sum of the measured layout-flush durations across the group, in ms. */
|
|
15
17
|
duration: number;
|
|
18
|
+
/** Stack captured once, at the first read that opened the group. */
|
|
16
19
|
stack: StackFrame[];
|
|
20
|
+
/** How many layout reads were coalesced into this group. Absent means 1.
|
|
21
|
+
* Reads in the same synchronous turn are merged so a layout-thrash loop
|
|
22
|
+
* surfaces as one signal carrying a count rather than thousands. */
|
|
23
|
+
count?: number;
|
|
17
24
|
};
|
|
18
25
|
type LayoutShiftSignal = {
|
|
19
26
|
kind: 'layout-shift';
|
|
@@ -115,11 +122,21 @@ type RenderSignal = {
|
|
|
115
122
|
duration: number;
|
|
116
123
|
/** Prop keys that changed since the previous render (reason === 'props'). */
|
|
117
124
|
changedProps?: string[];
|
|
118
|
-
/** Groups every render
|
|
119
|
-
*
|
|
125
|
+
/** Groups every render from the same commit. Shared by a commit signal and
|
|
126
|
+
* all of its members. */
|
|
120
127
|
commitId: number;
|
|
121
128
|
/** Fiber depth from the committed root — used to indent the cascade. */
|
|
122
129
|
depth: number;
|
|
130
|
+
/** Present only on the per-commit cascade signal: every component that
|
|
131
|
+
* re-rendered in this commit, in walk order. Each member is itself a
|
|
132
|
+
* RenderSignal (without its own `members`). On the commit signal,
|
|
133
|
+
* `component`/`reason`/`depth`/`changedProps` describe the cascade root and
|
|
134
|
+
* `duration` is the commit's total render time (sum of member durations).
|
|
135
|
+
* Coalescing one signal per commit (instead of one per fiber) keeps a
|
|
136
|
+
* layout-thrash-scale re-render from flooding the buffer and the UI. */
|
|
137
|
+
members?: RenderSignal[];
|
|
138
|
+
/** members.length, on the commit signal. */
|
|
139
|
+
count?: number;
|
|
123
140
|
};
|
|
124
141
|
type Signal = ForcedReflowSignal | LayoutShiftSignal | LongTaskSignal | WebVitalSignal | NetworkSignal | RenderSignal | InteractionSignal;
|
|
125
142
|
type SignalKind = Signal['kind'];
|
|
@@ -218,6 +235,12 @@ interface CreateSourceMapResolverOptions {
|
|
|
218
235
|
declare function createSourceMapResolver(opts?: CreateSourceMapResolverOptions): SourceMapResolver;
|
|
219
236
|
declare function parseStack(raw: string | undefined): StackFrame[];
|
|
220
237
|
|
|
238
|
+
/** Record that react-perfscope is about to fetch `url`, so the network
|
|
239
|
+
* collector can exclude its resource-timing entry. */
|
|
240
|
+
declare function markSelfRequest(url: string): void;
|
|
241
|
+
/** True when `url` was fetched by react-perfscope itself. */
|
|
242
|
+
declare function isSelfRequest(url: string): boolean;
|
|
243
|
+
|
|
221
244
|
declare function createLongTasksCollector(): Collector;
|
|
222
245
|
|
|
223
246
|
declare function createForcedReflowCollector(): Collector;
|
|
@@ -364,4 +387,4 @@ interface SelfProfilingCollector extends Collector {
|
|
|
364
387
|
*/
|
|
365
388
|
declare function createSelfProfilingCollector(): SelfProfilingCollector;
|
|
366
389
|
|
|
367
|
-
export { type Collector, type CollectorKind, type CreateSourceMapResolverOptions, type FetchMap, type ForcedReflowSignal, type FpsSample, type FrameCollector, type FrameStats, type HeapCollector, type HeapSample, type HeapTrend, type HeapTrendClass, type InteractionCollector, type InteractionSignal, type LayoutShiftSignal, type LongTaskAttribution, type LongTaskScript, type LongTaskSignal, type NetworkSignal, type ProfilerFrame, type ProfilerSample, type ProfilerStack, type ProfilerTrace, type Recorder, type RecordingResult, type RenderReason, type RenderSignal, type Signal, type SignalKind, type SourceMapResolver, type StackFrame, type WebVitalSignal, analyzeFrames, analyzeHeapTrend, attachLazyStack, attributeLongTaskSignals, attributeWindow, createForcedReflowCollector, createFrameCollector, createHeapCollector, createInteractionCollector, createLayoutShiftCollector, createLongTasksCollector, createNetworkCollector, createRecorder, createSelfProfilingCollector, createSourceMapResolver, createWebVitalsCollector, isUserResource, parseStack, resolveFrame };
|
|
390
|
+
export { type Collector, type CollectorKind, type CreateSourceMapResolverOptions, type FetchMap, type ForcedReflowSignal, type FpsSample, type FrameCollector, type FrameStats, type HeapCollector, type HeapSample, type HeapTrend, type HeapTrendClass, type InteractionCollector, type InteractionSignal, type LayoutShiftSignal, type LongTaskAttribution, type LongTaskScript, type LongTaskSignal, type NetworkSignal, type ProfilerFrame, type ProfilerSample, type ProfilerStack, type ProfilerTrace, type Recorder, type RecordingResult, type RenderReason, type RenderSignal, type Signal, type SignalKind, type SourceMapResolver, type StackFrame, type WebVitalSignal, analyzeFrames, analyzeHeapTrend, attachLazyStack, attributeLongTaskSignals, attributeWindow, createForcedReflowCollector, createFrameCollector, createHeapCollector, createInteractionCollector, createLayoutShiftCollector, createLongTasksCollector, createNetworkCollector, createRecorder, createSelfProfilingCollector, createSourceMapResolver, createWebVitalsCollector, isSelfRequest, isUserResource, markSelfRequest, parseStack, resolveFrame };
|
package/dist/index.d.ts
CHANGED
|
@@ -11,9 +11,16 @@ type StackFrame = {
|
|
|
11
11
|
};
|
|
12
12
|
type ForcedReflowSignal = {
|
|
13
13
|
kind: 'forced-reflow';
|
|
14
|
+
/** Time of the first layout read in the coalesced group. */
|
|
14
15
|
at: number;
|
|
16
|
+
/** Sum of the measured layout-flush durations across the group, in ms. */
|
|
15
17
|
duration: number;
|
|
18
|
+
/** Stack captured once, at the first read that opened the group. */
|
|
16
19
|
stack: StackFrame[];
|
|
20
|
+
/** How many layout reads were coalesced into this group. Absent means 1.
|
|
21
|
+
* Reads in the same synchronous turn are merged so a layout-thrash loop
|
|
22
|
+
* surfaces as one signal carrying a count rather than thousands. */
|
|
23
|
+
count?: number;
|
|
17
24
|
};
|
|
18
25
|
type LayoutShiftSignal = {
|
|
19
26
|
kind: 'layout-shift';
|
|
@@ -115,11 +122,21 @@ type RenderSignal = {
|
|
|
115
122
|
duration: number;
|
|
116
123
|
/** Prop keys that changed since the previous render (reason === 'props'). */
|
|
117
124
|
changedProps?: string[];
|
|
118
|
-
/** Groups every render
|
|
119
|
-
*
|
|
125
|
+
/** Groups every render from the same commit. Shared by a commit signal and
|
|
126
|
+
* all of its members. */
|
|
120
127
|
commitId: number;
|
|
121
128
|
/** Fiber depth from the committed root — used to indent the cascade. */
|
|
122
129
|
depth: number;
|
|
130
|
+
/** Present only on the per-commit cascade signal: every component that
|
|
131
|
+
* re-rendered in this commit, in walk order. Each member is itself a
|
|
132
|
+
* RenderSignal (without its own `members`). On the commit signal,
|
|
133
|
+
* `component`/`reason`/`depth`/`changedProps` describe the cascade root and
|
|
134
|
+
* `duration` is the commit's total render time (sum of member durations).
|
|
135
|
+
* Coalescing one signal per commit (instead of one per fiber) keeps a
|
|
136
|
+
* layout-thrash-scale re-render from flooding the buffer and the UI. */
|
|
137
|
+
members?: RenderSignal[];
|
|
138
|
+
/** members.length, on the commit signal. */
|
|
139
|
+
count?: number;
|
|
123
140
|
};
|
|
124
141
|
type Signal = ForcedReflowSignal | LayoutShiftSignal | LongTaskSignal | WebVitalSignal | NetworkSignal | RenderSignal | InteractionSignal;
|
|
125
142
|
type SignalKind = Signal['kind'];
|
|
@@ -218,6 +235,12 @@ interface CreateSourceMapResolverOptions {
|
|
|
218
235
|
declare function createSourceMapResolver(opts?: CreateSourceMapResolverOptions): SourceMapResolver;
|
|
219
236
|
declare function parseStack(raw: string | undefined): StackFrame[];
|
|
220
237
|
|
|
238
|
+
/** Record that react-perfscope is about to fetch `url`, so the network
|
|
239
|
+
* collector can exclude its resource-timing entry. */
|
|
240
|
+
declare function markSelfRequest(url: string): void;
|
|
241
|
+
/** True when `url` was fetched by react-perfscope itself. */
|
|
242
|
+
declare function isSelfRequest(url: string): boolean;
|
|
243
|
+
|
|
221
244
|
declare function createLongTasksCollector(): Collector;
|
|
222
245
|
|
|
223
246
|
declare function createForcedReflowCollector(): Collector;
|
|
@@ -364,4 +387,4 @@ interface SelfProfilingCollector extends Collector {
|
|
|
364
387
|
*/
|
|
365
388
|
declare function createSelfProfilingCollector(): SelfProfilingCollector;
|
|
366
389
|
|
|
367
|
-
export { type Collector, type CollectorKind, type CreateSourceMapResolverOptions, type FetchMap, type ForcedReflowSignal, type FpsSample, type FrameCollector, type FrameStats, type HeapCollector, type HeapSample, type HeapTrend, type HeapTrendClass, type InteractionCollector, type InteractionSignal, type LayoutShiftSignal, type LongTaskAttribution, type LongTaskScript, type LongTaskSignal, type NetworkSignal, type ProfilerFrame, type ProfilerSample, type ProfilerStack, type ProfilerTrace, type Recorder, type RecordingResult, type RenderReason, type RenderSignal, type Signal, type SignalKind, type SourceMapResolver, type StackFrame, type WebVitalSignal, analyzeFrames, analyzeHeapTrend, attachLazyStack, attributeLongTaskSignals, attributeWindow, createForcedReflowCollector, createFrameCollector, createHeapCollector, createInteractionCollector, createLayoutShiftCollector, createLongTasksCollector, createNetworkCollector, createRecorder, createSelfProfilingCollector, createSourceMapResolver, createWebVitalsCollector, isUserResource, parseStack, resolveFrame };
|
|
390
|
+
export { type Collector, type CollectorKind, type CreateSourceMapResolverOptions, type FetchMap, type ForcedReflowSignal, type FpsSample, type FrameCollector, type FrameStats, type HeapCollector, type HeapSample, type HeapTrend, type HeapTrendClass, type InteractionCollector, type InteractionSignal, type LayoutShiftSignal, type LongTaskAttribution, type LongTaskScript, type LongTaskSignal, type NetworkSignal, type ProfilerFrame, type ProfilerSample, type ProfilerStack, type ProfilerTrace, type Recorder, type RecordingResult, type RenderReason, type RenderSignal, type Signal, type SignalKind, type SourceMapResolver, type StackFrame, type WebVitalSignal, analyzeFrames, analyzeHeapTrend, attachLazyStack, attributeLongTaskSignals, attributeWindow, createForcedReflowCollector, createFrameCollector, createHeapCollector, createInteractionCollector, createLayoutShiftCollector, createLongTasksCollector, createNetworkCollector, createRecorder, createSelfProfilingCollector, createSourceMapResolver, createWebVitalsCollector, isSelfRequest, isUserResource, markSelfRequest, parseStack, resolveFrame };
|
package/dist/index.js
CHANGED
|
@@ -75,6 +75,17 @@ function createRecorder() {
|
|
|
75
75
|
|
|
76
76
|
// src/sourcemap.ts
|
|
77
77
|
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
|
|
78
|
+
|
|
79
|
+
// src/self-requests.ts
|
|
80
|
+
var selfRequests = /* @__PURE__ */ new Set();
|
|
81
|
+
function markSelfRequest(url) {
|
|
82
|
+
selfRequests.add(url);
|
|
83
|
+
}
|
|
84
|
+
function isSelfRequest(url) {
|
|
85
|
+
return selfRequests.has(url);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// src/sourcemap.ts
|
|
78
89
|
var CHROME_FRAME = /^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/;
|
|
79
90
|
var FIREFOX_FRAME = /^(.*?)@(.+?):(\d+):(\d+)$/;
|
|
80
91
|
async function resolveFrame(frame, fetchMap) {
|
|
@@ -122,6 +133,7 @@ function createSourceMapResolver(opts = {}) {
|
|
|
122
133
|
if (existing) return existing;
|
|
123
134
|
const promise = (async () => {
|
|
124
135
|
try {
|
|
136
|
+
markSelfRequest(sourceUrl);
|
|
125
137
|
const res = await f(sourceUrl);
|
|
126
138
|
if (!res || !res.ok) return null;
|
|
127
139
|
const text = await res.text();
|
|
@@ -137,6 +149,7 @@ function createSourceMapResolver(opts = {}) {
|
|
|
137
149
|
return JSON.parse(decoded);
|
|
138
150
|
}
|
|
139
151
|
const mapUrl = new URL(ref, sourceUrl).href;
|
|
152
|
+
markSelfRequest(mapUrl);
|
|
140
153
|
const mapRes = await f(mapUrl);
|
|
141
154
|
if (!mapRes || !mapRes.ok) return null;
|
|
142
155
|
return await mapRes.json();
|
|
@@ -275,18 +288,47 @@ var LAYOUT_GETTERS = [
|
|
|
275
288
|
"scrollHeight"
|
|
276
289
|
];
|
|
277
290
|
var LAYOUT_METHODS = ["getBoundingClientRect", "getClientRects"];
|
|
291
|
+
var scheduleFlush = typeof queueMicrotask === "function" ? queueMicrotask : typeof Promise !== "undefined" ? (cb) => {
|
|
292
|
+
Promise.resolve().then(cb);
|
|
293
|
+
} : (cb) => cb();
|
|
278
294
|
function createForcedReflowCollector() {
|
|
279
295
|
let active = false;
|
|
280
296
|
let emit = () => {
|
|
281
297
|
};
|
|
282
298
|
const saved = [];
|
|
283
299
|
let mutationObserver = null;
|
|
300
|
+
let group = null;
|
|
284
301
|
function consumePendingMutations() {
|
|
285
302
|
if (!mutationObserver) {
|
|
286
303
|
return true;
|
|
287
304
|
}
|
|
288
305
|
return mutationObserver.takeRecords().length > 0;
|
|
289
306
|
}
|
|
307
|
+
function flush() {
|
|
308
|
+
if (!group) return;
|
|
309
|
+
const g = group;
|
|
310
|
+
group = null;
|
|
311
|
+
const signal = {
|
|
312
|
+
kind: "forced-reflow",
|
|
313
|
+
at: g.at,
|
|
314
|
+
duration: g.duration,
|
|
315
|
+
count: g.count
|
|
316
|
+
};
|
|
317
|
+
attachLazyStack(signal, g.rawStack, 1);
|
|
318
|
+
emit(signal);
|
|
319
|
+
}
|
|
320
|
+
function record(at, duration, rawStack) {
|
|
321
|
+
if (group) {
|
|
322
|
+
group.count++;
|
|
323
|
+
group.duration += duration;
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
group = { at, duration, count: 1, rawStack };
|
|
327
|
+
scheduleFlush(flush);
|
|
328
|
+
}
|
|
329
|
+
function needsStack() {
|
|
330
|
+
return group === null;
|
|
331
|
+
}
|
|
290
332
|
function patchGetter(proto, key) {
|
|
291
333
|
if (typeof proto !== "object" || proto === null) return;
|
|
292
334
|
const desc = Object.getOwnPropertyDescriptor(proto, key);
|
|
@@ -300,13 +342,10 @@ function createForcedReflowCollector() {
|
|
|
300
342
|
if (!consumePendingMutations()) {
|
|
301
343
|
return originalGet.call(this);
|
|
302
344
|
}
|
|
345
|
+
const rawStack = needsStack() ? new Error().stack : void 0;
|
|
303
346
|
const at = performance.now();
|
|
304
|
-
const rawStack = new Error().stack;
|
|
305
347
|
const value = originalGet.call(this);
|
|
306
|
-
|
|
307
|
-
const signal = { kind: "forced-reflow", at, duration };
|
|
308
|
-
attachLazyStack(signal, rawStack, 1);
|
|
309
|
-
emit(signal);
|
|
348
|
+
record(at, performance.now() - at, rawStack);
|
|
310
349
|
return value;
|
|
311
350
|
}
|
|
312
351
|
return originalGet.call(this);
|
|
@@ -328,13 +367,10 @@ function createForcedReflowCollector() {
|
|
|
328
367
|
if (!consumePendingMutations()) {
|
|
329
368
|
return original.apply(this, args);
|
|
330
369
|
}
|
|
370
|
+
const rawStack = needsStack() ? new Error().stack : void 0;
|
|
331
371
|
const at = performance.now();
|
|
332
|
-
const rawStack = new Error().stack;
|
|
333
372
|
const value = original.apply(this, args);
|
|
334
|
-
|
|
335
|
-
const signal = { kind: "forced-reflow", at, duration };
|
|
336
|
-
attachLazyStack(signal, rawStack, 1);
|
|
337
|
-
emit(signal);
|
|
373
|
+
record(at, performance.now() - at, rawStack);
|
|
338
374
|
return value;
|
|
339
375
|
}
|
|
340
376
|
return original.apply(this, args);
|
|
@@ -376,6 +412,7 @@ function createForcedReflowCollector() {
|
|
|
376
412
|
deactivate() {
|
|
377
413
|
if (!active) return;
|
|
378
414
|
active = false;
|
|
415
|
+
flush();
|
|
379
416
|
if (mutationObserver) {
|
|
380
417
|
try {
|
|
381
418
|
mutationObserver.disconnect();
|
|
@@ -521,6 +558,7 @@ function createNetworkCollector() {
|
|
|
521
558
|
if (!active) return;
|
|
522
559
|
for (const raw of list.getEntries()) {
|
|
523
560
|
const entry = raw;
|
|
561
|
+
if (isSelfRequest(entry.name)) continue;
|
|
524
562
|
emit({
|
|
525
563
|
kind: "network",
|
|
526
564
|
url: entry.name,
|
|
@@ -983,7 +1021,9 @@ export {
|
|
|
983
1021
|
createSelfProfilingCollector,
|
|
984
1022
|
createSourceMapResolver,
|
|
985
1023
|
createWebVitalsCollector,
|
|
1024
|
+
isSelfRequest,
|
|
986
1025
|
isUserResource,
|
|
1026
|
+
markSelfRequest,
|
|
987
1027
|
parseStack,
|
|
988
1028
|
resolveFrame
|
|
989
1029
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/recorder.ts","../src/sourcemap.ts","../src/collectors/long-tasks.ts","../src/collectors/forced-reflow.ts","../src/collectors/layout-shift.ts","../src/collectors/network.ts","../src/collectors/web-vitals.ts","../src/collectors/heap.ts","../src/collectors/interaction.ts","../src/collectors/frames.ts","../src/collectors/self-profiling.ts"],"sourcesContent":["import type { Collector, Recorder, RecordingResult, Signal } from './types'\n\nconst BUFFER_CAP = 10_000\n\nexport interface InternalRecorder extends Recorder {\n __push: (signal: Signal) => void\n}\n\nexport function createRecorder(): Recorder {\n let recording = false\n let startedAt = 0\n let buffer: Signal[] = []\n const subscribers = new Set<(s: Signal) => void>()\n const collectors: Collector[] = []\n\n function notify(signal: Signal) {\n for (const cb of subscribers) {\n try {\n cb(signal)\n } catch (err) {\n console.warn('[react-perfscope] subscriber threw:', err)\n }\n }\n }\n\n function push(signal: Signal) {\n if (!recording) return\n buffer.push(signal)\n if (buffer.length > BUFFER_CAP) {\n buffer.splice(0, buffer.length - BUFFER_CAP)\n }\n notify(signal)\n }\n\n const recorder: InternalRecorder = {\n start() {\n if (recording) return\n recording = true\n startedAt = performance.now()\n buffer = []\n for (const c of collectors) {\n try {\n c.activate(push)\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to activate:`, err)\n }\n }\n },\n stop(): RecordingResult {\n if (!recording) {\n return { signals: [], startedAt: 0, duration: 0 }\n }\n for (const c of collectors) {\n try {\n c.deactivate()\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to deactivate:`, err)\n }\n }\n const duration = performance.now() - startedAt\n const result: RecordingResult = {\n signals: buffer.slice(),\n startedAt,\n duration,\n }\n recording = false\n buffer = []\n return result\n },\n isRecording() {\n return recording\n },\n onSignal(cb) {\n subscribers.add(cb)\n return () => subscribers.delete(cb)\n },\n use(collector) {\n collectors.push(collector)\n },\n __push: push,\n }\n return recorder\n}\n","import { TraceMap, originalPositionFor, type SourceMapInput } from '@jridgewell/trace-mapping'\nimport type { StackFrame } from './types'\n\nconst CHROME_FRAME = /^\\s*at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/\nconst FIREFOX_FRAME = /^(.*?)@(.+?):(\\d+):(\\d+)$/\n\n/** A parsed source map (the JSON object), as returned by a FetchMap. */\nexport type RawSourceMap = SourceMapInput\n\nexport type FetchMap = (file: string) => Promise<RawSourceMap | null>\n\nexport async function resolveFrame(\n frame: StackFrame,\n fetchMap: FetchMap\n): Promise<StackFrame> {\n try {\n const map = await fetchMap(frame.file)\n if (!map) return frame\n // trace-mapping is pure JS (no wasm), so this works in the browser where\n // Mozilla's source-map SourceMapConsumer needs an explicitly-initialized\n // mappings.wasm. Columns are 0-based here, matching the captured frames.\n const tracer = new TraceMap(map)\n const pos = originalPositionFor(tracer, { line: frame.line, column: frame.col })\n if (pos.source == null || pos.line == null || pos.column == null) {\n return frame\n }\n const resolved: StackFrame = {\n file: pos.source,\n line: pos.line,\n col: pos.column,\n }\n if (pos.name) resolved.fnName = pos.name\n else if (frame.fnName) resolved.fnName = frame.fnName\n return resolved\n } catch (err) {\n console.warn('[react-perfscope] resolveFrame failed:', err)\n return frame\n }\n}\n\n/**\n * Attach a lazy `stack` getter to `target` that parses `raw` on first access\n * and memoizes the result. Use this from collectors to defer parseStack cost\n * until a consumer actually reads `signal.stack`.\n *\n * `skipTopFrames` drops the leading N parsed frames — useful for collectors\n * that wrap a patched function (the wrapper itself shows up as the topmost\n * frame, but it's noise from the user's perspective).\n */\nexport function attachLazyStack(\n target: object,\n raw: string | undefined,\n skipTopFrames = 0\n): void {\n let cached: StackFrame[] | null = null\n Object.defineProperty(target, 'stack', {\n enumerable: true,\n configurable: true,\n get() {\n if (cached === null) {\n const all = parseStack(raw)\n cached = skipTopFrames > 0 ? all.slice(skipTopFrames) : all\n }\n return cached\n },\n })\n}\n\nexport interface SourceMapResolver {\n /** Resolve a parsed StackFrame to its original source position. Falls back to the input frame on any failure. */\n resolve(frame: StackFrame): Promise<StackFrame>\n}\n\nexport interface CreateSourceMapResolverOptions {\n /** Override the global fetch. Useful for tests and non-browser environments. */\n fetch?: typeof globalThis.fetch\n}\n\n/**\n * Create a SourceMap resolver that fetches `.map` files from the live URL\n * referenced in each source file's `//# sourceMappingURL=` directive.\n * Caches the parsed source map per source URL so repeated resolves against\n * the same file are O(1) after the first.\n *\n * Returns the input frame on any failure (network error, missing map, etc.).\n */\nexport function createSourceMapResolver(opts: CreateSourceMapResolverOptions = {}): SourceMapResolver {\n const f = opts.fetch ?? (typeof fetch !== 'undefined' ? fetch.bind(globalThis) : null)\n const cache = new Map<string, Promise<RawSourceMap | null>>()\n\n function fetchMapFor(sourceUrl: string): Promise<RawSourceMap | null> {\n if (!f) return Promise.resolve(null)\n const existing = cache.get(sourceUrl)\n if (existing) return existing\n const promise = (async () => {\n try {\n const res = await f(sourceUrl)\n if (!res || !res.ok) return null\n const text = await res.text()\n const m = text.match(/\\/\\/[#@]\\s*sourceMappingURL=(.+?)\\s*$/m)\n if (!m) return null\n const ref = m[1]!.trim()\n if (ref.startsWith('data:')) {\n const commaIdx = ref.indexOf(',')\n if (commaIdx === -1) return null\n const header = ref.slice(0, commaIdx)\n const payload = ref.slice(commaIdx + 1)\n const decoded = header.includes('base64')\n ? typeof atob === 'function'\n ? atob(payload)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n : (globalThis as any).Buffer.from(payload, 'base64').toString('utf8')\n : decodeURIComponent(payload)\n return JSON.parse(decoded) as RawSourceMap\n }\n const mapUrl = new URL(ref, sourceUrl).href\n const mapRes = await f(mapUrl)\n if (!mapRes || !mapRes.ok) return null\n return (await mapRes.json()) as RawSourceMap\n } catch {\n return null\n }\n })()\n cache.set(sourceUrl, promise)\n return promise\n }\n\n return {\n async resolve(frame) {\n try {\n return await resolveFrame(frame, fetchMapFor)\n } catch {\n return frame\n }\n },\n }\n}\n\nexport function parseStack(raw: string | undefined): StackFrame[] {\n if (!raw) return []\n const frames: StackFrame[] = []\n for (const line of raw.split('\\n')) {\n const chromeMatch = line.match(CHROME_FRAME)\n if (chromeMatch) {\n const [, fnName, file, lineStr, colStr] = chromeMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n continue\n }\n const firefoxMatch = line.match(FIREFOX_FRAME)\n if (firefoxMatch) {\n const [, fnName, file, lineStr, colStr] = firefoxMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n }\n }\n return frames\n}\n","import type { Collector, LongTaskScript, Signal } from '../types'\n\nconst LOAF = 'long-animation-frame'\nconst LEGACY = 'longtask'\n\n/** A single script entry inside a Long Animation Frame. */\ninterface ScriptTiming {\n duration?: number\n invoker?: string\n invokerType?: string\n sourceURL?: string\n sourceFunctionName?: string\n sourceCharPosition?: number\n}\n\ninterface LoAFEntry extends PerformanceEntry {\n blockingDuration?: number\n scripts?: ScriptTiming[]\n}\n\nfunction supportsLoAF(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n return Array.isArray(types) && types.includes(LOAF)\n}\n\nfunction mapScripts(scripts: ScriptTiming[]): LongTaskScript[] {\n return scripts.map((s) => ({\n invokerType: s.invokerType ?? 'unknown',\n invoker: s.invoker ?? '',\n sourceURL: s.sourceURL ?? '',\n sourceFunctionName: s.sourceFunctionName ?? '',\n charPosition: typeof s.sourceCharPosition === 'number' ? s.sourceCharPosition : -1,\n duration: typeof s.duration === 'number' ? s.duration : 0,\n }))\n}\n\nexport function createLongTasksCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'long-task',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; long-tasks disabled')\n return\n }\n active = true\n const useLoAF = supportsLoAF()\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const entry of list.getEntries()) {\n if (useLoAF) {\n const loaf = entry as LoAFEntry\n const scripts = Array.isArray(loaf.scripts) ? mapScripts(loaf.scripts) : []\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n scripts,\n ...(typeof loaf.blockingDuration === 'number'\n ? { blockingDuration: loaf.blockingDuration }\n : {}),\n })\n } else {\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n })\n }\n }\n })\n observer.observe({ type: useLoAF ? LOAF : LEGACY, buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] long-tasks collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\nimport { attachLazyStack } from '../sourcemap'\n\nconst LAYOUT_GETTERS = [\n 'offsetWidth',\n 'offsetHeight',\n 'offsetLeft',\n 'offsetTop',\n 'clientWidth',\n 'clientHeight',\n 'scrollWidth',\n 'scrollHeight',\n] as const\n\nconst LAYOUT_METHODS = ['getBoundingClientRect', 'getClientRects'] as const\n\ntype SavedDescriptor = {\n proto: object\n key: string\n descriptor: PropertyDescriptor\n}\n\nexport function createForcedReflowCollector(): Collector {\n let active = false\n let emit: (s: Signal) => void = () => {}\n const saved: SavedDescriptor[] = []\n let mutationObserver: MutationObserver | null = null\n\n function consumePendingMutations(): boolean {\n if (!mutationObserver) {\n // Fallback when MutationObserver isn't available: always treat as dirty\n // (Phase 1 over-report behavior).\n return true\n }\n return mutationObserver.takeRecords().length > 0\n }\n\n function patchGetter(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || !desc.get) return\n saved.push({ proto, key, descriptor: desc })\n const originalGet = desc.get\n Object.defineProperty(proto, key, {\n configurable: true,\n get(this: unknown) {\n if (active) {\n if (!consumePendingMutations()) {\n return originalGet.call(this)\n }\n const at = performance.now()\n const rawStack = new Error().stack\n const value = originalGet.call(this)\n const duration = performance.now() - at\n const signal = { kind: 'forced-reflow' as const, at, duration } as unknown as Signal\n attachLazyStack(signal, rawStack, 1)\n emit(signal)\n return value\n }\n return originalGet.call(this)\n },\n set: desc.set,\n })\n }\n\n function patchMethod(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || typeof desc.value !== 'function') return\n saved.push({ proto, key, descriptor: desc })\n const original = desc.value as (...args: unknown[]) => unknown\n Object.defineProperty(proto, key, {\n configurable: true,\n writable: true,\n value: function patchedLayoutMethod(this: unknown, ...args: unknown[]) {\n if (active) {\n if (!consumePendingMutations()) {\n return original.apply(this, args)\n }\n const at = performance.now()\n const rawStack = new Error().stack\n const value = original.apply(this, args)\n const duration = performance.now() - at\n const signal = { kind: 'forced-reflow' as const, at, duration } as unknown as Signal\n attachLazyStack(signal, rawStack, 1)\n emit(signal)\n return value\n }\n return original.apply(this, args)\n },\n })\n }\n\n return {\n kind: 'forced-reflow',\n activate(emitFn) {\n if (active) return\n emit = emitFn\n active = true\n\n if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {\n try {\n mutationObserver = new MutationObserver(() => {})\n mutationObserver.observe(document, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: true,\n })\n } catch (err) {\n console.warn('[react-perfscope] forced-reflow MutationObserver failed:', err)\n mutationObserver = null\n }\n }\n\n if (typeof HTMLElement !== 'undefined') {\n for (const key of LAYOUT_GETTERS) {\n patchGetter(HTMLElement.prototype, key)\n }\n }\n if (typeof Element !== 'undefined') {\n for (const key of LAYOUT_METHODS) {\n patchMethod(Element.prototype, key)\n }\n }\n },\n deactivate() {\n if (!active) return\n active = false\n if (mutationObserver) {\n try {\n mutationObserver.disconnect()\n } catch {\n // ignore\n }\n mutationObserver = null\n }\n for (const { proto, key, descriptor } of saved) {\n Object.defineProperty(proto, key, descriptor)\n }\n saved.length = 0\n },\n }\n}\n","import type { Collector, Signal } from '../types'\n\ninterface LayoutShiftSource {\n currentRect: DOMRect\n previousRect?: DOMRect\n node?: Node | null\n}\n\ninterface LayoutShiftEntryLike extends PerformanceEntry {\n value: number\n hadRecentInput: boolean\n sources?: LayoutShiftSource[]\n}\n\nconst PERFSCOPE_HOST_ATTR = 'data-perfscope-host'\n\nfunction rectsOverlap(a: DOMRect, b: DOMRect, tolerance = 0): boolean {\n return !(\n a.x + a.width < b.x - tolerance ||\n b.x + b.width < a.x - tolerance ||\n a.y + a.height < b.y - tolerance ||\n b.y + b.height < a.y - tolerance\n )\n}\n\n/**\n * Returns true when every source in the entry is part of our floating\n * widget. We want to ignore shifts caused by the perfscope UI itself.\n *\n * Detection has two paths:\n * 1. Node-based: walk up `source.node` looking for `[data-perfscope-host]`.\n * Works when the node is in light DOM.\n * 2. Rect-based fallback: compare `source.currentRect` against every host\n * element's bounding rect. This catches the Shadow-DOM case where the\n * browser doesn't expose the inner node (Shadow root boundary).\n */\nfunction collectPerfscopeRects(): DOMRect[] {\n const hosts = Array.from(document.querySelectorAll(`[${PERFSCOPE_HOST_ATTR}]`))\n const rects: DOMRect[] = []\n for (const h of hosts) {\n // The light-DOM host element usually has height 0 because Shadow DOM\n // content isn't part of its layout. We need to peek inside the shadow\n // root and collect bounds of any positioned children.\n const sr = (h as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot\n if (sr) {\n for (const child of Array.from(sr.children)) {\n const r = (child as Element).getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n } else {\n const r = h.getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n }\n return rects\n}\n\nfunction entryIsOnlyFromPerfscope(sources: LayoutShiftSource[]): boolean {\n if (sources.length === 0) return false\n if (typeof document === 'undefined') return false\n\n const hostRects = collectPerfscopeRects()\n if (hostRects.length === 0) return false\n\n for (const src of sources) {\n let matched = false\n const node = src.node as (Node & { closest?: (sel: string) => Element | null }) | null | undefined\n if (node) {\n // Node-based check\n if (typeof (node as { closest?: unknown }).closest === 'function') {\n if ((node as Element).closest(`[${PERFSCOPE_HOST_ATTR}]`)) matched = true\n } else {\n let parent: (Element | null) = (node as Node).parentElement as Element | null\n while (parent) {\n if (parent.hasAttribute(PERFSCOPE_HOST_ATTR)) { matched = true; break }\n parent = parent.parentElement\n }\n }\n }\n // Rect-based fallback (shadow DOM): if source rect overlaps any of our\n // host rects, consider it our widget. Tolerance covers the case where\n // the widget changes size during the shift (its previous/current bounds\n // differ but both sit in the same screen corner).\n if (!matched) {\n for (const hostRect of hostRects) {\n if (rectsOverlap(src.currentRect, hostRect, 24)) {\n matched = true\n break\n }\n }\n }\n if (!matched) return false\n }\n return true\n}\n\nexport function createLayoutShiftCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'layout-shift',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; layout-shift disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as LayoutShiftEntryLike\n // Note: production CLS metrics exclude shifts with hadRecentInput\n // (user-initiated movements are considered intentional). For a\n // dev tool, the user explicitly WANTS to see what their clicks\n // caused — so we report these too.\n const sources = entry.sources ?? []\n if (entryIsOnlyFromPerfscope(sources)) continue\n // Convert viewport-relative rects to document-relative coords so\n // overlays stay anchored to the shifted DOM position when the\n // user scrolls. Filter above runs first on viewport coords (our\n // widget is position:fixed, lives in viewport space).\n const sx = (typeof window !== 'undefined' && window.scrollX) || 0\n const sy = (typeof window !== 'undefined' && window.scrollY) || 0\n const toDocRect = (r: DOMRect) =>\n new DOMRect(r.x + sx, r.y + sy, r.width, r.height)\n const rects = sources.map((s) => toDocRect(s.currentRect))\n // previousRect is undefined when the element was newly inserted.\n // An \"empty\" rect (w=0, h=0) likewise means there was no prior\n // box — treat both as `null` so the overlay can decide not to\n // draw an arrow for these.\n const prevRects: (DOMRect | null)[] = sources.map((s) => {\n const pr = s.previousRect\n if (!pr) return null\n if (pr.width === 0 && pr.height === 0) return null\n return toDocRect(pr)\n })\n emit({\n kind: 'layout-shift',\n at: entry.startTime,\n value: entry.value,\n sources: rects,\n previousSources: prevRects,\n })\n }\n })\n observer.observe({ type: 'layout-shift', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] layout-shift collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\n\ninterface ResourceTimingLike extends PerformanceEntry {\n transferSize?: number\n renderBlockingStatus?: 'blocking' | 'non-blocking'\n}\n\nexport function createNetworkCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'network',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; network disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as ResourceTimingLike\n emit({\n kind: 'network',\n url: entry.name,\n startedAt: entry.startTime,\n duration: entry.duration,\n size: entry.transferSize ?? 0,\n blocking: entry.renderBlockingStatus === 'blocking',\n })\n }\n })\n observer.observe({ type: 'resource', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] network collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import { onLCP, onINP, onCLS, onFCP, onTTFB, type Metric } from 'web-vitals'\nimport type { Collector, Signal, WebVitalSignal } from '../types'\n\ntype VitalName = WebVitalSignal['name']\n\nexport function createWebVitalsCollector(): Collector {\n let active = false\n let subscribed = false\n let emit: (signal: Signal) => void = () => {}\n\n function makeHandler(name: VitalName) {\n return (metric: Metric) => {\n if (!active) return\n emit({ kind: 'web-vital', name, value: metric.value })\n }\n }\n\n return {\n kind: 'web-vital',\n activate(emitFn) {\n emit = emitFn\n active = true\n if (subscribed) return\n try {\n onLCP(makeHandler('LCP'))\n onINP(makeHandler('INP'))\n onCLS(makeHandler('CLS'))\n onFCP(makeHandler('FCP'))\n onTTFB(makeHandler('TTFB'))\n subscribed = true\n } catch (err) {\n console.warn('[react-perfscope] web-vitals collector failed to subscribe:', err)\n active = false\n }\n },\n deactivate() {\n // The web-vitals library does not expose unsubscribe. We keep the\n // handlers attached and gate emission via `active`. Re-activating\n // updates `emit` without re-subscribing.\n active = false\n },\n }\n}\n","import type {\n Collector,\n HeapSample,\n HeapTrend,\n HeapTrendClass,\n RecordingResult,\n} from '../types'\n\n/** How often to read heap usage while recording. Reading performance.memory\n * is cheap, so we sample at 4Hz: a 1s cadence is too coarse — short spikes fall\n * between samples and the line, drawn straight between sparse points, smooths\n * them into a ramp. 250ms localizes spikes without meaningful overhead. */\nconst SAMPLE_INTERVAL_MS = 250\n/** Cap on retained samples so a multi-hour session can't grow the array\n * unbounded. At 250ms this is ~83 min; past that, oldest samples drop. */\nconst MAX_SAMPLES = 20_000\n\n/** Below this, a trend can't be estimated reliably. */\nconst MIN_SAMPLES = 4\n/** How many contiguous segments to split the series into when estimating the\n * floor. Each segment contributes its minimum (the post-GC trough). */\nconst FLOOR_SEGMENTS = 8\n\nconst MB = 1024 * 1024\n/** Floor-growth thresholds, in bytes per minute. */\nconst GROWING_SLOPE = 1 * MB\nconst LEAK_SLOPE = 5 * MB\n/** A rate alone isn't enough: over a short recording, a sub-megabyte wobble in\n * the floor extrapolates to a huge MB/min and would false-positive. Require the\n * floor to have actually risen by at least this much across the window before\n * calling anything growing/leaking. */\nconst MIN_NET_GROWTH = 2 * MB\n\ninterface MemoryInfo {\n usedJSHeapSize: number\n totalJSHeapSize: number\n jsHeapSizeLimit: number\n}\n\nfunction readMemory(): MemoryInfo | null {\n const perf = (globalThis as { performance?: { memory?: MemoryInfo } }).performance\n const mem = perf?.memory\n if (!mem || typeof mem.usedJSHeapSize !== 'number') return null\n return mem\n}\n\n/**\n * Least-squares slope of points (x, y). Returns 0 when x has no spread\n * (vertical / single distinct x) to avoid a divide-by-zero blow-up.\n */\nfunction slope(points: { x: number; y: number }[]): number {\n const n = points.length\n if (n < 2) return 0\n let sx = 0\n let sy = 0\n let sxy = 0\n let sxx = 0\n for (const { x, y } of points) {\n sx += x\n sy += y\n sxy += x * y\n sxx += x * x\n }\n const denom = n * sxx - sx * sx\n if (denom === 0) return 0\n return (n * sxy - sx * sy) / denom\n}\n\n/**\n * Estimate whether memory is being retained across the recording.\n *\n * GC makes raw heap usage a sawtooth, so the peak is noisy. The reliable\n * signal is the *floor* — the post-GC troughs. We split the series into\n * contiguous segments, take the minimum of each (its trough), and regress\n * those minima against time.\n *\n * A rising overall slope is necessary but NOT sufficient: a one-time step\n * (heap warms up early, then plateaus) also regresses to a positive slope, and\n * flagging that as a leak is a false positive — the classic \"idle recording\n * reads abnormal\" bug. A real leak keeps climbing, so we additionally require\n * the *recent* half of the floor to still be rising. We also gate on a minimum\n * net growth, since over a short window a sub-MB wobble extrapolates to a steep\n * per-minute slope.\n *\n * Returns null when there are too few samples to say anything.\n */\nexport function analyzeHeapTrend(samples: HeapSample[]): HeapTrend | null {\n if (samples.length < MIN_SAMPLES) return null\n const t0 = samples[0]!.at\n const segSize = Math.max(1, Math.ceil(samples.length / FLOOR_SEGMENTS))\n const floorPoints: { x: number; y: number }[] = []\n for (let i = 0; i < samples.length; i += segSize) {\n const seg = samples.slice(i, i + segSize)\n let min = Infinity\n for (const s of seg) min = Math.min(min, s.used)\n const mid = seg[Math.floor(seg.length / 2)]!\n floorPoints.push({ x: (mid.at - t0) / 60000, y: min })\n }\n const slopeBytesPerMin = slope(floorPoints)\n const spanMin = (samples[samples.length - 1]!.at - t0) / 60000\n const projectedGrowth = slopeBytesPerMin * spanMin\n // Recent trend: is the floor still climbing in the latter half? Distinguishes\n // a sustained leak from a one-time step that has since plateaued.\n const recent = floorPoints.slice(Math.floor(floorPoints.length / 2))\n const recentSlope = recent.length >= 2 ? slope(recent) : slopeBytesPerMin\n\n let classification: HeapTrendClass = 'stable'\n const sustained = projectedGrowth >= MIN_NET_GROWTH && recentSlope >= GROWING_SLOPE\n if (sustained) {\n classification =\n slopeBytesPerMin >= LEAK_SLOPE && recentSlope >= LEAK_SLOPE ? 'leak-suspected' : 'growing'\n }\n return { classification, slopeBytesPerMin }\n}\n\nexport interface HeapCollector extends Collector {\n /** Attach the sampled heap series to the recording result. Returns the\n * input untouched when nothing was sampled (unsupported browser). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Samples `performance.memory` on an interval for the duration of a recording\n * and attaches the series via `finalize`. It is a Collector so the recorder\n * drives its start/stop, but it emits no signals — the series is a separate\n * track (see RecordingResult.heapSamples), so a busy session's signal buffer\n * can't evict it. No-ops entirely when performance.memory is unavailable\n * (non-Chromium), leaving `heapSamples` absent so the UI can show a fallback.\n */\nexport function createHeapCollector(): HeapCollector {\n let samples: HeapSample[] = []\n let timer: ReturnType<typeof setInterval> | null = null\n\n function sample(): void {\n const mem = readMemory()\n if (!mem) return\n samples.push({ at: performance.now(), used: mem.usedJSHeapSize, total: mem.totalJSHeapSize })\n if (samples.length > MAX_SAMPLES) samples.splice(0, samples.length - MAX_SAMPLES)\n }\n\n return {\n kind: 'heap',\n activate() {\n samples = []\n if (!readMemory()) return // unsupported → never start the timer\n sample()\n timer = setInterval(sample, SAMPLE_INTERVAL_MS)\n },\n deactivate() {\n if (timer == null) return\n clearInterval(timer)\n timer = null\n sample() // one final reading at stop\n },\n finalize(result) {\n if (samples.length === 0) return result\n return { ...result, heapSamples: samples.slice() }\n },\n }\n}\n","import type { Collector, InteractionSignal, RecordingResult } from '../types'\n\n/** Event Timing only surfaces events at/over this duration (ms); 40ms keeps\n * trivial interactions out while still catching anything a user would feel. */\nconst DURATION_THRESHOLD = 40\n\ninterface EventTimingEntry extends PerformanceEntry {\n processingStart: number\n processingEnd: number\n interactionId?: number\n target?: unknown\n}\n\nfunction selectorFor(target: unknown): string | undefined {\n const el = target as { tagName?: string; id?: string; className?: unknown } | null\n if (!el || typeof el.tagName !== 'string') return undefined\n let s = el.tagName.toLowerCase()\n if (el.id) s += `#${el.id}`\n else if (typeof el.className === 'string' && el.className.trim()) {\n s += `.${el.className.trim().split(/\\s+/)[0]}`\n }\n return s\n}\n\nfunction supportsEventTiming(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n // happy-dom / older browsers may not expose supportedEntryTypes; if the\n // observer exists at all we still try, and observe() throwing is caught.\n return !types || types.includes('event')\n}\n\nexport interface InteractionCollector extends Collector {\n /** Group buffered Event Timing entries into one interaction each and append\n * them to the result. Returns the input untouched when none qualified. */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records Event Timing entries during a recording and, on finalize, turns each\n * user interaction (grouped by interactionId) into one signal carrying the INP\n * latency breakdown: input delay → processing → presentation. The longest\n * event in a group defines the interaction's latency (matching how INP is\n * attributed). Emits no live signals — interactions are assembled at finalize,\n * then the self-profiling collector attributes the processing window to the\n * developer's hot functions.\n */\nexport function createInteractionCollector(): InteractionCollector {\n let active = false\n let observer: PerformanceObserver | null = null\n let entries: EventTimingEntry[] = []\n\n return {\n kind: 'interaction',\n activate() {\n if (typeof PerformanceObserver === 'undefined' || !supportsEventTiming()) return\n active = true\n entries = []\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const e of list.getEntries()) entries.push(e as EventTimingEntry)\n })\n // `event` covers all interaction events; `first-input` guarantees the\n // first one even if it's under the duration threshold.\n observer.observe({ type: 'event', buffered: false, durationThreshold: DURATION_THRESHOLD } as PerformanceObserverInit)\n try {\n observer.observe({ type: 'first-input', buffered: false } as PerformanceObserverInit)\n } catch {\n // first-input not supported everywhere; the event stream is enough.\n }\n } catch (err) {\n console.warn('[react-perfscope] interaction collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n finalize(result) {\n const byId = new Map<number, EventTimingEntry[]>()\n for (const e of entries) {\n const id = e.interactionId\n if (!id) continue // 0 / undefined → not part of a discrete interaction\n const group = byId.get(id)\n if (group) group.push(e)\n else byId.set(id, [e])\n }\n const interactions: InteractionSignal[] = []\n for (const group of byId.values()) {\n // All events of one interaction (pointerdown/up/click) report the same\n // `duration` (the whole interaction latency), so the breakdown can't\n // come from a single event. Span the processing across the group:\n // earliest processingStart → latest processingEnd (matches web-vitals).\n // The \"defining\" event for label/target is the one with the most\n // processing — typically the click/keydown that actually ran handlers.\n let duration = 0\n let startTime = Infinity\n let processingStart = Infinity\n let processingEnd = -Infinity\n let defining = group[0]!\n let maxProcessing = -Infinity\n for (const e of group) {\n if (e.duration > duration) duration = e.duration\n if (e.startTime < startTime) startTime = e.startTime\n if (e.processingStart < processingStart) processingStart = e.processingStart\n if (e.processingEnd > processingEnd) processingEnd = e.processingEnd\n const proc = e.processingEnd - e.processingStart\n if (proc > maxProcessing) {\n maxProcessing = proc\n defining = e\n }\n }\n if (duration < DURATION_THRESHOLD) continue\n const inputDelay = Math.max(0, processingStart - startTime)\n const processing = Math.max(0, processingEnd - processingStart)\n const presentation = Math.max(0, startTime + duration - processingEnd)\n interactions.push({\n kind: 'interaction',\n at: startTime,\n eventType: defining.name,\n ...(selectorFor(defining.target) ? { target: selectorFor(defining.target) } : {}),\n duration,\n inputDelay,\n processing,\n presentation,\n })\n }\n if (interactions.length === 0) return result\n interactions.sort((a, b) => a.at - b.at)\n return { ...result, signals: [...result.signals, ...interactions] }\n },\n }\n}\n","import type { Collector, FpsSample, FrameStats, RecordingResult } from '../types'\n\n/** 60fps frame budget (ms). Gaps are scored against this to count drops. */\nconst FRAME_BUDGET = 1000 / 60\n/** Window for the FPS series; 500ms smooths per-frame noise while still showing\n * a scroll-jank dip. */\nconst BUCKET_MS = 500\n/** A trailing window shorter than this is too small to estimate FPS reliably. */\nconst MIN_BUCKET_SPAN = 100\n/** Below this we can't say anything useful. */\nconst MIN_FRAMES = 8\n/** Cap retained frames so a long session can't grow the array unbounded\n * (~5.5 min at 60fps); past that, oldest drop. */\nconst MAX_FRAMES = 20_000\n\n/**\n * Turn raw requestAnimationFrame timestamps into a frame-rate picture:\n * a windowed FPS series, the lowest sustained FPS, the worst single hitch,\n * and an approximate dropped-frame count. Long tasks (>50ms) show up here as\n * big gaps, but so does sustained scroll jank (30–50ms frames) that the\n * long-task collector's threshold misses.\n *\n * Returns null when there are too few frames to analyze.\n */\nexport function analyzeFrames(frames: number[]): FrameStats | null {\n if (frames.length < MIN_FRAMES) return null\n\n let longestFrameMs = 0\n let droppedFrames = 0\n for (let i = 1; i < frames.length; i++) {\n const gap = frames[i]! - frames[i - 1]!\n if (gap > longestFrameMs) longestFrameMs = gap\n const dropped = Math.round(gap / FRAME_BUDGET) - 1\n if (dropped > 0) droppedFrames += dropped\n }\n\n const t0 = frames[0]!\n const end = frames[frames.length - 1]!\n const series: FpsSample[] = []\n let minFps = Infinity\n let idx = 0\n for (let bStart = t0; bStart < end; bStart += BUCKET_MS) {\n const bEnd = Math.min(bStart + BUCKET_MS, end)\n const span = bEnd - bStart\n let count = 0\n while (idx < frames.length && frames[idx]! < bEnd) {\n count++\n idx++\n }\n if (span < MIN_BUCKET_SPAN) break // skip a tiny trailing window\n const fps = count / (span / 1000)\n series.push({ at: bStart + span / 2, fps })\n if (fps < minFps) minFps = fps\n }\n if (series.length === 0) return null\n return { series, minFps, longestFrameMs, droppedFrames }\n}\n\nexport interface FrameCollector extends Collector {\n /** Attach the captured frame timestamps to the result. Returns the input\n * untouched when too few frames were seen (or rAF was unavailable). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records requestAnimationFrame timestamps for the duration of a recording so\n * the UI can chart frame rate and surface jank. Emits no signals — the\n * timestamps are a side track attached at finalize. No-ops when\n * requestAnimationFrame is unavailable (non-DOM environments).\n */\nexport function createFrameCollector(): FrameCollector {\n let active = false\n let rafId: number | null = null\n let frames: number[] = []\n\n function loop(t: number): void {\n if (!active) return\n frames.push(t)\n if (frames.length > MAX_FRAMES) frames.splice(0, frames.length - MAX_FRAMES)\n rafId = requestAnimationFrame(loop)\n }\n\n return {\n kind: 'frame',\n activate() {\n if (typeof requestAnimationFrame === 'undefined') return\n active = true\n frames = []\n rafId = requestAnimationFrame(loop)\n },\n deactivate() {\n active = false\n if (rafId != null && typeof cancelAnimationFrame !== 'undefined') {\n try {\n cancelAnimationFrame(rafId)\n } catch {\n // ignore\n }\n }\n rafId = null\n },\n finalize(result) {\n if (frames.length < MIN_FRAMES) return result\n return { ...result, frames: frames.slice() }\n },\n }\n}\n","import type { Collector, LongTaskAttribution, RecordingResult, Signal, StackFrame } from '../types'\n\n/**\n * JS Self-Profiling API trace shape (the subset we consume).\n * @see https://wicg.github.io/js-self-profiling/\n */\nexport interface ProfilerFrame {\n name?: string\n resourceId?: number\n line?: number\n column?: number\n}\nexport interface ProfilerStack {\n frameId: number\n parentId?: number\n}\nexport interface ProfilerSample {\n /** DOMHighResTimeStamp, same clock as performance.now() / entry.startTime. */\n timestamp: number\n stackId?: number\n}\nexport interface ProfilerTrace {\n resources: string[]\n frames: ProfilerFrame[]\n stacks: ProfilerStack[]\n samples: ProfilerSample[]\n}\n\ninterface ProfilerInstance {\n stop(): Promise<ProfilerTrace>\n}\ninterface ProfilerCtor {\n new (opts: { sampleInterval: number; maxBufferSize: number }): ProfilerInstance\n}\n\n/** Default sampling cadence. The browser may coarsen this. */\nconst SAMPLE_INTERVAL_MS = 10\nconst MAX_BUFFER_SIZE = 100_000\n/** Keep the noisiest few; deeper tails rarely help the developer. */\nconst MAX_FRAMES_PER_TASK = 5\n\n/**\n * Whether a resource URL belongs to the developer's own source (vs. a\n * dependency or tooling shim). Dependency frames are noise when the question\n * is \"which of MY functions is slow\".\n */\nexport function isUserResource(url: string | undefined): boolean {\n if (!url) return false\n if (url.includes('/node_modules/')) return false\n // Vite/dev tooling virtual modules: /@vite/client, /@react-refresh, /@id/...\n try {\n const path = new URL(url).pathname\n if (path.startsWith('/@')) return false\n } catch {\n if (url.startsWith('/@')) return false\n }\n return true\n}\n\nfunction frameToStackFrame(trace: ProfilerTrace, frame: ProfilerFrame): StackFrame {\n const file = frame.resourceId != null ? (trace.resources[frame.resourceId] ?? '') : ''\n const sf: StackFrame = {\n file,\n line: frame.line ?? 0,\n col: frame.column ?? 0,\n }\n if (frame.name) sf.fnName = frame.name\n return sf\n}\n\n/**\n * Climb a sample's stack from the leaf toward the root, returning the first\n * (deepest) frame that lives in user source. That frame is where the\n * developer's own code was actually executing when the sample was taken.\n */\nfunction leafUserFrame(trace: ProfilerTrace, stackId: number | undefined): ProfilerFrame | null {\n let id = stackId\n let guard = 0\n while (id != null && guard++ < 1000) {\n const stack = trace.stacks[id]\n if (!stack) break\n const frame = trace.frames[stack.frameId]\n if (frame && isUserResource(trace.resources[frame.resourceId ?? -1])) {\n return frame\n }\n id = stack.parentId\n }\n return null\n}\n\n/**\n * Aggregate the hottest user-source frames among samples whose timestamp\n * falls in [start, end]. `selfRatio` is relative to ALL in-window samples\n * (including vendor-only ones), so it reflects the share of the task's\n * blocking time spent in that user function.\n */\nexport function attributeWindow(\n trace: ProfilerTrace,\n start: number,\n end: number\n): LongTaskAttribution[] {\n let total = 0\n const counts = new Map<string, { frame: StackFrame; count: number }>()\n for (const sample of trace.samples) {\n if (sample.timestamp < start || sample.timestamp > end) continue\n total++\n const frame = leafUserFrame(trace, sample.stackId)\n if (!frame) continue\n const sf = frameToStackFrame(trace, frame)\n const key = `${sf.file}:${sf.line}:${sf.col}:${sf.fnName ?? ''}`\n const entry = counts.get(key)\n if (entry) entry.count++\n else counts.set(key, { frame: sf, count: 1 })\n }\n if (total === 0) return []\n return [...counts.values()]\n .sort((a, b) => b.count - a.count)\n .slice(0, MAX_FRAMES_PER_TASK)\n .map(({ frame, count }) => ({ frame, selfRatio: count / total, sampleCount: count }))\n}\n\n/**\n * Return a copy of `signals` with each long-task signal enriched with the\n * hottest user frames sampled during its window. Long tasks with no in-window\n * user samples are left without `attribution`. Non-long-task signals pass\n * through by reference.\n */\nexport function attributeLongTaskSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'long-task') return signal\n const attribution = attributeWindow(trace, signal.at, signal.at + signal.duration)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\n/**\n * Like {@link attributeLongTaskSignals} but for interactions: attributes the\n * *processing* window (handlers running, `[at+inputDelay, +processing]`) to the\n * developer's hot functions — answering \"which of my code made this click\n * slow\". Input delay and presentation aren't JS-on-the-stack, so they're\n * excluded from the window.\n */\nexport function attributeInteractionSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'interaction') return signal\n const start = signal.at + signal.inputDelay\n const attribution = attributeWindow(trace, start, start + signal.processing)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\ninterface SelfProfilingCollector extends Collector {\n /** Stop the profiler (if running), await its trace, and return a result\n * with long-task signals enriched. Falls back to the input on any failure\n * or when the Profiler API / Document-Policy header is unavailable. */\n finalize(result: RecordingResult): Promise<RecordingResult>\n}\n\n/**\n * Collector that runs the JS Self-Profiling API across a recording and, on\n * finalize, attributes each long task to the developer's own hot functions —\n * something LoAF can't do for React-delegated events (it only sees React's\n * single root dispatcher).\n *\n * It reports `kind: 'long-task'` because it enriches that signal rather than\n * emitting its own. Requires Chromium + a `Document-Policy: js-profiling`\n * response header (the dev plugins inject it); degrades to a no-op otherwise.\n */\nexport function createSelfProfilingCollector(): SelfProfilingCollector {\n let profiler: ProfilerInstance | null = null\n let tracePromise: Promise<ProfilerTrace> | null = null\n\n return {\n kind: 'long-task',\n activate() {\n tracePromise = null\n const Ctor = (globalThis as { Profiler?: ProfilerCtor }).Profiler\n if (typeof Ctor !== 'function') return\n try {\n profiler = new Ctor({ sampleInterval: SAMPLE_INTERVAL_MS, maxBufferSize: MAX_BUFFER_SIZE })\n } catch (err) {\n // Thrown when the Document-Policy: js-profiling header is absent.\n console.warn(\n '[react-perfscope] self-profiling unavailable (needs Document-Policy: js-profiling header); long tasks keep LoAF-only attribution:',\n err\n )\n profiler = null\n }\n },\n deactivate() {\n if (!profiler) return\n try {\n tracePromise = profiler.stop()\n } catch (err) {\n console.warn('[react-perfscope] self-profiling stop failed:', err)\n tracePromise = null\n }\n profiler = null\n },\n async finalize(result: RecordingResult): Promise<RecordingResult> {\n if (!tracePromise) return result\n try {\n const trace = await tracePromise\n const signals = attributeInteractionSignals(trace, attributeLongTaskSignals(trace, result.signals))\n return { ...result, signals }\n } catch (err) {\n console.warn('[react-perfscope] self-profiling finalize failed:', err)\n return result\n } finally {\n tracePromise = null\n }\n },\n }\n}\n"],"mappings":";AAEA,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AAQ,MAAM;AACpB,cAAM,UAAU,4BAA4B,OAAO,yBAAyB,OAAO,OAAO,OAAO,CAAC;AAClG,eAAO,EAAE,GAAG,QAAQ,QAAQ;AAAA,MAC9B,SAAS,KAAK;AACZ,gBAAQ,KAAK,qDAAqD,GAAG;AACrE,eAAO;AAAA,MACT,UAAE;AACA,uBAAe;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACF;","names":["SAMPLE_INTERVAL_MS"]}
|
|
1
|
+
{"version":3,"sources":["../src/recorder.ts","../src/sourcemap.ts","../src/self-requests.ts","../src/collectors/long-tasks.ts","../src/collectors/forced-reflow.ts","../src/collectors/layout-shift.ts","../src/collectors/network.ts","../src/collectors/web-vitals.ts","../src/collectors/heap.ts","../src/collectors/interaction.ts","../src/collectors/frames.ts","../src/collectors/self-profiling.ts"],"sourcesContent":["import type { Collector, Recorder, RecordingResult, Signal } from './types'\n\nconst BUFFER_CAP = 10_000\n\nexport interface InternalRecorder extends Recorder {\n __push: (signal: Signal) => void\n}\n\nexport function createRecorder(): Recorder {\n let recording = false\n let startedAt = 0\n let buffer: Signal[] = []\n const subscribers = new Set<(s: Signal) => void>()\n const collectors: Collector[] = []\n\n function notify(signal: Signal) {\n for (const cb of subscribers) {\n try {\n cb(signal)\n } catch (err) {\n console.warn('[react-perfscope] subscriber threw:', err)\n }\n }\n }\n\n function push(signal: Signal) {\n if (!recording) return\n buffer.push(signal)\n if (buffer.length > BUFFER_CAP) {\n buffer.splice(0, buffer.length - BUFFER_CAP)\n }\n notify(signal)\n }\n\n const recorder: InternalRecorder = {\n start() {\n if (recording) return\n recording = true\n startedAt = performance.now()\n buffer = []\n for (const c of collectors) {\n try {\n c.activate(push)\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to activate:`, err)\n }\n }\n },\n stop(): RecordingResult {\n if (!recording) {\n return { signals: [], startedAt: 0, duration: 0 }\n }\n for (const c of collectors) {\n try {\n c.deactivate()\n } catch (err) {\n console.warn(`[react-perfscope] collector ${c.kind} failed to deactivate:`, err)\n }\n }\n const duration = performance.now() - startedAt\n const result: RecordingResult = {\n signals: buffer.slice(),\n startedAt,\n duration,\n }\n recording = false\n buffer = []\n return result\n },\n isRecording() {\n return recording\n },\n onSignal(cb) {\n subscribers.add(cb)\n return () => subscribers.delete(cb)\n },\n use(collector) {\n collectors.push(collector)\n },\n __push: push,\n }\n return recorder\n}\n","import { TraceMap, originalPositionFor, type SourceMapInput } from '@jridgewell/trace-mapping'\nimport type { StackFrame } from './types'\nimport { markSelfRequest } from './self-requests'\n\nconst CHROME_FRAME = /^\\s*at\\s+(?:(.+?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?$/\nconst FIREFOX_FRAME = /^(.*?)@(.+?):(\\d+):(\\d+)$/\n\n/** A parsed source map (the JSON object), as returned by a FetchMap. */\nexport type RawSourceMap = SourceMapInput\n\nexport type FetchMap = (file: string) => Promise<RawSourceMap | null>\n\nexport async function resolveFrame(\n frame: StackFrame,\n fetchMap: FetchMap\n): Promise<StackFrame> {\n try {\n const map = await fetchMap(frame.file)\n if (!map) return frame\n // trace-mapping is pure JS (no wasm), so this works in the browser where\n // Mozilla's source-map SourceMapConsumer needs an explicitly-initialized\n // mappings.wasm. Columns are 0-based here, matching the captured frames.\n const tracer = new TraceMap(map)\n const pos = originalPositionFor(tracer, { line: frame.line, column: frame.col })\n if (pos.source == null || pos.line == null || pos.column == null) {\n return frame\n }\n const resolved: StackFrame = {\n file: pos.source,\n line: pos.line,\n col: pos.column,\n }\n if (pos.name) resolved.fnName = pos.name\n else if (frame.fnName) resolved.fnName = frame.fnName\n return resolved\n } catch (err) {\n console.warn('[react-perfscope] resolveFrame failed:', err)\n return frame\n }\n}\n\n/**\n * Attach a lazy `stack` getter to `target` that parses `raw` on first access\n * and memoizes the result. Use this from collectors to defer parseStack cost\n * until a consumer actually reads `signal.stack`.\n *\n * `skipTopFrames` drops the leading N parsed frames — useful for collectors\n * that wrap a patched function (the wrapper itself shows up as the topmost\n * frame, but it's noise from the user's perspective).\n */\nexport function attachLazyStack(\n target: object,\n raw: string | undefined,\n skipTopFrames = 0\n): void {\n let cached: StackFrame[] | null = null\n Object.defineProperty(target, 'stack', {\n enumerable: true,\n configurable: true,\n get() {\n if (cached === null) {\n const all = parseStack(raw)\n cached = skipTopFrames > 0 ? all.slice(skipTopFrames) : all\n }\n return cached\n },\n })\n}\n\nexport interface SourceMapResolver {\n /** Resolve a parsed StackFrame to its original source position. Falls back to the input frame on any failure. */\n resolve(frame: StackFrame): Promise<StackFrame>\n}\n\nexport interface CreateSourceMapResolverOptions {\n /** Override the global fetch. Useful for tests and non-browser environments. */\n fetch?: typeof globalThis.fetch\n}\n\n/**\n * Create a SourceMap resolver that fetches `.map` files from the live URL\n * referenced in each source file's `//# sourceMappingURL=` directive.\n * Caches the parsed source map per source URL so repeated resolves against\n * the same file are O(1) after the first.\n *\n * Returns the input frame on any failure (network error, missing map, etc.).\n */\nexport function createSourceMapResolver(opts: CreateSourceMapResolverOptions = {}): SourceMapResolver {\n const f = opts.fetch ?? (typeof fetch !== 'undefined' ? fetch.bind(globalThis) : null)\n const cache = new Map<string, Promise<RawSourceMap | null>>()\n\n function fetchMapFor(sourceUrl: string): Promise<RawSourceMap | null> {\n if (!f) return Promise.resolve(null)\n const existing = cache.get(sourceUrl)\n if (existing) return existing\n const promise = (async () => {\n try {\n markSelfRequest(sourceUrl)\n const res = await f(sourceUrl)\n if (!res || !res.ok) return null\n const text = await res.text()\n const m = text.match(/\\/\\/[#@]\\s*sourceMappingURL=(.+?)\\s*$/m)\n if (!m) return null\n const ref = m[1]!.trim()\n if (ref.startsWith('data:')) {\n const commaIdx = ref.indexOf(',')\n if (commaIdx === -1) return null\n const header = ref.slice(0, commaIdx)\n const payload = ref.slice(commaIdx + 1)\n const decoded = header.includes('base64')\n ? typeof atob === 'function'\n ? atob(payload)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n : (globalThis as any).Buffer.from(payload, 'base64').toString('utf8')\n : decodeURIComponent(payload)\n return JSON.parse(decoded) as RawSourceMap\n }\n const mapUrl = new URL(ref, sourceUrl).href\n markSelfRequest(mapUrl)\n const mapRes = await f(mapUrl)\n if (!mapRes || !mapRes.ok) return null\n return (await mapRes.json()) as RawSourceMap\n } catch {\n return null\n }\n })()\n cache.set(sourceUrl, promise)\n return promise\n }\n\n return {\n async resolve(frame) {\n try {\n return await resolveFrame(frame, fetchMapFor)\n } catch {\n return frame\n }\n },\n }\n}\n\nexport function parseStack(raw: string | undefined): StackFrame[] {\n if (!raw) return []\n const frames: StackFrame[] = []\n for (const line of raw.split('\\n')) {\n const chromeMatch = line.match(CHROME_FRAME)\n if (chromeMatch) {\n const [, fnName, file, lineStr, colStr] = chromeMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n continue\n }\n const firefoxMatch = line.match(FIREFOX_FRAME)\n if (firefoxMatch) {\n const [, fnName, file, lineStr, colStr] = firefoxMatch\n const frame: StackFrame = {\n file: file ?? '',\n line: Number(lineStr),\n col: Number(colStr),\n }\n if (fnName) frame.fnName = fnName\n frames.push(frame)\n }\n }\n return frames\n}\n","// Registry of URLs that react-perfscope itself fetched (source files and their\n// source maps, when resolving stack frames). The network collector consults\n// this so the tool's own traffic never shows up as one of the app's network\n// signals — measuring shouldn't report the measurer.\n\nconst selfRequests = new Set<string>()\n\n/** Record that react-perfscope is about to fetch `url`, so the network\n * collector can exclude its resource-timing entry. */\nexport function markSelfRequest(url: string): void {\n selfRequests.add(url)\n}\n\n/** True when `url` was fetched by react-perfscope itself. */\nexport function isSelfRequest(url: string): boolean {\n return selfRequests.has(url)\n}\n","import type { Collector, LongTaskScript, Signal } from '../types'\n\nconst LOAF = 'long-animation-frame'\nconst LEGACY = 'longtask'\n\n/** A single script entry inside a Long Animation Frame. */\ninterface ScriptTiming {\n duration?: number\n invoker?: string\n invokerType?: string\n sourceURL?: string\n sourceFunctionName?: string\n sourceCharPosition?: number\n}\n\ninterface LoAFEntry extends PerformanceEntry {\n blockingDuration?: number\n scripts?: ScriptTiming[]\n}\n\nfunction supportsLoAF(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n return Array.isArray(types) && types.includes(LOAF)\n}\n\nfunction mapScripts(scripts: ScriptTiming[]): LongTaskScript[] {\n return scripts.map((s) => ({\n invokerType: s.invokerType ?? 'unknown',\n invoker: s.invoker ?? '',\n sourceURL: s.sourceURL ?? '',\n sourceFunctionName: s.sourceFunctionName ?? '',\n charPosition: typeof s.sourceCharPosition === 'number' ? s.sourceCharPosition : -1,\n duration: typeof s.duration === 'number' ? s.duration : 0,\n }))\n}\n\nexport function createLongTasksCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'long-task',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; long-tasks disabled')\n return\n }\n active = true\n const useLoAF = supportsLoAF()\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const entry of list.getEntries()) {\n if (useLoAF) {\n const loaf = entry as LoAFEntry\n const scripts = Array.isArray(loaf.scripts) ? mapScripts(loaf.scripts) : []\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n scripts,\n ...(typeof loaf.blockingDuration === 'number'\n ? { blockingDuration: loaf.blockingDuration }\n : {}),\n })\n } else {\n emit({\n kind: 'long-task',\n at: entry.startTime,\n duration: entry.duration,\n stack: [],\n })\n }\n }\n })\n observer.observe({ type: useLoAF ? LOAF : LEGACY, buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] long-tasks collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\nimport { attachLazyStack } from '../sourcemap'\n\nconst LAYOUT_GETTERS = [\n 'offsetWidth',\n 'offsetHeight',\n 'offsetLeft',\n 'offsetTop',\n 'clientWidth',\n 'clientHeight',\n 'scrollWidth',\n 'scrollHeight',\n] as const\n\nconst LAYOUT_METHODS = ['getBoundingClientRect', 'getClientRects'] as const\n\ntype SavedDescriptor = {\n proto: object\n key: string\n descriptor: PropertyDescriptor\n}\n\ntype OpenGroup = {\n at: number\n duration: number\n count: number\n rawStack: string | undefined\n}\n\n// Close the coalescing window at the end of the current synchronous turn.\n// queueMicrotask runs after the running task drains, so a layout-thrash loop\n// (read offsetWidth N times in one turn) collapses into a single group.\nconst scheduleFlush: (cb: () => void) => void =\n typeof queueMicrotask === 'function'\n ? queueMicrotask\n : typeof Promise !== 'undefined'\n ? (cb) => {\n Promise.resolve().then(cb)\n }\n : (cb) => cb()\n\nexport function createForcedReflowCollector(): Collector {\n let active = false\n let emit: (s: Signal) => void = () => {}\n const saved: SavedDescriptor[] = []\n let mutationObserver: MutationObserver | null = null\n let group: OpenGroup | null = null\n\n function consumePendingMutations(): boolean {\n if (!mutationObserver) {\n // Fallback when MutationObserver isn't available: always treat as dirty\n // (Phase 1 over-report behavior).\n return true\n }\n return mutationObserver.takeRecords().length > 0\n }\n\n function flush() {\n if (!group) return\n const g = group\n group = null\n const signal = {\n kind: 'forced-reflow' as const,\n at: g.at,\n duration: g.duration,\n count: g.count,\n } as unknown as Signal\n attachLazyStack(signal, g.rawStack, 1)\n emit(signal)\n }\n\n // A layout read happened while recording and layout was dirty. Open a group\n // on the first such read of the turn, then just accumulate count/duration for\n // the rest of the turn. `rawStack` is captured by the caller (the patched\n // accessor) so the stack's top user frame stays at a fixed depth — passing it\n // through a helper would add a frame and misattribute the reflow to this file.\n function record(at: number, duration: number, rawStack: string | undefined) {\n if (group) {\n group.count++\n group.duration += duration\n return\n }\n group = { at, duration, count: 1, rawStack }\n scheduleFlush(flush)\n }\n\n // True when the next dirty read opens a fresh group and so needs a stack.\n // Lets the accessor skip `new Error().stack` (the dominant cost) on the\n // subsequent reads it coalesces into an already-open group.\n function needsStack(): boolean {\n return group === null\n }\n\n function patchGetter(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || !desc.get) return\n saved.push({ proto, key, descriptor: desc })\n const originalGet = desc.get\n Object.defineProperty(proto, key, {\n configurable: true,\n get(this: unknown) {\n if (active) {\n if (!consumePendingMutations()) {\n return originalGet.call(this)\n }\n const rawStack = needsStack() ? new Error().stack : undefined\n const at = performance.now()\n const value = originalGet.call(this)\n record(at, performance.now() - at, rawStack)\n return value\n }\n return originalGet.call(this)\n },\n set: desc.set,\n })\n }\n\n function patchMethod(proto: object, key: string) {\n if (typeof proto !== 'object' || proto === null) return\n const desc = Object.getOwnPropertyDescriptor(proto, key)\n if (!desc || typeof desc.value !== 'function') return\n saved.push({ proto, key, descriptor: desc })\n const original = desc.value as (...args: unknown[]) => unknown\n Object.defineProperty(proto, key, {\n configurable: true,\n writable: true,\n value: function patchedLayoutMethod(this: unknown, ...args: unknown[]) {\n if (active) {\n if (!consumePendingMutations()) {\n return original.apply(this, args)\n }\n const rawStack = needsStack() ? new Error().stack : undefined\n const at = performance.now()\n const value = original.apply(this, args)\n record(at, performance.now() - at, rawStack)\n return value\n }\n return original.apply(this, args)\n },\n })\n }\n\n return {\n kind: 'forced-reflow',\n activate(emitFn) {\n if (active) return\n emit = emitFn\n active = true\n\n if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {\n try {\n mutationObserver = new MutationObserver(() => {})\n mutationObserver.observe(document, {\n attributes: true,\n childList: true,\n subtree: true,\n characterData: true,\n })\n } catch (err) {\n console.warn('[react-perfscope] forced-reflow MutationObserver failed:', err)\n mutationObserver = null\n }\n }\n\n if (typeof HTMLElement !== 'undefined') {\n for (const key of LAYOUT_GETTERS) {\n patchGetter(HTMLElement.prototype, key)\n }\n }\n if (typeof Element !== 'undefined') {\n for (const key of LAYOUT_METHODS) {\n patchMethod(Element.prototype, key)\n }\n }\n },\n deactivate() {\n if (!active) return\n active = false\n // Emit any group still open before the scheduled microtask runs, so the\n // last burst isn't lost when stop() is called mid-turn.\n flush()\n if (mutationObserver) {\n try {\n mutationObserver.disconnect()\n } catch {\n // ignore\n }\n mutationObserver = null\n }\n for (const { proto, key, descriptor } of saved) {\n Object.defineProperty(proto, key, descriptor)\n }\n saved.length = 0\n },\n }\n}\n","import type { Collector, Signal } from '../types'\n\ninterface LayoutShiftSource {\n currentRect: DOMRect\n previousRect?: DOMRect\n node?: Node | null\n}\n\ninterface LayoutShiftEntryLike extends PerformanceEntry {\n value: number\n hadRecentInput: boolean\n sources?: LayoutShiftSource[]\n}\n\nconst PERFSCOPE_HOST_ATTR = 'data-perfscope-host'\n\nfunction rectsOverlap(a: DOMRect, b: DOMRect, tolerance = 0): boolean {\n return !(\n a.x + a.width < b.x - tolerance ||\n b.x + b.width < a.x - tolerance ||\n a.y + a.height < b.y - tolerance ||\n b.y + b.height < a.y - tolerance\n )\n}\n\n/**\n * Returns true when every source in the entry is part of our floating\n * widget. We want to ignore shifts caused by the perfscope UI itself.\n *\n * Detection has two paths:\n * 1. Node-based: walk up `source.node` looking for `[data-perfscope-host]`.\n * Works when the node is in light DOM.\n * 2. Rect-based fallback: compare `source.currentRect` against every host\n * element's bounding rect. This catches the Shadow-DOM case where the\n * browser doesn't expose the inner node (Shadow root boundary).\n */\nfunction collectPerfscopeRects(): DOMRect[] {\n const hosts = Array.from(document.querySelectorAll(`[${PERFSCOPE_HOST_ATTR}]`))\n const rects: DOMRect[] = []\n for (const h of hosts) {\n // The light-DOM host element usually has height 0 because Shadow DOM\n // content isn't part of its layout. We need to peek inside the shadow\n // root and collect bounds of any positioned children.\n const sr = (h as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot\n if (sr) {\n for (const child of Array.from(sr.children)) {\n const r = (child as Element).getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n } else {\n const r = h.getBoundingClientRect()\n if (r.width > 0 && r.height > 0) rects.push(r)\n }\n }\n return rects\n}\n\nfunction entryIsOnlyFromPerfscope(sources: LayoutShiftSource[]): boolean {\n if (sources.length === 0) return false\n if (typeof document === 'undefined') return false\n\n const hostRects = collectPerfscopeRects()\n if (hostRects.length === 0) return false\n\n for (const src of sources) {\n let matched = false\n const node = src.node as (Node & { closest?: (sel: string) => Element | null }) | null | undefined\n if (node) {\n // Node-based check\n if (typeof (node as { closest?: unknown }).closest === 'function') {\n if ((node as Element).closest(`[${PERFSCOPE_HOST_ATTR}]`)) matched = true\n } else {\n let parent: (Element | null) = (node as Node).parentElement as Element | null\n while (parent) {\n if (parent.hasAttribute(PERFSCOPE_HOST_ATTR)) { matched = true; break }\n parent = parent.parentElement\n }\n }\n }\n // Rect-based fallback (shadow DOM): if source rect overlaps any of our\n // host rects, consider it our widget. Tolerance covers the case where\n // the widget changes size during the shift (its previous/current bounds\n // differ but both sit in the same screen corner).\n if (!matched) {\n for (const hostRect of hostRects) {\n if (rectsOverlap(src.currentRect, hostRect, 24)) {\n matched = true\n break\n }\n }\n }\n if (!matched) return false\n }\n return true\n}\n\nexport function createLayoutShiftCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'layout-shift',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; layout-shift disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as LayoutShiftEntryLike\n // Note: production CLS metrics exclude shifts with hadRecentInput\n // (user-initiated movements are considered intentional). For a\n // dev tool, the user explicitly WANTS to see what their clicks\n // caused — so we report these too.\n const sources = entry.sources ?? []\n if (entryIsOnlyFromPerfscope(sources)) continue\n // Convert viewport-relative rects to document-relative coords so\n // overlays stay anchored to the shifted DOM position when the\n // user scrolls. Filter above runs first on viewport coords (our\n // widget is position:fixed, lives in viewport space).\n const sx = (typeof window !== 'undefined' && window.scrollX) || 0\n const sy = (typeof window !== 'undefined' && window.scrollY) || 0\n const toDocRect = (r: DOMRect) =>\n new DOMRect(r.x + sx, r.y + sy, r.width, r.height)\n const rects = sources.map((s) => toDocRect(s.currentRect))\n // previousRect is undefined when the element was newly inserted.\n // An \"empty\" rect (w=0, h=0) likewise means there was no prior\n // box — treat both as `null` so the overlay can decide not to\n // draw an arrow for these.\n const prevRects: (DOMRect | null)[] = sources.map((s) => {\n const pr = s.previousRect\n if (!pr) return null\n if (pr.width === 0 && pr.height === 0) return null\n return toDocRect(pr)\n })\n emit({\n kind: 'layout-shift',\n at: entry.startTime,\n value: entry.value,\n sources: rects,\n previousSources: prevRects,\n })\n }\n })\n observer.observe({ type: 'layout-shift', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] layout-shift collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import type { Collector, Signal } from '../types'\nimport { isSelfRequest } from '../self-requests'\n\ninterface ResourceTimingLike extends PerformanceEntry {\n transferSize?: number\n renderBlockingStatus?: 'blocking' | 'non-blocking'\n}\n\nexport function createNetworkCollector(): Collector {\n let observer: PerformanceObserver | null = null\n let active = false\n\n return {\n kind: 'network',\n activate(emit: (signal: Signal) => void) {\n if (typeof PerformanceObserver === 'undefined') {\n console.warn('[react-perfscope] PerformanceObserver not supported; network disabled')\n return\n }\n active = true\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const raw of list.getEntries()) {\n const entry = raw as ResourceTimingLike\n // Skip react-perfscope's own traffic (source-map fetches).\n if (isSelfRequest(entry.name)) continue\n emit({\n kind: 'network',\n url: entry.name,\n startedAt: entry.startTime,\n duration: entry.duration,\n size: entry.transferSize ?? 0,\n blocking: entry.renderBlockingStatus === 'blocking',\n })\n }\n })\n observer.observe({ type: 'resource', buffered: false })\n } catch (err) {\n console.warn('[react-perfscope] network collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n }\n}\n","import { onLCP, onINP, onCLS, onFCP, onTTFB, type Metric } from 'web-vitals'\nimport type { Collector, Signal, WebVitalSignal } from '../types'\n\ntype VitalName = WebVitalSignal['name']\n\nexport function createWebVitalsCollector(): Collector {\n let active = false\n let subscribed = false\n let emit: (signal: Signal) => void = () => {}\n\n function makeHandler(name: VitalName) {\n return (metric: Metric) => {\n if (!active) return\n emit({ kind: 'web-vital', name, value: metric.value })\n }\n }\n\n return {\n kind: 'web-vital',\n activate(emitFn) {\n emit = emitFn\n active = true\n if (subscribed) return\n try {\n onLCP(makeHandler('LCP'))\n onINP(makeHandler('INP'))\n onCLS(makeHandler('CLS'))\n onFCP(makeHandler('FCP'))\n onTTFB(makeHandler('TTFB'))\n subscribed = true\n } catch (err) {\n console.warn('[react-perfscope] web-vitals collector failed to subscribe:', err)\n active = false\n }\n },\n deactivate() {\n // The web-vitals library does not expose unsubscribe. We keep the\n // handlers attached and gate emission via `active`. Re-activating\n // updates `emit` without re-subscribing.\n active = false\n },\n }\n}\n","import type {\n Collector,\n HeapSample,\n HeapTrend,\n HeapTrendClass,\n RecordingResult,\n} from '../types'\n\n/** How often to read heap usage while recording. Reading performance.memory\n * is cheap, so we sample at 4Hz: a 1s cadence is too coarse — short spikes fall\n * between samples and the line, drawn straight between sparse points, smooths\n * them into a ramp. 250ms localizes spikes without meaningful overhead. */\nconst SAMPLE_INTERVAL_MS = 250\n/** Cap on retained samples so a multi-hour session can't grow the array\n * unbounded. At 250ms this is ~83 min; past that, oldest samples drop. */\nconst MAX_SAMPLES = 20_000\n\n/** Below this, a trend can't be estimated reliably. */\nconst MIN_SAMPLES = 4\n/** How many contiguous segments to split the series into when estimating the\n * floor. Each segment contributes its minimum (the post-GC trough). */\nconst FLOOR_SEGMENTS = 8\n\nconst MB = 1024 * 1024\n/** Floor-growth thresholds, in bytes per minute. */\nconst GROWING_SLOPE = 1 * MB\nconst LEAK_SLOPE = 5 * MB\n/** A rate alone isn't enough: over a short recording, a sub-megabyte wobble in\n * the floor extrapolates to a huge MB/min and would false-positive. Require the\n * floor to have actually risen by at least this much across the window before\n * calling anything growing/leaking. */\nconst MIN_NET_GROWTH = 2 * MB\n\ninterface MemoryInfo {\n usedJSHeapSize: number\n totalJSHeapSize: number\n jsHeapSizeLimit: number\n}\n\nfunction readMemory(): MemoryInfo | null {\n const perf = (globalThis as { performance?: { memory?: MemoryInfo } }).performance\n const mem = perf?.memory\n if (!mem || typeof mem.usedJSHeapSize !== 'number') return null\n return mem\n}\n\n/**\n * Least-squares slope of points (x, y). Returns 0 when x has no spread\n * (vertical / single distinct x) to avoid a divide-by-zero blow-up.\n */\nfunction slope(points: { x: number; y: number }[]): number {\n const n = points.length\n if (n < 2) return 0\n let sx = 0\n let sy = 0\n let sxy = 0\n let sxx = 0\n for (const { x, y } of points) {\n sx += x\n sy += y\n sxy += x * y\n sxx += x * x\n }\n const denom = n * sxx - sx * sx\n if (denom === 0) return 0\n return (n * sxy - sx * sy) / denom\n}\n\n/**\n * Estimate whether memory is being retained across the recording.\n *\n * GC makes raw heap usage a sawtooth, so the peak is noisy. The reliable\n * signal is the *floor* — the post-GC troughs. We split the series into\n * contiguous segments, take the minimum of each (its trough), and regress\n * those minima against time.\n *\n * A rising overall slope is necessary but NOT sufficient: a one-time step\n * (heap warms up early, then plateaus) also regresses to a positive slope, and\n * flagging that as a leak is a false positive — the classic \"idle recording\n * reads abnormal\" bug. A real leak keeps climbing, so we additionally require\n * the *recent* half of the floor to still be rising. We also gate on a minimum\n * net growth, since over a short window a sub-MB wobble extrapolates to a steep\n * per-minute slope.\n *\n * Returns null when there are too few samples to say anything.\n */\nexport function analyzeHeapTrend(samples: HeapSample[]): HeapTrend | null {\n if (samples.length < MIN_SAMPLES) return null\n const t0 = samples[0]!.at\n const segSize = Math.max(1, Math.ceil(samples.length / FLOOR_SEGMENTS))\n const floorPoints: { x: number; y: number }[] = []\n for (let i = 0; i < samples.length; i += segSize) {\n const seg = samples.slice(i, i + segSize)\n let min = Infinity\n for (const s of seg) min = Math.min(min, s.used)\n const mid = seg[Math.floor(seg.length / 2)]!\n floorPoints.push({ x: (mid.at - t0) / 60000, y: min })\n }\n const slopeBytesPerMin = slope(floorPoints)\n const spanMin = (samples[samples.length - 1]!.at - t0) / 60000\n const projectedGrowth = slopeBytesPerMin * spanMin\n // Recent trend: is the floor still climbing in the latter half? Distinguishes\n // a sustained leak from a one-time step that has since plateaued.\n const recent = floorPoints.slice(Math.floor(floorPoints.length / 2))\n const recentSlope = recent.length >= 2 ? slope(recent) : slopeBytesPerMin\n\n let classification: HeapTrendClass = 'stable'\n const sustained = projectedGrowth >= MIN_NET_GROWTH && recentSlope >= GROWING_SLOPE\n if (sustained) {\n classification =\n slopeBytesPerMin >= LEAK_SLOPE && recentSlope >= LEAK_SLOPE ? 'leak-suspected' : 'growing'\n }\n return { classification, slopeBytesPerMin }\n}\n\nexport interface HeapCollector extends Collector {\n /** Attach the sampled heap series to the recording result. Returns the\n * input untouched when nothing was sampled (unsupported browser). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Samples `performance.memory` on an interval for the duration of a recording\n * and attaches the series via `finalize`. It is a Collector so the recorder\n * drives its start/stop, but it emits no signals — the series is a separate\n * track (see RecordingResult.heapSamples), so a busy session's signal buffer\n * can't evict it. No-ops entirely when performance.memory is unavailable\n * (non-Chromium), leaving `heapSamples` absent so the UI can show a fallback.\n */\nexport function createHeapCollector(): HeapCollector {\n let samples: HeapSample[] = []\n let timer: ReturnType<typeof setInterval> | null = null\n\n function sample(): void {\n const mem = readMemory()\n if (!mem) return\n samples.push({ at: performance.now(), used: mem.usedJSHeapSize, total: mem.totalJSHeapSize })\n if (samples.length > MAX_SAMPLES) samples.splice(0, samples.length - MAX_SAMPLES)\n }\n\n return {\n kind: 'heap',\n activate() {\n samples = []\n if (!readMemory()) return // unsupported → never start the timer\n sample()\n timer = setInterval(sample, SAMPLE_INTERVAL_MS)\n },\n deactivate() {\n if (timer == null) return\n clearInterval(timer)\n timer = null\n sample() // one final reading at stop\n },\n finalize(result) {\n if (samples.length === 0) return result\n return { ...result, heapSamples: samples.slice() }\n },\n }\n}\n","import type { Collector, InteractionSignal, RecordingResult } from '../types'\n\n/** Event Timing only surfaces events at/over this duration (ms); 40ms keeps\n * trivial interactions out while still catching anything a user would feel. */\nconst DURATION_THRESHOLD = 40\n\ninterface EventTimingEntry extends PerformanceEntry {\n processingStart: number\n processingEnd: number\n interactionId?: number\n target?: unknown\n}\n\nfunction selectorFor(target: unknown): string | undefined {\n const el = target as { tagName?: string; id?: string; className?: unknown } | null\n if (!el || typeof el.tagName !== 'string') return undefined\n let s = el.tagName.toLowerCase()\n if (el.id) s += `#${el.id}`\n else if (typeof el.className === 'string' && el.className.trim()) {\n s += `.${el.className.trim().split(/\\s+/)[0]}`\n }\n return s\n}\n\nfunction supportsEventTiming(): boolean {\n const PO = (globalThis as { PerformanceObserver?: { supportedEntryTypes?: readonly string[] } })\n .PerformanceObserver\n const types = PO?.supportedEntryTypes\n // happy-dom / older browsers may not expose supportedEntryTypes; if the\n // observer exists at all we still try, and observe() throwing is caught.\n return !types || types.includes('event')\n}\n\nexport interface InteractionCollector extends Collector {\n /** Group buffered Event Timing entries into one interaction each and append\n * them to the result. Returns the input untouched when none qualified. */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records Event Timing entries during a recording and, on finalize, turns each\n * user interaction (grouped by interactionId) into one signal carrying the INP\n * latency breakdown: input delay → processing → presentation. The longest\n * event in a group defines the interaction's latency (matching how INP is\n * attributed). Emits no live signals — interactions are assembled at finalize,\n * then the self-profiling collector attributes the processing window to the\n * developer's hot functions.\n */\nexport function createInteractionCollector(): InteractionCollector {\n let active = false\n let observer: PerformanceObserver | null = null\n let entries: EventTimingEntry[] = []\n\n return {\n kind: 'interaction',\n activate() {\n if (typeof PerformanceObserver === 'undefined' || !supportsEventTiming()) return\n active = true\n entries = []\n try {\n observer = new PerformanceObserver((list) => {\n if (!active) return\n for (const e of list.getEntries()) entries.push(e as EventTimingEntry)\n })\n // `event` covers all interaction events; `first-input` guarantees the\n // first one even if it's under the duration threshold.\n observer.observe({ type: 'event', buffered: false, durationThreshold: DURATION_THRESHOLD } as PerformanceObserverInit)\n try {\n observer.observe({ type: 'first-input', buffered: false } as PerformanceObserverInit)\n } catch {\n // first-input not supported everywhere; the event stream is enough.\n }\n } catch (err) {\n console.warn('[react-perfscope] interaction collector failed to start:', err)\n observer = null\n active = false\n }\n },\n deactivate() {\n active = false\n if (observer) {\n try {\n observer.disconnect()\n } catch {\n // ignore\n }\n observer = null\n }\n },\n finalize(result) {\n const byId = new Map<number, EventTimingEntry[]>()\n for (const e of entries) {\n const id = e.interactionId\n if (!id) continue // 0 / undefined → not part of a discrete interaction\n const group = byId.get(id)\n if (group) group.push(e)\n else byId.set(id, [e])\n }\n const interactions: InteractionSignal[] = []\n for (const group of byId.values()) {\n // All events of one interaction (pointerdown/up/click) report the same\n // `duration` (the whole interaction latency), so the breakdown can't\n // come from a single event. Span the processing across the group:\n // earliest processingStart → latest processingEnd (matches web-vitals).\n // The \"defining\" event for label/target is the one with the most\n // processing — typically the click/keydown that actually ran handlers.\n let duration = 0\n let startTime = Infinity\n let processingStart = Infinity\n let processingEnd = -Infinity\n let defining = group[0]!\n let maxProcessing = -Infinity\n for (const e of group) {\n if (e.duration > duration) duration = e.duration\n if (e.startTime < startTime) startTime = e.startTime\n if (e.processingStart < processingStart) processingStart = e.processingStart\n if (e.processingEnd > processingEnd) processingEnd = e.processingEnd\n const proc = e.processingEnd - e.processingStart\n if (proc > maxProcessing) {\n maxProcessing = proc\n defining = e\n }\n }\n if (duration < DURATION_THRESHOLD) continue\n const inputDelay = Math.max(0, processingStart - startTime)\n const processing = Math.max(0, processingEnd - processingStart)\n const presentation = Math.max(0, startTime + duration - processingEnd)\n interactions.push({\n kind: 'interaction',\n at: startTime,\n eventType: defining.name,\n ...(selectorFor(defining.target) ? { target: selectorFor(defining.target) } : {}),\n duration,\n inputDelay,\n processing,\n presentation,\n })\n }\n if (interactions.length === 0) return result\n interactions.sort((a, b) => a.at - b.at)\n return { ...result, signals: [...result.signals, ...interactions] }\n },\n }\n}\n","import type { Collector, FpsSample, FrameStats, RecordingResult } from '../types'\n\n/** 60fps frame budget (ms). Gaps are scored against this to count drops. */\nconst FRAME_BUDGET = 1000 / 60\n/** Window for the FPS series; 500ms smooths per-frame noise while still showing\n * a scroll-jank dip. */\nconst BUCKET_MS = 500\n/** A trailing window shorter than this is too small to estimate FPS reliably. */\nconst MIN_BUCKET_SPAN = 100\n/** Below this we can't say anything useful. */\nconst MIN_FRAMES = 8\n/** Cap retained frames so a long session can't grow the array unbounded\n * (~5.5 min at 60fps); past that, oldest drop. */\nconst MAX_FRAMES = 20_000\n\n/**\n * Turn raw requestAnimationFrame timestamps into a frame-rate picture:\n * a windowed FPS series, the lowest sustained FPS, the worst single hitch,\n * and an approximate dropped-frame count. Long tasks (>50ms) show up here as\n * big gaps, but so does sustained scroll jank (30–50ms frames) that the\n * long-task collector's threshold misses.\n *\n * Returns null when there are too few frames to analyze.\n */\nexport function analyzeFrames(frames: number[]): FrameStats | null {\n if (frames.length < MIN_FRAMES) return null\n\n let longestFrameMs = 0\n let droppedFrames = 0\n for (let i = 1; i < frames.length; i++) {\n const gap = frames[i]! - frames[i - 1]!\n if (gap > longestFrameMs) longestFrameMs = gap\n const dropped = Math.round(gap / FRAME_BUDGET) - 1\n if (dropped > 0) droppedFrames += dropped\n }\n\n const t0 = frames[0]!\n const end = frames[frames.length - 1]!\n const series: FpsSample[] = []\n let minFps = Infinity\n let idx = 0\n for (let bStart = t0; bStart < end; bStart += BUCKET_MS) {\n const bEnd = Math.min(bStart + BUCKET_MS, end)\n const span = bEnd - bStart\n let count = 0\n while (idx < frames.length && frames[idx]! < bEnd) {\n count++\n idx++\n }\n if (span < MIN_BUCKET_SPAN) break // skip a tiny trailing window\n const fps = count / (span / 1000)\n series.push({ at: bStart + span / 2, fps })\n if (fps < minFps) minFps = fps\n }\n if (series.length === 0) return null\n return { series, minFps, longestFrameMs, droppedFrames }\n}\n\nexport interface FrameCollector extends Collector {\n /** Attach the captured frame timestamps to the result. Returns the input\n * untouched when too few frames were seen (or rAF was unavailable). */\n finalize(result: RecordingResult): RecordingResult\n}\n\n/**\n * Records requestAnimationFrame timestamps for the duration of a recording so\n * the UI can chart frame rate and surface jank. Emits no signals — the\n * timestamps are a side track attached at finalize. No-ops when\n * requestAnimationFrame is unavailable (non-DOM environments).\n */\nexport function createFrameCollector(): FrameCollector {\n let active = false\n let rafId: number | null = null\n let frames: number[] = []\n\n function loop(t: number): void {\n if (!active) return\n frames.push(t)\n if (frames.length > MAX_FRAMES) frames.splice(0, frames.length - MAX_FRAMES)\n rafId = requestAnimationFrame(loop)\n }\n\n return {\n kind: 'frame',\n activate() {\n if (typeof requestAnimationFrame === 'undefined') return\n active = true\n frames = []\n rafId = requestAnimationFrame(loop)\n },\n deactivate() {\n active = false\n if (rafId != null && typeof cancelAnimationFrame !== 'undefined') {\n try {\n cancelAnimationFrame(rafId)\n } catch {\n // ignore\n }\n }\n rafId = null\n },\n finalize(result) {\n if (frames.length < MIN_FRAMES) return result\n return { ...result, frames: frames.slice() }\n },\n }\n}\n","import type { Collector, LongTaskAttribution, RecordingResult, Signal, StackFrame } from '../types'\n\n/**\n * JS Self-Profiling API trace shape (the subset we consume).\n * @see https://wicg.github.io/js-self-profiling/\n */\nexport interface ProfilerFrame {\n name?: string\n resourceId?: number\n line?: number\n column?: number\n}\nexport interface ProfilerStack {\n frameId: number\n parentId?: number\n}\nexport interface ProfilerSample {\n /** DOMHighResTimeStamp, same clock as performance.now() / entry.startTime. */\n timestamp: number\n stackId?: number\n}\nexport interface ProfilerTrace {\n resources: string[]\n frames: ProfilerFrame[]\n stacks: ProfilerStack[]\n samples: ProfilerSample[]\n}\n\ninterface ProfilerInstance {\n stop(): Promise<ProfilerTrace>\n}\ninterface ProfilerCtor {\n new (opts: { sampleInterval: number; maxBufferSize: number }): ProfilerInstance\n}\n\n/** Default sampling cadence. The browser may coarsen this. */\nconst SAMPLE_INTERVAL_MS = 10\nconst MAX_BUFFER_SIZE = 100_000\n/** Keep the noisiest few; deeper tails rarely help the developer. */\nconst MAX_FRAMES_PER_TASK = 5\n\n/**\n * Whether a resource URL belongs to the developer's own source (vs. a\n * dependency or tooling shim). Dependency frames are noise when the question\n * is \"which of MY functions is slow\".\n */\nexport function isUserResource(url: string | undefined): boolean {\n if (!url) return false\n if (url.includes('/node_modules/')) return false\n // Vite/dev tooling virtual modules: /@vite/client, /@react-refresh, /@id/...\n try {\n const path = new URL(url).pathname\n if (path.startsWith('/@')) return false\n } catch {\n if (url.startsWith('/@')) return false\n }\n return true\n}\n\nfunction frameToStackFrame(trace: ProfilerTrace, frame: ProfilerFrame): StackFrame {\n const file = frame.resourceId != null ? (trace.resources[frame.resourceId] ?? '') : ''\n const sf: StackFrame = {\n file,\n line: frame.line ?? 0,\n col: frame.column ?? 0,\n }\n if (frame.name) sf.fnName = frame.name\n return sf\n}\n\n/**\n * Climb a sample's stack from the leaf toward the root, returning the first\n * (deepest) frame that lives in user source. That frame is where the\n * developer's own code was actually executing when the sample was taken.\n */\nfunction leafUserFrame(trace: ProfilerTrace, stackId: number | undefined): ProfilerFrame | null {\n let id = stackId\n let guard = 0\n while (id != null && guard++ < 1000) {\n const stack = trace.stacks[id]\n if (!stack) break\n const frame = trace.frames[stack.frameId]\n if (frame && isUserResource(trace.resources[frame.resourceId ?? -1])) {\n return frame\n }\n id = stack.parentId\n }\n return null\n}\n\n/**\n * Aggregate the hottest user-source frames among samples whose timestamp\n * falls in [start, end]. `selfRatio` is relative to ALL in-window samples\n * (including vendor-only ones), so it reflects the share of the task's\n * blocking time spent in that user function.\n */\nexport function attributeWindow(\n trace: ProfilerTrace,\n start: number,\n end: number\n): LongTaskAttribution[] {\n let total = 0\n const counts = new Map<string, { frame: StackFrame; count: number }>()\n for (const sample of trace.samples) {\n if (sample.timestamp < start || sample.timestamp > end) continue\n total++\n const frame = leafUserFrame(trace, sample.stackId)\n if (!frame) continue\n const sf = frameToStackFrame(trace, frame)\n const key = `${sf.file}:${sf.line}:${sf.col}:${sf.fnName ?? ''}`\n const entry = counts.get(key)\n if (entry) entry.count++\n else counts.set(key, { frame: sf, count: 1 })\n }\n if (total === 0) return []\n return [...counts.values()]\n .sort((a, b) => b.count - a.count)\n .slice(0, MAX_FRAMES_PER_TASK)\n .map(({ frame, count }) => ({ frame, selfRatio: count / total, sampleCount: count }))\n}\n\n/**\n * Return a copy of `signals` with each long-task signal enriched with the\n * hottest user frames sampled during its window. Long tasks with no in-window\n * user samples are left without `attribution`. Non-long-task signals pass\n * through by reference.\n */\nexport function attributeLongTaskSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'long-task') return signal\n const attribution = attributeWindow(trace, signal.at, signal.at + signal.duration)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\n/**\n * Like {@link attributeLongTaskSignals} but for interactions: attributes the\n * *processing* window (handlers running, `[at+inputDelay, +processing]`) to the\n * developer's hot functions — answering \"which of my code made this click\n * slow\". Input delay and presentation aren't JS-on-the-stack, so they're\n * excluded from the window.\n */\nexport function attributeInteractionSignals(trace: ProfilerTrace, signals: Signal[]): Signal[] {\n return signals.map((signal) => {\n if (signal.kind !== 'interaction') return signal\n const start = signal.at + signal.inputDelay\n const attribution = attributeWindow(trace, start, start + signal.processing)\n if (attribution.length === 0) return signal\n return { ...signal, attribution }\n })\n}\n\ninterface SelfProfilingCollector extends Collector {\n /** Stop the profiler (if running), await its trace, and return a result\n * with long-task signals enriched. Falls back to the input on any failure\n * or when the Profiler API / Document-Policy header is unavailable. */\n finalize(result: RecordingResult): Promise<RecordingResult>\n}\n\n/**\n * Collector that runs the JS Self-Profiling API across a recording and, on\n * finalize, attributes each long task to the developer's own hot functions —\n * something LoAF can't do for React-delegated events (it only sees React's\n * single root dispatcher).\n *\n * It reports `kind: 'long-task'` because it enriches that signal rather than\n * emitting its own. Requires Chromium + a `Document-Policy: js-profiling`\n * response header (the dev plugins inject it); degrades to a no-op otherwise.\n */\nexport function createSelfProfilingCollector(): SelfProfilingCollector {\n let profiler: ProfilerInstance | null = null\n let tracePromise: Promise<ProfilerTrace> | null = null\n\n return {\n kind: 'long-task',\n activate() {\n tracePromise = null\n const Ctor = (globalThis as { Profiler?: ProfilerCtor }).Profiler\n if (typeof Ctor !== 'function') return\n try {\n profiler = new Ctor({ sampleInterval: SAMPLE_INTERVAL_MS, maxBufferSize: MAX_BUFFER_SIZE })\n } catch (err) {\n // Thrown when the Document-Policy: js-profiling header is absent.\n console.warn(\n '[react-perfscope] self-profiling unavailable (needs Document-Policy: js-profiling header); long tasks keep LoAF-only attribution:',\n err\n )\n profiler = null\n }\n },\n deactivate() {\n if (!profiler) return\n try {\n tracePromise = profiler.stop()\n } catch (err) {\n console.warn('[react-perfscope] self-profiling stop failed:', err)\n tracePromise = null\n }\n profiler = null\n },\n async finalize(result: RecordingResult): Promise<RecordingResult> {\n if (!tracePromise) return result\n try {\n const trace = await tracePromise\n const signals = attributeInteractionSignals(trace, attributeLongTaskSignals(trace, result.signals))\n return { ...result, signals }\n } catch (err) {\n console.warn('[react-perfscope] self-profiling finalize failed:', err)\n return result\n } finally {\n tracePromise = null\n }\n },\n }\n}\n"],"mappings":";AAEA,IAAM,aAAa;AAMZ,SAAS,iBAA2B;AACzC,MAAI,YAAY;AAChB,MAAI,YAAY;AAChB,MAAI,SAAmB,CAAC;AACxB,QAAM,cAAc,oBAAI,IAAyB;AACjD,QAAM,aAA0B,CAAC;AAEjC,WAAS,OAAO,QAAgB;AAC9B,eAAW,MAAM,aAAa;AAC5B,UAAI;AACF,WAAG,MAAM;AAAA,MACX,SA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