inpspy 0.0.0-stage → 1.0.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/dist/index.cjs ADDED
@@ -0,0 +1,980 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target2, all) => {
7
+ for (var name in all)
8
+ __defProp(target2, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ attributeScripts: () => attributeScripts,
24
+ clear: () => clear,
25
+ describeElement: () => describeElement,
26
+ estimateInp: () => estimateInp,
27
+ formatReport: () => formatReport,
28
+ getInteractions: () => getInteractions,
29
+ getReport: () => getReport,
30
+ getSupport: () => getSupport,
31
+ isRunning: () => isRunning,
32
+ isThirdParty: () => isThirdParty,
33
+ rate: () => rate,
34
+ start: () => start,
35
+ summarize: () => summarize
36
+ });
37
+ module.exports = __toCommonJS(src_exports);
38
+
39
+ // src/core.ts
40
+ var GOOD = 200;
41
+ var POOR = 500;
42
+ function rate(duration) {
43
+ if (duration <= GOOD) return "good";
44
+ if (duration <= POOR) return "needs-improvement";
45
+ return "poor";
46
+ }
47
+ var RATING_LABEL = {
48
+ good: "good",
49
+ "needs-improvement": "needs improvement",
50
+ poor: "poor"
51
+ };
52
+ function longestEntry(entries) {
53
+ let best;
54
+ for (const entry of entries) {
55
+ if (!best || entry.duration > best.duration || entry.duration === best.duration && entry.startTime < best.startTime) {
56
+ best = entry;
57
+ }
58
+ }
59
+ return best;
60
+ }
61
+ function summarize(entries) {
62
+ const main = longestEntry(entries);
63
+ if (!main) return void 0;
64
+ const end = main.startTime + main.duration;
65
+ const frame = entries.filter((e) => Math.abs(e.startTime + e.duration - end) <= 8 && e.startTime >= main.startTime - 8);
66
+ let first = Infinity;
67
+ let last = -Infinity;
68
+ for (const e of frame) {
69
+ first = Math.min(first, e.processingStart);
70
+ last = Math.max(last, e.processingEnd);
71
+ }
72
+ const processingStart = clamp(first, main.startTime, end);
73
+ const processingEnd = clamp(last, processingStart, end);
74
+ return {
75
+ main,
76
+ startTime: main.startTime,
77
+ duration: main.duration,
78
+ phases: {
79
+ inputDelay: processingStart - main.startTime,
80
+ processing: processingEnd - processingStart,
81
+ presentationDelay: end - processingEnd
82
+ },
83
+ frame
84
+ };
85
+ }
86
+ function clamp(value, min, max) {
87
+ return Math.min(Math.max(value, min), max);
88
+ }
89
+ function interactionType(events) {
90
+ return events.some((name) => name.startsWith("key")) ? "keyboard" : "pointer";
91
+ }
92
+ function estimateInp(longest2, interactionCount2) {
93
+ if (longest2.length === 0) return null;
94
+ const sorted = [...longest2].sort((a, b) => b - a);
95
+ const skip = Math.floor(Math.max(interactionCount2, longest2.length) / 50);
96
+ return sorted[Math.min(skip, sorted.length - 1)];
97
+ }
98
+ function keepLongest(list, value, max = 10) {
99
+ list.push(value);
100
+ list.sort((a, b) => b - a);
101
+ if (list.length > max) list.length = max;
102
+ return list;
103
+ }
104
+ function isThirdParty(url, pageOrigin2) {
105
+ if (!url || !pageOrigin2 || pageOrigin2 === "null") return false;
106
+ try {
107
+ const u = new URL(url, pageOrigin2);
108
+ const origin = u.origin !== "null" ? u.origin : u.host ? `${u.protocol}//${u.host}` : "";
109
+ return origin !== "" && origin !== pageOrigin2;
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+ function attributeScripts(start2, end, loafs, pageOrigin2) {
115
+ const frames = loafs.filter((f) => f.startTime < end && f.startTime + f.duration > start2);
116
+ if (frames.length === 0) return { attribution: "none", scripts: [] };
117
+ const scripts = [];
118
+ for (const frame of frames) {
119
+ for (const s of frame.scripts ?? []) {
120
+ if (!(s.startTime < end && s.startTime + s.duration > start2)) continue;
121
+ const url = s.sourceURL ?? "";
122
+ scripts.push({
123
+ url,
124
+ functionName: s.sourceFunctionName ?? "",
125
+ invoker: s.invoker ?? "",
126
+ invokerType: s.invokerType ?? "",
127
+ duration: s.duration,
128
+ forcedStyleAndLayoutDuration: s.forcedStyleAndLayoutDuration ?? 0,
129
+ startTime: s.startTime,
130
+ thirdParty: isThirdParty(url, pageOrigin2)
131
+ });
132
+ }
133
+ }
134
+ scripts.sort((a, b) => b.duration - a.duration);
135
+ return { attribution: "loaf", scripts };
136
+ }
137
+ function scriptName(url) {
138
+ if (!url) return "(inline or unknown script)";
139
+ try {
140
+ const u = new URL(url);
141
+ const file = u.pathname.split("/").filter(Boolean).pop();
142
+ return file ? decodeURIComponent(file) : u.host || url;
143
+ } catch {
144
+ return url.split(/[?#]/)[0].split("/").filter(Boolean).pop() ?? url;
145
+ }
146
+ }
147
+ function invokerLabel(script) {
148
+ const { invoker, invokerType } = script;
149
+ if (invokerType === "event-listener") {
150
+ const event = invoker.slice(invoker.lastIndexOf(".") + 1).replace(/^on/, "");
151
+ return event ? `${event} handler` : "event listener";
152
+ }
153
+ if (invokerType === "user-callback") {
154
+ if (invoker.startsWith("TimerHandler:")) return `${invoker.slice(13)} callback`;
155
+ if (invoker === "FrameRequestCallback") return "requestAnimationFrame callback";
156
+ if (invoker === "IdleRequestCallback") return "requestIdleCallback callback";
157
+ return invoker ? `${invoker} callback` : "callback";
158
+ }
159
+ if (invokerType === "resolve-promise" || invokerType === "reject-promise") {
160
+ return invoker ? `${invoker} (${invokerType === "resolve-promise" ? "then" : "catch"})` : "promise callback";
161
+ }
162
+ if (invokerType === "classic-script" || invokerType === "module-script") return "script evaluation";
163
+ return invoker || invokerType || "script";
164
+ }
165
+ function scriptLabel(script) {
166
+ const parts = [`${ms(script.duration)}`, `${scriptName(script.url)}${script.thirdParty ? " (third-party)" : ""}`];
167
+ parts.push(script.functionName ? `${script.functionName}() \xB7 ${invokerLabel(script)}` : invokerLabel(script));
168
+ return parts.join(" \xB7 ");
169
+ }
170
+ function ms(value) {
171
+ return `${Math.round(value)} ms`;
172
+ }
173
+ var MAX_TEXT = 32;
174
+ function escapeIdent(value) {
175
+ const css = globalThis.CSS;
176
+ if (css?.escape) return css.escape(value);
177
+ return value.replace(/^(\d)/, "\\3$1 ").replace(/[^\w-]/g, "\\$&");
178
+ }
179
+ function attr(el2, name) {
180
+ return (el2.getAttribute?.(name) ?? "").trim();
181
+ }
182
+ function selectorPart(el2) {
183
+ const tag = el2.tagName.toLowerCase();
184
+ const id = el2.id ?? attr(el2, "id");
185
+ if (id) return `${tag}#${escapeIdent(id)}`;
186
+ let part = tag;
187
+ const classes = attr(el2, "class").split(/\s+/).filter((c) => c && c.length <= 30).slice(0, 2);
188
+ for (const c of classes) part += `.${escapeIdent(c)}`;
189
+ const testId = attr(el2, "data-testid");
190
+ if (testId) part += `[data-testid="${testId.replace(/["\\]/g, "\\$&")}"]`;
191
+ return part;
192
+ }
193
+ function elementText(el2) {
194
+ const tag = el2.tagName.toLowerCase();
195
+ let text = attr(el2, "aria-label") || attr(el2, "title") || attr(el2, "alt") || attr(el2, "placeholder");
196
+ if (!text && tag !== "input" && tag !== "textarea" && tag !== "select") text = el2.textContent ?? "";
197
+ if (!text && (tag === "input" || tag === "select" || tag === "textarea")) text = attr(el2, "name");
198
+ text = text.replace(/\s+/g, " ").trim();
199
+ return text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT - 1)}\u2026` : text;
200
+ }
201
+ function describeElement(el2) {
202
+ if (!el2 || typeof el2.tagName !== "string") return { selector: "(removed element)", text: "" };
203
+ let selector = selectorPart(el2);
204
+ if (!selector.includes("#") && !selector.includes("[data-testid")) {
205
+ let parent = el2.parentElement ?? null;
206
+ for (let depth = 0; parent && depth < 6; depth++, parent = parent.parentElement ?? null) {
207
+ const pid = parent.id ?? attr(parent, "id");
208
+ if (pid) {
209
+ selector = `${parent.tagName.toLowerCase()}#${escapeIdent(pid)} ${selector}`;
210
+ break;
211
+ }
212
+ }
213
+ }
214
+ return { selector, text: elementText(el2) };
215
+ }
216
+ function cell(value) {
217
+ return value.replace(/\|/g, "\\|").replace(/\n/g, " ");
218
+ }
219
+ function code(value) {
220
+ return `\`${value.replace(/`/g, "'")}\``;
221
+ }
222
+ function target(i) {
223
+ return i.targetText ? `${code(i.target)} "${i.targetText}"` : code(i.target);
224
+ }
225
+ function eventName(i) {
226
+ const named = ["click", "keydown", "keyup", "pointerup", "pointerdown", "keypress"];
227
+ return named.find((n) => i.events.includes(n)) ?? i.events[0] ?? i.type;
228
+ }
229
+ function formatReport(interactions2, context, format = "markdown") {
230
+ if (format === "json") {
231
+ return JSON.stringify(
232
+ {
233
+ url: context.url,
234
+ inp: context.inp,
235
+ rating: context.inp === null ? null : rate(context.inp),
236
+ interactionCount: context.interactionCount,
237
+ durationThreshold: context.durationThreshold,
238
+ loafSupported: context.loafSupported,
239
+ interactions: interactions2
240
+ },
241
+ null,
242
+ 2
243
+ );
244
+ }
245
+ const lines = ["## inpspy report", ""];
246
+ lines.push(`- Page: ${context.url}`);
247
+ lines.push(
248
+ context.inp === null ? `- Page INP (estimate): no interaction at or above ${context.durationThreshold} ms yet` : `- Page INP (estimate): **${ms(context.inp)}** (${RATING_LABEL[rate(context.inp)]}), ${context.interactionCount} interaction${context.interactionCount === 1 ? "" : "s"}`
249
+ );
250
+ lines.push(
251
+ `- Recorded: ${interactions2.length} interaction${interactions2.length === 1 ? "" : "s"} at or above ${context.durationThreshold} ms`
252
+ );
253
+ if (!context.loafSupported) {
254
+ lines.push("- Script attribution: not available (needs the Long Animation Frames API, Chromium 123+)");
255
+ }
256
+ if (interactions2.length === 0) return `${lines.join("\n")}
257
+ `;
258
+ lines.push("", "| # | Duration | Rating | Event | Target | Input delay | Processing | Presentation |");
259
+ lines.push("| ---: | ---: | --- | --- | --- | ---: | ---: | ---: |");
260
+ interactions2.forEach((i, n) => {
261
+ lines.push(
262
+ `| ${n + 1} | ${ms(i.duration)} | ${RATING_LABEL[i.rating]} | ${eventName(i)} | ${cell(target(i))} | ${ms(i.phases.inputDelay)} | ${ms(i.phases.processing)} | ${ms(i.phases.presentationDelay)} |`
263
+ );
264
+ });
265
+ const slowest = [...interactions2].sort((a, b) => b.duration - a.duration).slice(0, 5);
266
+ lines.push("", "### Slowest interactions");
267
+ for (const i of slowest) {
268
+ lines.push("", `#### ${ms(i.duration)} \xB7 ${eventName(i)} on ${target(i)}`);
269
+ lines.push(
270
+ `- Input delay ${ms(i.phases.inputDelay)} \xB7 processing ${ms(i.phases.processing)} \xB7 presentation delay ${ms(i.phases.presentationDelay)}`
271
+ );
272
+ if (i.attribution === "unsupported") continue;
273
+ if (i.scripts.length === 0) {
274
+ lines.push(
275
+ i.attribution === "none" ? "- Scripts: no long animation frame overlapped this interaction" : "- Scripts: none over 5 ms (the time went into rendering or browser work)"
276
+ );
277
+ continue;
278
+ }
279
+ lines.push("- Scripts:");
280
+ for (const s of i.scripts.slice(0, 5)) {
281
+ const fn = s.functionName ? ` \xB7 ${code(`${s.functionName}()`)}` : "";
282
+ const forced = s.forcedStyleAndLayoutDuration >= 1 ? ` \xB7 ${ms(s.forcedStyleAndLayoutDuration)} forced layout` : "";
283
+ lines.push(
284
+ ` - ${ms(s.duration)} \xB7 ${s.url ? code(s.url) : "inline or unknown script"}${s.thirdParty ? " (third-party)" : ""}${fn} \xB7 ${invokerLabel(s)}${forced}`
285
+ );
286
+ }
287
+ }
288
+ return `${lines.join("\n")}
289
+ `;
290
+ }
291
+
292
+ // src/overlay.ts
293
+ var CSS = `
294
+ :host{all:initial}
295
+ *{box-sizing:border-box}
296
+ .root{position:fixed;z-index:2147483647;display:flex;flex-direction:column;align-items:flex-end;gap:8px;max-width:calc(100vw - 24px);width:380px;pointer-events:none;
297
+ font:13px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:var(--fg);
298
+ --bg:#ffffff;--fg:#0f172a;--muted:#64748b;--line:#e2e8f0;--soft:#f1f5f9;--code:#334155;
299
+ --good:#0a8f4e;--ni:#d97706;--poor:#dc2626;--in:#8b5cf6;--pr:#3b82f6;--pd:#14b8a6;--tp:#b45309;--tpbg:#fef3c7;--shadow:0 10px 30px rgba(15,23,42,.16),0 2px 6px rgba(15,23,42,.08)}
300
+ @media (prefers-color-scheme:dark){.root{--bg:#0f172a;--fg:#e2e8f0;--muted:#94a3b8;--line:#1e293b;--soft:#1e293b;--code:#cbd5e1;--good:#34d399;--ni:#fbbf24;--poor:#f87171;--tp:#fcd34d;--tpbg:#422006;--shadow:0 10px 30px rgba(0,0,0,.5)}}
301
+ .bottom-right{right:12px;bottom:12px}
302
+ .bottom-left{left:12px;bottom:12px;align-items:flex-start}
303
+ .top-right{right:12px;top:12px;flex-direction:column-reverse}
304
+ .top-left{left:12px;top:12px;flex-direction:column-reverse;align-items:flex-start}
305
+ .toasts{display:flex;flex-direction:column;gap:8px;width:100%}
306
+ .top-right .toasts,.top-left .toasts{flex-direction:column-reverse}
307
+ .card{pointer-events:auto;background:var(--bg);border:1px solid var(--line);border-left:4px solid var(--rc);border-radius:12px;padding:10px 12px;box-shadow:var(--shadow);width:100%}
308
+ .good{--rc:var(--good)}.needs-improvement{--rc:var(--ni)}.poor{--rc:var(--poor)}.none{--rc:var(--muted)}
309
+ @media (prefers-reduced-motion:no-preference){.toast{animation:in .18s ease-out}}
310
+ @keyframes in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
311
+ .head{display:flex;align-items:center;gap:8px}
312
+ .ms{font-weight:700;font-size:15px;color:var(--rc);font-variant-numeric:tabular-nums}
313
+ .what{color:var(--muted);flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
314
+ .target{margin-top:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
315
+ code{font:12px/1.4 ui-monospace,"Cascadia Mono",Menlo,Consolas,monospace;color:var(--code);background:var(--soft);border-radius:4px;padding:1px 4px}
316
+ .text{color:var(--muted)}
317
+ .bar{display:flex;height:6px;border-radius:3px;overflow:hidden;margin-top:8px;background:var(--soft)}
318
+ .bar i{display:block;height:100%;min-width:2px}
319
+ .in{background:var(--in)}.pr{background:var(--pr)}.pd{background:var(--pd)}
320
+ .phases{display:flex;flex-wrap:wrap;gap:2px 12px;margin-top:5px;color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums}
321
+ .phases b{color:var(--fg);font-weight:600}
322
+ .sw{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:5px;vertical-align:0}
323
+ ul{list-style:none;margin:6px 0 0;padding:0}
324
+ .scripts li{font-size:12px;margin-top:3px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
325
+ .scripts .d{font-weight:600;font-variant-numeric:tabular-nums}
326
+ .tp{display:inline-block;background:var(--tpbg);color:var(--tp);font-weight:600;font-size:11px;border-radius:4px;padding:0 5px;margin-left:2px}
327
+ .note{margin:6px 0 0;color:var(--muted);font-size:12px}
328
+ button{font:inherit;color:inherit;cursor:pointer;border-radius:8px}
329
+ button:focus-visible{outline:2px solid var(--pr);outline-offset:2px}
330
+ .x{border:0;background:transparent;color:var(--muted);font-size:16px;line-height:1;padding:2px 6px;margin:-2px -6px -2px 0}
331
+ .x:hover{color:var(--fg);background:var(--soft)}
332
+ .launcher{pointer-events:auto;display:inline-flex;align-items:center;gap:7px;border:1px solid var(--line);background:var(--bg);box-shadow:var(--shadow);border-radius:999px;padding:6px 12px;font-size:12px}
333
+ .launcher b{font-variant-numeric:tabular-nums;color:var(--rc)}
334
+ .dot{width:8px;height:8px;border-radius:50%;background:var(--rc)}
335
+ .count{color:var(--muted)}
336
+ .panel{pointer-events:auto;background:var(--bg);border:1px solid var(--line);border-radius:14px;box-shadow:var(--shadow);width:100%;max-height:min(70vh,560px);display:flex;flex-direction:column;overflow:hidden}
337
+ .panel[hidden]{display:none}
338
+ .ph{padding:12px 14px 10px;border-bottom:1px solid var(--line)}
339
+ .ph-top{display:flex;align-items:center;gap:8px}
340
+ .title{font-weight:700;font-size:14px;flex:1}
341
+ .big{font-size:22px;font-weight:800;color:var(--rc);font-variant-numeric:tabular-nums;letter-spacing:-.3px}
342
+ .sub{color:var(--muted);font-size:12px}
343
+ .actions{display:flex;gap:6px;margin-top:8px}
344
+ .btn{border:1px solid var(--line);background:var(--soft);padding:4px 10px;font-size:12px;font-weight:600}
345
+ .btn:hover{border-color:var(--muted)}
346
+ .list{list-style:none;overflow:auto;padding:8px 10px 10px;margin:0;display:flex;flex-direction:column;gap:8px}
347
+ .list .card{box-shadow:none}
348
+ .empty{color:var(--muted);padding:14px;text-align:center}
349
+ .legend{display:flex;gap:12px;padding:8px 14px;border-top:1px solid var(--line);color:var(--muted);font-size:11px}
350
+ .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
351
+ `;
352
+ function el(tag, className, text) {
353
+ const node = document.createElement(tag);
354
+ if (className) node.className = className;
355
+ if (text !== void 0) node.textContent = text;
356
+ return node;
357
+ }
358
+ function eventLabel(i) {
359
+ const named = ["click", "keydown", "keyup", "pointerup", "pointerdown", "keypress"];
360
+ return named.find((n) => i.events.includes(n)) ?? i.events[0] ?? i.type;
361
+ }
362
+ function phaseBar(i) {
363
+ const bar = el("div", "bar");
364
+ bar.setAttribute("aria-hidden", "true");
365
+ const total = Math.max(i.duration, 1);
366
+ const parts = [
367
+ ["in", i.phases.inputDelay],
368
+ ["pr", i.phases.processing],
369
+ ["pd", i.phases.presentationDelay]
370
+ ];
371
+ for (const [cls, value] of parts) {
372
+ const seg = el("i", cls);
373
+ seg.style.width = `${value / total * 100}%`;
374
+ bar.append(seg);
375
+ }
376
+ return bar;
377
+ }
378
+ function phaseText(i) {
379
+ const row = el("div", "phases");
380
+ const parts = [
381
+ ["in", "Input delay", i.phases.inputDelay],
382
+ ["pr", "Processing", i.phases.processing],
383
+ ["pd", "Presentation", i.phases.presentationDelay]
384
+ ];
385
+ for (const [cls, label, value] of parts) {
386
+ const span = el("span");
387
+ span.append(el("i", `sw ${cls}`), `${label} `, el("b", void 0, ms(value)));
388
+ row.append(span);
389
+ }
390
+ return row;
391
+ }
392
+ function card(i, state, toast, onClose) {
393
+ const root = el("div", `card ${i.rating}${toast ? " toast" : ""}`);
394
+ root.dataset.interaction = String(i.id);
395
+ const head = el("div", "head");
396
+ head.append(el("span", "ms", ms(i.duration)), el("span", "what", `${eventLabel(i)} \xB7 ${RATING_LABEL[i.rating]}`));
397
+ if (onClose) {
398
+ const x = el("button", "x", "\xD7");
399
+ x.type = "button";
400
+ x.setAttribute("aria-label", "Dismiss");
401
+ x.addEventListener("click", onClose);
402
+ head.append(x);
403
+ }
404
+ const target2 = el("div", "target");
405
+ target2.append(el("code", void 0, i.target));
406
+ if (i.targetText) target2.append(" ", el("span", "text", `\u201C${i.targetText}\u201D`));
407
+ root.append(head, target2, phaseBar(i), phaseText(i));
408
+ if (i.attribution === "unsupported") {
409
+ if (toast) root.append(el("p", "note", "Script attribution needs Long Animation Frames (Chromium 123+)."));
410
+ } else if (i.scripts.length > 0) {
411
+ const list = el("ul", "scripts");
412
+ for (const s of i.scripts.slice(0, 3)) {
413
+ const li = el("li");
414
+ li.title = `${s.url || "inline or unknown script"}${s.functionName ? ` \xB7 ${s.functionName}()` : ""} \xB7 ${s.invoker}`;
415
+ li.append(el("span", "d", ms(s.duration)), ` \xB7 ${scriptName(s.url)}`);
416
+ if (s.thirdParty) li.append(" ", el("span", "tp", "third-party"));
417
+ li.append(` \xB7 ${s.functionName ? `${s.functionName}() \xB7 ` : ""}${invokerLabel(s)}`);
418
+ list.append(li);
419
+ }
420
+ root.append(list);
421
+ } else if (state.loafSupported) {
422
+ root.append(
423
+ el(
424
+ "p",
425
+ "note",
426
+ i.attribution === "none" ? "No long animation frame overlapped this interaction." : "No script ran 5 ms or more: the time went into rendering."
427
+ )
428
+ );
429
+ }
430
+ return root;
431
+ }
432
+ function createOverlay(options) {
433
+ const host = document.createElement("inpspy-overlay");
434
+ host.setAttribute("data-inpspy", "");
435
+ host.style.cssText = "all:initial !important;position:fixed !important;z-index:2147483647 !important;";
436
+ const shadow = host.attachShadow({ mode: "open" });
437
+ const sheetSupported = "adoptedStyleSheets" in shadow && typeof CSSStyleSheet !== "undefined" && "replaceSync" in CSSStyleSheet.prototype;
438
+ if (sheetSupported) {
439
+ const sheet = new CSSStyleSheet();
440
+ sheet.replaceSync(CSS);
441
+ shadow.adoptedStyleSheets = [sheet];
442
+ } else {
443
+ shadow.append(el("style", void 0, CSS));
444
+ }
445
+ const root = el("div", `root ${options.position}`);
446
+ const toasts = el("div", "toasts");
447
+ toasts.setAttribute("role", "region");
448
+ toasts.setAttribute("aria-label", "inpspy: slow interactions");
449
+ const live = el("div", "sr");
450
+ live.setAttribute("aria-live", "polite");
451
+ const panel = el("section", "panel");
452
+ panel.id = "inpspy-panel";
453
+ panel.hidden = true;
454
+ panel.setAttribute("aria-label", "inpspy: interactions");
455
+ const ph = el("div", "ph");
456
+ const phTop = el("div", "ph-top");
457
+ const title = el("div", "title", "inpspy");
458
+ const close = el("button", "x", "\xD7");
459
+ close.type = "button";
460
+ close.setAttribute("aria-label", "Close panel");
461
+ phTop.append(title, close);
462
+ const summary = el("div");
463
+ const big = el("span", "big");
464
+ const sub = el("div", "sub");
465
+ summary.append(big, " ", el("span", "sub", "page INP estimate"));
466
+ const actions = el("div", "actions");
467
+ const copy = el("button", "btn copy", "Copy report");
468
+ copy.type = "button";
469
+ const clear2 = el("button", "btn clear", "Clear");
470
+ clear2.type = "button";
471
+ actions.append(copy, clear2);
472
+ const notes = el("div");
473
+ ph.append(phTop, summary, sub, notes, actions);
474
+ const list = el("ol", "list");
475
+ list.setAttribute("aria-label", "Recorded interactions, newest first");
476
+ const legend = el("div", "legend");
477
+ for (const [cls, label] of [
478
+ ["in", "input delay"],
479
+ ["pr", "processing"],
480
+ ["pd", "presentation delay"]
481
+ ]) {
482
+ const span = el("span");
483
+ span.append(el("i", `sw ${cls}`), label);
484
+ legend.append(span);
485
+ }
486
+ panel.append(ph, list, legend);
487
+ const launcher = el("button", "launcher");
488
+ launcher.type = "button";
489
+ launcher.setAttribute("aria-expanded", "false");
490
+ launcher.setAttribute("aria-controls", panel.id);
491
+ const dot = el("span", "dot");
492
+ const launcherValue = el("b");
493
+ const launcherCount = el("span", "count");
494
+ launcher.append(dot, "INP ", launcherValue, launcherCount);
495
+ root.append(toasts, panel, launcher, live);
496
+ shadow.append(root);
497
+ (document.body ?? document.documentElement).append(host);
498
+ const timers = /* @__PURE__ */ new Set();
499
+ function setOpen(open) {
500
+ panel.hidden = !open;
501
+ launcher.setAttribute("aria-expanded", String(open));
502
+ if (open) refresh();
503
+ }
504
+ function refresh() {
505
+ const state = options.getState();
506
+ const rating = state.inp === null ? "none" : rate(state.inp);
507
+ launcher.className = `launcher ${rating}`;
508
+ launcherValue.textContent = state.inp === null ? "\u2013" : ms(state.inp);
509
+ launcherCount.textContent = ` \xB7 ${state.interactionCount}`;
510
+ launcher.title = "inpspy: open the interactions panel";
511
+ launcher.setAttribute(
512
+ "aria-label",
513
+ `inpspy: page INP ${state.inp === null ? "not measured yet" : ms(state.inp)}, ${state.interactionCount} interactions. Show details.`
514
+ );
515
+ if (panel.hidden) return;
516
+ summary.className = rating;
517
+ big.textContent = state.inp === null ? "\u2013" : ms(state.inp);
518
+ sub.textContent = state.inp === null ? `No interaction at or above ${state.durationThreshold} ms yet. Click around.` : `${RATING_LABEL[rate(state.inp)]} \xB7 ${state.interactionCount} interaction${state.interactionCount === 1 ? "" : "s"} \xB7 ${state.interactions.length} recorded (\u2265 ${state.durationThreshold} ms)`;
519
+ notes.replaceChildren();
520
+ if (!state.eventTimingSupported) {
521
+ notes.append(el("p", "note", "This browser has no Event Timing API, so interactions can't be measured. Use a Chromium browser."));
522
+ } else if (!state.loafSupported) {
523
+ notes.append(el("p", "note", "Script attribution needs the Long Animation Frames API (Chromium 123+)."));
524
+ }
525
+ list.replaceChildren();
526
+ if (state.interactions.length === 0) {
527
+ list.append(el("li", "empty", "Nothing recorded yet."));
528
+ } else {
529
+ for (const i of [...state.interactions].reverse()) {
530
+ const li = el("li");
531
+ li.append(card(i, state, false));
532
+ list.append(li);
533
+ }
534
+ }
535
+ }
536
+ function removeToast(node) {
537
+ node.remove();
538
+ }
539
+ function toast(i) {
540
+ const state = options.getState();
541
+ let node;
542
+ const dismiss = () => removeToast(node);
543
+ node = card(i, state, true, dismiss);
544
+ toasts.append(node);
545
+ while (toasts.children.length > 3) toasts.firstElementChild?.remove();
546
+ live.textContent = `Slow interaction: ${ms(i.duration)} ${eventLabel(i)} on ${i.target}`;
547
+ if (options.toastDuration > 0) {
548
+ let remaining = options.toastDuration;
549
+ let started = Date.now();
550
+ let timer;
551
+ const arm = () => {
552
+ started = Date.now();
553
+ timer = setTimeout(() => {
554
+ timers.delete(timer);
555
+ removeToast(node);
556
+ }, remaining);
557
+ timers.add(timer);
558
+ };
559
+ const pause = () => {
560
+ if (timer === void 0) return;
561
+ clearTimeout(timer);
562
+ timers.delete(timer);
563
+ timer = void 0;
564
+ remaining = Math.max(1e3, remaining - (Date.now() - started));
565
+ };
566
+ const resume = () => {
567
+ if (timer === void 0 && node.isConnected && !node.matches(":hover") && !node.contains(shadow.activeElement)) arm();
568
+ };
569
+ node.addEventListener("mouseenter", pause);
570
+ node.addEventListener("focusin", pause);
571
+ node.addEventListener("mouseleave", resume);
572
+ node.addEventListener("focusout", () => setTimeout(resume, 0));
573
+ arm();
574
+ }
575
+ }
576
+ launcher.addEventListener("click", () => setOpen(panel.hidden));
577
+ close.addEventListener("click", () => {
578
+ setOpen(false);
579
+ launcher.focus();
580
+ });
581
+ panel.addEventListener("keydown", (e) => {
582
+ if (e.key === "Escape") {
583
+ setOpen(false);
584
+ launcher.focus();
585
+ }
586
+ });
587
+ clear2.addEventListener("click", () => {
588
+ options.onClear();
589
+ toasts.replaceChildren();
590
+ refresh();
591
+ });
592
+ let copyTimer;
593
+ copy.addEventListener("click", () => {
594
+ const text = options.getReport();
595
+ const done = (ok) => {
596
+ copy.textContent = ok ? "Copied" : "Copy failed";
597
+ clearTimeout(copyTimer);
598
+ copyTimer = setTimeout(() => copy.textContent = "Copy report", 2e3);
599
+ };
600
+ const fallback = () => done(copyWithTextarea(text, shadow));
601
+ if (navigator.clipboard?.writeText) navigator.clipboard.writeText(text).then(() => done(true), fallback);
602
+ else fallback();
603
+ });
604
+ refresh();
605
+ return {
606
+ host,
607
+ toast,
608
+ refresh,
609
+ clearToasts: () => toasts.replaceChildren(),
610
+ contains: (node) => node === host || node instanceof Node && (host.contains(node) || shadow.contains(node)),
611
+ destroy() {
612
+ for (const t of timers) clearTimeout(t);
613
+ timers.clear();
614
+ clearTimeout(copyTimer);
615
+ host.remove();
616
+ }
617
+ };
618
+ }
619
+ function copyWithTextarea(text, shadow) {
620
+ const previous = shadow.activeElement ?? document.activeElement;
621
+ const area = document.createElement("textarea");
622
+ area.value = text;
623
+ area.setAttribute("readonly", "");
624
+ area.style.cssText = "position:fixed;opacity:0;pointer-events:none;left:0;top:0";
625
+ shadow.append(area);
626
+ area.select();
627
+ let ok = false;
628
+ try {
629
+ ok = document.execCommand("copy");
630
+ } catch {
631
+ ok = false;
632
+ }
633
+ area.remove();
634
+ previous?.focus?.();
635
+ return ok;
636
+ }
637
+
638
+ // src/spy.ts
639
+ var SETTLE_MS = 120;
640
+ var LOAF_BUFFER = 200;
641
+ var POSITIONS = ["bottom-right", "bottom-left", "top-right", "top-left"];
642
+ var session = null;
643
+ var interactions = [];
644
+ var longest = [];
645
+ var recordedCount = 0;
646
+ var durationThreshold = 40;
647
+ var loafSupported = false;
648
+ var eventTimingSupported = false;
649
+ var noop = () => {
650
+ };
651
+ function inBrowser() {
652
+ return typeof window !== "undefined" && typeof document !== "undefined" && typeof performance !== "undefined";
653
+ }
654
+ function supportedTypes() {
655
+ if (typeof PerformanceObserver === "undefined") return [];
656
+ return PerformanceObserver.supportedEntryTypes ?? [];
657
+ }
658
+ function getSupport() {
659
+ if (!inBrowser()) return { eventTiming: false, longAnimationFrames: false };
660
+ const types = supportedTypes();
661
+ return { eventTiming: types.includes("event"), longAnimationFrames: types.includes("long-animation-frame") };
662
+ }
663
+ function num(value, fallback, min = 0) {
664
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(min, value) : fallback;
665
+ }
666
+ function resolve(options) {
667
+ return {
668
+ threshold: num(options.threshold, 200),
669
+ durationThreshold: Math.round(num(options.durationThreshold, 40, 16)),
670
+ overlay: options.overlay !== false,
671
+ console: options.console !== false,
672
+ maxEntries: Math.max(1, Math.round(num(options.maxEntries, 50, 1))),
673
+ position: POSITIONS.includes(options.position) ? options.position : "bottom-right",
674
+ toastDuration: num(options.toastDuration, 8e3),
675
+ onInteraction: typeof options.onInteraction === "function" ? options.onInteraction : void 0
676
+ };
677
+ }
678
+ function interactionCount() {
679
+ const count = inBrowser() ? performance.interactionCount : void 0;
680
+ return typeof count === "number" && count >= recordedCount ? count : recordedCount;
681
+ }
682
+ function pageInp() {
683
+ return estimateInp(longest, interactionCount());
684
+ }
685
+ function pageOrigin() {
686
+ return inBrowser() ? location.origin : "";
687
+ }
688
+ function getInteractions() {
689
+ return interactions.map((i) => ({ ...i, events: [...i.events], phases: { ...i.phases }, scripts: i.scripts.map((s) => ({ ...s })) }));
690
+ }
691
+ function getReport(format = "markdown") {
692
+ return formatReport(
693
+ interactions,
694
+ {
695
+ url: inBrowser() ? location.href : "",
696
+ inp: pageInp(),
697
+ interactionCount: interactionCount(),
698
+ durationThreshold,
699
+ loafSupported
700
+ },
701
+ format
702
+ );
703
+ }
704
+ function clear() {
705
+ interactions = [];
706
+ longest = [];
707
+ recordedCount = 0;
708
+ session?.recorded.clear();
709
+ session?.overlay?.clearToasts();
710
+ session?.overlay?.refresh();
711
+ }
712
+ function overlayState() {
713
+ return {
714
+ interactions,
715
+ inp: pageInp(),
716
+ interactionCount: interactionCount(),
717
+ durationThreshold,
718
+ eventTimingSupported,
719
+ loafSupported
720
+ };
721
+ }
722
+ function snapshot(entry) {
723
+ const node = entry.target ?? null;
724
+ const target2 = node && node.nodeType === 1 ? node : null;
725
+ const { selector, text } = describeElement(target2);
726
+ return {
727
+ name: entry.name,
728
+ startTime: entry.startTime,
729
+ duration: entry.duration,
730
+ processingStart: entry.processingStart,
731
+ processingEnd: entry.processingEnd,
732
+ interactionId: entry.interactionId ?? 0,
733
+ element: target2,
734
+ selector,
735
+ text
736
+ };
737
+ }
738
+ function build(s, id, entries) {
739
+ const summary = summarize(entries);
740
+ if (!summary) return null;
741
+ const preferred = ["click", "keydown", "pointerup", "pointerdown", "keyup"];
742
+ const withTarget = entries.filter((e) => e.element);
743
+ let pick = preferred.map((n) => withTarget.find((e) => e.name === n)).find(Boolean) ?? (summary.main.element ? summary.main : withTarget[0]) ?? summary.main;
744
+ if (!pick.element) {
745
+ const seen = preferred.map((n) => entries.filter((e) => e.name === n)).flat().map((e) => s.inputs.find((i) => i.name === e.name && Math.abs(i.time - e.startTime) < 1)).find(Boolean);
746
+ if (seen) pick = { element: null, selector: seen.selector, text: seen.text };
747
+ }
748
+ const events = [...new Set(entries.map((e) => e.name))];
749
+ const end = summary.startTime + summary.duration;
750
+ const scripts = loafSupported ? attributeScripts(summary.startTime, end, s.loafs, pageOrigin()) : { attribution: "unsupported", scripts: [] };
751
+ return {
752
+ element: pick.element,
753
+ interaction: {
754
+ id,
755
+ type: interactionType(events),
756
+ events,
757
+ startTime: summary.startTime,
758
+ duration: summary.duration,
759
+ rating: rate(summary.duration),
760
+ phases: summary.phases,
761
+ target: pick.selector,
762
+ targetText: pick.text,
763
+ scripts: scripts.scripts,
764
+ attribution: scripts.attribution,
765
+ url: location.href
766
+ }
767
+ };
768
+ }
769
+ function isOwnInteraction(s, entries) {
770
+ if (s.overlay && entries.some((e) => e.element && s.overlay.contains(e.element))) return true;
771
+ return entries.some((e) => s.overlayInputs.some((t) => Math.abs(t - e.startTime) < 1));
772
+ }
773
+ function logToConsole(i, element) {
774
+ const color = i.rating === "poor" ? "#dc2626" : i.rating === "needs-improvement" ? "#d97706" : "#0a8f4e";
775
+ const event = i.events.includes("click") ? "click" : i.events[0];
776
+ console.groupCollapsed(
777
+ `%cinpspy%c ${ms(i.duration)} ${event} on ${i.target}${i.targetText ? ` "${i.targetText}"` : ""} (${RATING_LABEL[i.rating]})`,
778
+ `background:${color};color:#fff;border-radius:3px;padding:1px 5px;font-weight:bold`,
779
+ `color:${color};font-weight:bold`
780
+ );
781
+ console.log(
782
+ `Input delay ${ms(i.phases.inputDelay)} \xB7 processing ${ms(i.phases.processing)} \xB7 presentation delay ${ms(i.phases.presentationDelay)}`
783
+ );
784
+ if (element) console.log("Target:", element);
785
+ if (i.attribution === "unsupported") {
786
+ console.log("Scripts: not available (needs the Long Animation Frames API, Chromium 123+)");
787
+ } else if (i.scripts.length === 0) {
788
+ console.log(i.attribution === "none" ? "Scripts: no long animation frame overlapped" : "Scripts: none ran 5 ms or more (rendering work)");
789
+ } else {
790
+ console.log("Scripts:");
791
+ for (const script of i.scripts.slice(0, 5)) console.log(` ${scriptLabel(script)}`, script.url ? `
792
+ ${script.url}` : "");
793
+ }
794
+ console.groupEnd();
795
+ }
796
+ function record(s, id, entries) {
797
+ if (session !== s || isOwnInteraction(s, entries)) return;
798
+ const built = build(s, id, entries);
799
+ if (!built) return;
800
+ const { interaction, element } = built;
801
+ s.recorded.set(id, entries);
802
+ interactions.push(interaction);
803
+ if (interactions.length > s.options.maxEntries) {
804
+ for (const old of interactions.splice(0, interactions.length - s.options.maxEntries)) s.recorded.delete(old.id);
805
+ }
806
+ keepLongest(longest, interaction.duration);
807
+ recordedCount++;
808
+ const slow = interaction.duration >= s.options.threshold;
809
+ if (slow && s.options.console) logToConsole(interaction, element);
810
+ if (slow) s.overlay?.toast(interaction);
811
+ s.overlay?.refresh();
812
+ try {
813
+ s.options.onInteraction?.({ ...interaction });
814
+ } catch (error) {
815
+ console.error("inpspy: onInteraction threw", error);
816
+ }
817
+ }
818
+ function update(s, id, entry) {
819
+ const entries = s.recorded.get(id);
820
+ entries.push(entry);
821
+ const index = interactions.findIndex((i) => i.id === id);
822
+ if (index < 0) return;
823
+ const built = build(s, id, entries);
824
+ if (!built || built.interaction.duration <= interactions[index].duration) return;
825
+ interactions[index] = built.interaction;
826
+ keepLongest(longest, built.interaction.duration);
827
+ s.overlay?.refresh();
828
+ }
829
+ function reattribute(s, frames) {
830
+ let changed = false;
831
+ for (const frame of frames) {
832
+ for (let n = interactions.length - 1; n >= 0 && n >= interactions.length - 10; n--) {
833
+ const i = interactions[n];
834
+ if (i.attribution === "loaf" && i.scripts.length > 0) continue;
835
+ const end = i.startTime + i.duration;
836
+ if (!(frame.startTime < end && frame.startTime + frame.duration > i.startTime)) continue;
837
+ const result = attributeScripts(i.startTime, end, s.loafs, pageOrigin());
838
+ interactions[n] = { ...i, ...result };
839
+ changed = true;
840
+ }
841
+ }
842
+ if (changed) s.overlay?.refresh();
843
+ }
844
+ function start(options = {}) {
845
+ if (!inBrowser()) return noop;
846
+ session?.stop();
847
+ const resolved = resolve(options);
848
+ const support = getSupport();
849
+ eventTimingSupported = support.eventTiming;
850
+ loafSupported = support.longAnimationFrames;
851
+ durationThreshold = resolved.durationThreshold;
852
+ interactions = [];
853
+ longest = [];
854
+ recordedCount = 0;
855
+ const s = {
856
+ options: resolved,
857
+ observers: [],
858
+ overlay: null,
859
+ pending: /* @__PURE__ */ new Map(),
860
+ recorded: /* @__PURE__ */ new Map(),
861
+ overlayInputs: [],
862
+ loafs: [],
863
+ inputs: [],
864
+ removeListeners: noop,
865
+ stop: noop
866
+ };
867
+ session = s;
868
+ if (resolved.overlay) {
869
+ s.overlay = createOverlay({
870
+ position: resolved.position,
871
+ toastDuration: resolved.toastDuration,
872
+ getState: overlayState,
873
+ getReport: () => getReport("markdown"),
874
+ onClear: clear
875
+ });
876
+ const host = s.overlay.host;
877
+ const remember = (e) => {
878
+ s.overlayInputs.push(e.timeStamp);
879
+ if (s.overlayInputs.length > 20) s.overlayInputs.shift();
880
+ };
881
+ const types = ["pointerdown", "pointerup", "click", "keydown", "keyup"];
882
+ for (const t of types) host.addEventListener(t, remember, true);
883
+ s.removeListeners = () => {
884
+ for (const t of types) host.removeEventListener(t, remember, true);
885
+ };
886
+ }
887
+ const inputTypes = ["pointerdown", "pointerup", "click", "keydown", "keyup"];
888
+ const seeInput = (e) => {
889
+ if (!(e.target instanceof Element) || s.overlay?.contains(e.target)) return;
890
+ const { selector, text } = describeElement(e.target);
891
+ s.inputs.push({ time: e.timeStamp, name: e.type, selector, text });
892
+ if (s.inputs.length > 30) s.inputs.shift();
893
+ };
894
+ if (eventTimingSupported) {
895
+ for (const t of inputTypes) window.addEventListener(t, seeInput, { capture: true, passive: true });
896
+ }
897
+ const removeOverlayListeners = s.removeListeners;
898
+ s.removeListeners = () => {
899
+ removeOverlayListeners();
900
+ for (const t of inputTypes) window.removeEventListener(t, seeInput, { capture: true });
901
+ };
902
+ if (loafSupported) {
903
+ const loafObserver = new PerformanceObserver((list) => {
904
+ const frames = list.getEntries();
905
+ s.loafs.push(...frames);
906
+ if (s.loafs.length > LOAF_BUFFER) s.loafs.splice(0, s.loafs.length - LOAF_BUFFER);
907
+ reattribute(s, frames);
908
+ });
909
+ try {
910
+ loafObserver.observe({ type: "long-animation-frame", buffered: true });
911
+ s.observers.push(loafObserver);
912
+ } catch {
913
+ loafSupported = false;
914
+ }
915
+ }
916
+ if (eventTimingSupported) {
917
+ const eventObserver = new PerformanceObserver((list) => {
918
+ for (const raw of list.getEntries()) {
919
+ if (!raw.interactionId) continue;
920
+ const entry = snapshot(raw);
921
+ const id = entry.interactionId;
922
+ if (s.recorded.has(id)) {
923
+ update(s, id, entry);
924
+ continue;
925
+ }
926
+ const pending = s.pending.get(id);
927
+ if (pending) {
928
+ clearTimeout(pending.timer);
929
+ pending.entries.push(entry);
930
+ }
931
+ const entries = pending?.entries ?? [entry];
932
+ const timer = setTimeout(() => {
933
+ s.pending.delete(id);
934
+ record(s, id, entries);
935
+ }, SETTLE_MS);
936
+ s.pending.set(id, { entries, timer });
937
+ }
938
+ });
939
+ try {
940
+ eventObserver.observe({ type: "event", buffered: true, durationThreshold: resolved.durationThreshold });
941
+ s.observers.push(eventObserver);
942
+ } catch {
943
+ eventTimingSupported = false;
944
+ }
945
+ }
946
+ s.overlay?.refresh();
947
+ let stopped = false;
948
+ const stop = () => {
949
+ if (stopped) return;
950
+ stopped = true;
951
+ for (const o of s.observers) o.disconnect();
952
+ for (const { timer } of s.pending.values()) clearTimeout(timer);
953
+ s.pending.clear();
954
+ s.removeListeners();
955
+ s.overlay?.destroy();
956
+ s.overlay = null;
957
+ if (session === s) session = null;
958
+ };
959
+ s.stop = stop;
960
+ return stop;
961
+ }
962
+ function isRunning() {
963
+ return session !== null;
964
+ }
965
+ // Annotate the CommonJS export names for ESM import in node:
966
+ 0 && (module.exports = {
967
+ attributeScripts,
968
+ clear,
969
+ describeElement,
970
+ estimateInp,
971
+ formatReport,
972
+ getInteractions,
973
+ getReport,
974
+ getSupport,
975
+ isRunning,
976
+ isThirdParty,
977
+ rate,
978
+ start,
979
+ summarize
980
+ });