@ogygia/insights 0.0.0 → 0.15.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.
@@ -0,0 +1,575 @@
1
+ import { analyze_cpu, fn_label, is_trace } from "./cpu.js";
2
+ // src/session-insights.ts
3
+ /**
4
+ * What a recorded session (devtools/session.ts) says — pure, so it tests on plain data. Findings point back
5
+ * at the page: an interaction's target, a shift's element, an island (the tab resolves the refs).
6
+ * The CPU trace, when there is one, names the function behind a slow interaction or a long task
7
+ * (cpu.ts, with each interaction as its own window); long animation frames name the script when
8
+ * the sampler could not run.
9
+ */
10
+ /** The session on one clock, lane by lane (the Record tab draws it). Capped per lane. */
11
+ function session_timeline(s, names) {
12
+ const z = s.from;
13
+ const cap = (xs) => xs.slice(0, 300);
14
+ const input = [];
15
+ s.clicks.forEach((c, i) => input.push({
16
+ t0: c.t - z,
17
+ t1: c.t - z,
18
+ label: `click ${c.target}`,
19
+ tone: "info",
20
+ ref: {
21
+ kind: "click",
22
+ i
23
+ }
24
+ }));
25
+ const seen = /* @__PURE__ */ new Set();
26
+ s.interactions.forEach((x, i) => {
27
+ if (!x.id || seen.has(x.id)) return;
28
+ seen.add(x.id);
29
+ let tone = "ok";
30
+ if (x.duration >= SLOW) tone = "bad";
31
+ else if (x.duration >= SLUGGISH) tone = "warn";
32
+ input.push({
33
+ t0: x.t - z,
34
+ t1: x.t - z + x.duration,
35
+ label: `${x.name} ${x.target} — ${Math.round(x.duration)} ms (handlers ${Math.round(x.processing)} ms)`,
36
+ tone,
37
+ ref: {
38
+ kind: "interaction",
39
+ i
40
+ }
41
+ });
42
+ });
43
+ const main = s.longtasks.map((t) => ({
44
+ t0: t.t - z,
45
+ t1: t.t - z + t.ms,
46
+ label: `long task ${Math.round(t.ms)} ms`,
47
+ tone: t.ms >= 200 ? "bad" : "warn"
48
+ }));
49
+ const net = s.requests.map((r) => {
50
+ const ssr = r.server?.find((x) => x.name === "ssr")?.ms;
51
+ const up = r.server?.find((x) => x.name === "net")?.ms ?? 0;
52
+ let path = r.url;
53
+ try {
54
+ path = new URL(r.url).pathname;
55
+ } catch {}
56
+ let tone = "info";
57
+ if (r.status !== null && r.status >= 400) tone = "bad";
58
+ else if (r.ms >= 1e3) tone = "warn";
59
+ return {
60
+ t0: r.t - z,
61
+ t1: r.t - z + r.ms,
62
+ label: `${path} — ${Math.round(r.ms)} ms${ssr !== void 0 ? ` (server ${Math.round(ssr)} ms${up ? `, waiting ${Math.round(up)} ms` : ""})` : ""}${r.status && r.status >= 400 ? ` · ${r.status}` : ""}`,
63
+ tone,
64
+ ...ssr !== void 0 ? { server: {
65
+ ms: ssr,
66
+ up
67
+ } } : {}
68
+ };
69
+ });
70
+ const islands = [];
71
+ for (const p of (s.pages ?? []).slice(1)) islands.push({
72
+ t0: p.t - z,
73
+ t1: p.t - z,
74
+ label: `page load: ${p.url}`,
75
+ tone: "info"
76
+ });
77
+ const hyd = /* @__PURE__ */ new Map();
78
+ for (const e of s.hooks) if (e.hook === "regionHydrated" && e.fp) hyd.set(e.fp, e.at);
79
+ for (const e of s.hooks) {
80
+ const fp = e.fp;
81
+ if (e.hook === "regionWoke" && fp) islands.push({
82
+ t0: e.at - z,
83
+ t1: (hyd.get(fp) ?? e.at) - z,
84
+ label: `${names(fp)} woke (${e.when})`,
85
+ tone: "ok",
86
+ ref: {
87
+ kind: "island",
88
+ fp
89
+ }
90
+ });
91
+ else if (e.hook === "regionFailed" && fp) islands.push({
92
+ t0: e.at - z,
93
+ t1: e.at - z,
94
+ label: `${names(fp)} failed to hydrate`,
95
+ tone: "bad",
96
+ ref: {
97
+ kind: "island",
98
+ fp
99
+ }
100
+ });
101
+ else if (e.hook === "navigated") {
102
+ const nav_ms = e.swapped - e.t;
103
+ islands.push({
104
+ t0: e.at - nav_ms - z,
105
+ t1: e.at - z,
106
+ label: `navigation to ${e.to} — ${Math.round(nav_ms)} ms`,
107
+ tone: nav_ms >= 500 ? "warn" : "info"
108
+ });
109
+ }
110
+ }
111
+ const layout = s.shifts.map((x, i) => {
112
+ let tone = "info";
113
+ if (!x.input) tone = x.value >= .05 ? "bad" : "warn";
114
+ return {
115
+ t0: x.t - z,
116
+ t1: x.t - z,
117
+ label: `layout shift ${x.value}${x.input ? " (after input)" : ""}${x.fp ? ` in ${names(x.fp)}` : ""}`,
118
+ tone,
119
+ ref: {
120
+ kind: "shift",
121
+ i
122
+ }
123
+ };
124
+ });
125
+ const errors = s.errors.map((e) => ({
126
+ t0: e.t - z,
127
+ t1: e.t - z,
128
+ label: e.message,
129
+ tone: "bad"
130
+ }));
131
+ return [
132
+ {
133
+ key: "input",
134
+ label: "input",
135
+ items: cap(input)
136
+ },
137
+ {
138
+ key: "main",
139
+ label: "main thread",
140
+ items: cap(main)
141
+ },
142
+ {
143
+ key: "net",
144
+ label: "requests",
145
+ items: cap(net)
146
+ },
147
+ {
148
+ key: "islands",
149
+ label: "islands · nav",
150
+ items: cap(islands)
151
+ },
152
+ {
153
+ key: "layout",
154
+ label: "layout",
155
+ items: cap(layout)
156
+ },
157
+ {
158
+ key: "errors",
159
+ label: "errors",
160
+ items: cap(errors)
161
+ }
162
+ ].filter((l) => l.items.length);
163
+ }
164
+ const ms = (n) => n >= 1e3 ? `${(n / 1e3).toFixed(2)} s` : `${Math.round(n)} ms`;
165
+ const INTERACTION_FIX = {
166
+ processing: "The handlers are the cost: do less before the next paint (update the screen first, then do the rest in a later task), or move the work off the main thread.",
167
+ input: "The click waited for other work to finish: something else held the main thread when it came (see the long tasks).",
168
+ paint: "Rendering the result is the cost: a big DOM change or an expensive style/layout after it. Change less at once."
169
+ };
170
+ const kb = (n) => {
171
+ if (n < 1024) return `${n} B`;
172
+ return n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1048576).toFixed(1)} MB`;
173
+ };
174
+ const path_of = (u) => {
175
+ try {
176
+ const x = new URL(u);
177
+ return x.pathname + (x.search.length > 1 ? x.search.slice(0, 40) : "");
178
+ } catch {
179
+ return u;
180
+ }
181
+ };
182
+ /** a GET on this page's own origin (the profiler can render only those) */
183
+ function same_origin_get(url, page_url) {
184
+ try {
185
+ return new URL(url).origin === new URL(page_url).origin && !url.includes("/__profiler");
186
+ } catch {
187
+ return false;
188
+ }
189
+ }
190
+ /** Slow from here (Event Timing duration, ms): Google's INP lines. */
191
+ const SLOW = 200;
192
+ const SLUGGISH = 100;
193
+ function analyze_session(s, names, page_url) {
194
+ const findings = [];
195
+ const name_of = (fp) => fp ? names(fp) : "the page";
196
+ const by_id = /* @__PURE__ */ new Map();
197
+ const longest = /* @__PURE__ */ new Map();
198
+ s.interactions.forEach((x, i) => {
199
+ if (!x.id) return;
200
+ longest.set(x.id, Math.max(longest.get(x.id) ?? 0, x.duration));
201
+ const prev = by_id.get(x.id);
202
+ const p = prev === void 0 ? null : s.interactions[prev];
203
+ if (!p || x.processing > p.processing || x.processing === p.processing && x.duration > p.duration) by_id.set(x.id, i);
204
+ });
205
+ for (const [id, i] of by_id) s.interactions[i] = {
206
+ ...s.interactions[i],
207
+ duration: longest.get(id) ?? s.interactions[i].duration
208
+ };
209
+ const chosen = [...by_id.values()];
210
+ let cpu = null;
211
+ if (is_trace(s.cpu)) {
212
+ const windows = chosen.map((i) => ({
213
+ fp: `ix:${i}`,
214
+ from: s.interactions[i].t,
215
+ to: s.interactions[i].t + s.interactions[i].duration
216
+ }));
217
+ cpu = analyze_cpu(s.cpu, windows, s.longtasks, page_url);
218
+ }
219
+ const why = (i) => {
220
+ const f = cpu?.islands[`ix:${i}`]?.top[0];
221
+ if (f && f.self_ms >= 5) return `; mostly ${fn_label(f)}`;
222
+ const x = s.interactions[i];
223
+ const sc = s.frames.find((fr) => fr.t <= x.t + x.duration && fr.t + fr.ms >= x.t && fr.scripts.length)?.scripts.slice().sort((a, b) => b.ms - a.ms)[0];
224
+ return sc && sc.ms >= 5 ? `; mostly ${sc.invoker || sc.fn || "a script"}${sc.source ? ` (${path_of(sc.source).split("/").pop()})` : ""}` : "";
225
+ };
226
+ const slow = chosen.filter((i) => s.interactions[i].duration >= SLUGGISH).sort((a, b) => s.interactions[b].duration - s.interactions[a].duration);
227
+ for (const i of slow.slice(0, 5)) {
228
+ const x = s.interactions[i];
229
+ let part = "paint";
230
+ if (x.processing >= x.input_delay && x.processing >= x.presentation) part = "processing";
231
+ else if (x.input_delay >= x.presentation) part = "input";
232
+ findings.push({
233
+ code: "slow-interaction",
234
+ severity: x.duration >= SLOW ? "warn" : "info",
235
+ message: `${x.name} on ${x.target}${x.fp ? ` in ${name_of(x.fp)}` : ""} took ${ms(x.duration)} to show a result (waiting ${ms(x.input_delay)} · handlers ${ms(x.processing)} · painting ${ms(x.presentation)})${why(i)}.`,
236
+ fix: INTERACTION_FIX[part],
237
+ refs: [{
238
+ kind: "interaction",
239
+ i
240
+ }]
241
+ });
242
+ }
243
+ const rage = [];
244
+ for (let a = 0; a < s.clicks.length; a++) {
245
+ let n = 1;
246
+ for (let b = a + 1; b < s.clicks.length && s.clicks[b].t - s.clicks[a].t < 1e3; b++) if (s.clicks[b].target === s.clicks[a].target) n++;
247
+ if (n >= 3 && !rage.some((r) => s.clicks[r].target === s.clicks[a].target)) rage.push(a);
248
+ }
249
+ for (const i of rage) findings.push({
250
+ code: "rage-click",
251
+ severity: "warn",
252
+ message: `${s.clicks[i].target}${s.clicks[i].fp ? ` in ${name_of(s.clicks[i].fp)}` : ""} was clicked 3+ times within a second: to a visitor it looked like nothing happened.`,
253
+ fix: "Show a reaction at once (a pressed state, a spinner), and make sure the click is handled.",
254
+ refs: [{
255
+ kind: "click",
256
+ i
257
+ }]
258
+ });
259
+ const navs = s.hooks.filter((e) => e.hook === "navStarted").map((e) => e.at);
260
+ const raged = new Set(rage.map((r) => s.clicks[r].target));
261
+ const dead = [];
262
+ const late = [];
263
+ s.clicks.forEach((c, i) => {
264
+ if (raged.has(c.target)) return;
265
+ if (!c.clickable) return;
266
+ if (c.fp) {
267
+ const first = s.mut_log.find((m) => m.t >= c.t && m.t <= c.t + 3e3 && m.fp === c.fp);
268
+ if (!first && !navs.some((t) => t >= c.t && t <= c.t + 3e3)) dead.push(i);
269
+ else if (first && first.t - c.t > 500) late.push({
270
+ i,
271
+ after: first.t - c.t
272
+ });
273
+ return;
274
+ }
275
+ const until = c.t + 500;
276
+ const others = new Set(s.clicks.filter((o, j) => j !== i && o.t >= c.t && o.t <= until && o.fp).map((o) => o.fp));
277
+ const changed = s.mut_log.some((m) => m.t >= c.t && m.t <= until && !others.has(m.fp));
278
+ const asked = s.requests.some((r) => r.t >= c.t && r.t <= until) && !others.size;
279
+ if (!changed && !asked && !navs.some((t) => t >= c.t && t <= until)) dead.push(i);
280
+ });
281
+ if (late.length) findings.push({
282
+ code: "late-feedback",
283
+ severity: "info",
284
+ message: `${late.length} click${late.length === 1 ? "" : "s"} got no visible answer for a while: ${late.slice(0, 3).map(({ i, after }) => `${s.clicks[i].target}${s.clicks[i].fp ? ` in ${name_of(s.clicks[i].fp)}` : ""} (${ms(after)})`).join(", ")}.`,
285
+ fix: "Show a reaction at once — a pressed or loading state — and then the result.",
286
+ refs: late.slice(0, 6).map(({ i }) => ({
287
+ kind: "click",
288
+ i
289
+ }))
290
+ });
291
+ if (dead.length) findings.push({
292
+ code: "dead-click",
293
+ severity: "info",
294
+ message: `${dead.length} click${dead.length === 1 ? "" : "s"} changed nothing on the page (no DOM change, no request, no navigation): ${[...new Set(dead.map((i) => s.clicks[i].target))].slice(0, 3).join(", ")}.`,
295
+ fix: "If it should do something, its handler is missing (an island that never woke, plain HTML with no JS) or it failed silently.",
296
+ refs: dead.slice(0, 6).map((i) => ({
297
+ kind: "click",
298
+ i
299
+ }))
300
+ });
301
+ const lt_ms = s.longtasks.reduce((a, t) => a + t.ms, 0);
302
+ if (s.longtasks.length) {
303
+ const f = cpu?.outside.top[0];
304
+ findings.push({
305
+ code: "long-tasks",
306
+ severity: lt_ms >= 300 ? "warn" : "info",
307
+ message: `${s.longtasks.length} long task${s.longtasks.length === 1 ? "" : "s"} held the main thread for ${ms(lt_ms)} in all (the longest ${ms(Math.max(...s.longtasks.map((t) => t.ms)))})${f && f.self_ms >= 5 ? `; outside the interactions, mostly ${fn_label(f)}` : ""}.`,
308
+ refs: []
309
+ });
310
+ }
311
+ const unexpected = s.shifts.map((x, i) => ({
312
+ x,
313
+ i
314
+ })).filter(({ x }) => !x.input);
315
+ const cls = unexpected.reduce((a, { x }) => a + x.value, 0);
316
+ if (cls >= .02) findings.push({
317
+ code: "unexpected-shift",
318
+ severity: cls >= .1 ? "warn" : "info",
319
+ message: `The layout moved by itself (no input) ${unexpected.length} time${unexpected.length === 1 ? "" : "s"}, CLS ${Math.round(cls * 1e3) / 1e3}${unexpected[0]?.x.fp ? `, first in ${name_of(unexpected[0].x.fp)}` : ""}.`,
320
+ fix: "Reserve space for what arrives late (images, holes, islands that grow as they wake).",
321
+ refs: unexpected.slice(0, 6).map(({ i }) => ({
322
+ kind: "shift",
323
+ i
324
+ }))
325
+ });
326
+ const bytes = s.requests.reduce((a, r) => a + r.bytes, 0);
327
+ const failed = s.requests.filter((r) => r.status !== null && r.status >= 400);
328
+ if (failed.length) findings.push({
329
+ code: "failed-requests",
330
+ severity: "warn",
331
+ message: `${failed.length} request${failed.length === 1 ? "" : "s"} failed: ${failed.slice(0, 3).map((r) => `${r.status} ${path_of(r.url)}`).join(", ")}.`,
332
+ refs: []
333
+ });
334
+ const slow_req = s.requests.filter((r) => r.ms >= 1e3).sort((a, b) => b.ms - a.ms);
335
+ if (slow_req.length) findings.push({
336
+ code: "slow-requests",
337
+ severity: "info",
338
+ message: `${slow_req.length} request${slow_req.length === 1 ? "" : "s"} took over a second: ${slow_req.slice(0, 3).map((r) => `${path_of(r.url)} ${ms(r.ms)}`).join(", ")}.`,
339
+ refs: []
340
+ });
341
+ const by_url = /* @__PURE__ */ new Map();
342
+ for (const r of s.requests) if (r.type === "fetch" || r.type === "xmlhttprequest") by_url.set(path_of(r.url), (by_url.get(path_of(r.url)) ?? 0) + 1);
343
+ const repeated = [...by_url].filter(([, n]) => n >= 3).sort((a, b) => b[1] - a[1]);
344
+ if (repeated.length) findings.push({
345
+ code: "repeated-requests",
346
+ severity: "info",
347
+ message: `The same request went out again and again: ${repeated.slice(0, 3).map(([u, n]) => `${u} ×${n}`).join(", ")}.`,
348
+ fix: "Cache the answer, or share one request between the parts that ask.",
349
+ refs: []
350
+ });
351
+ const st = (r, name) => r.server?.find((x) => x.name === name);
352
+ const served = s.requests.filter((r) => st(r, "ssr")).sort((a, b) => (st(b, "ssr")?.ms ?? 0) - (st(a, "ssr")?.ms ?? 0));
353
+ for (const r of served.slice(0, 3)) {
354
+ const ssr = st(r, "ssr").ms;
355
+ if (ssr < 200) break;
356
+ const cpu_ms = st(r, "cpu")?.ms;
357
+ const net = st(r, "net");
358
+ const up = st(r, "up1");
359
+ findings.push({
360
+ code: "server-time",
361
+ severity: ssr >= 500 ? "warn" : "info",
362
+ message: `${path_of(r.url)} took ${ms(r.ms)}: ${ms(ssr)} on the server${cpu_ms !== void 0 ? ` (${ms(cpu_ms)} of CPU)` : ""}${net ? `, ${ms(net.ms)} of it waiting on ${net.desc.split("(")[1]?.split(")")[0] ?? "several"} outbound call${net.desc.includes("(1)") ? "" : "s"}${up ? ` — the slowest ${up.desc} ${ms(up.ms)}` : ""}` : ""}, ${ms(Math.max(0, r.ms - ssr))} on the network.`,
363
+ fix: net && net.ms >= ssr * .5 ? "The server mostly waited: start the calls together, cache the answer, or move the call out of this request." : "Profile it on the server (the button) to see where its time went.",
364
+ refs: (() => {
365
+ const c = s.clicks.filter((x) => x.t <= r.t && r.t - x.t <= 3e3).at(-1);
366
+ return c ? [{
367
+ kind: "click",
368
+ i: s.clicks.indexOf(c)
369
+ }] : [];
370
+ })(),
371
+ ...same_origin_get(r.url, page_url) ? { url: r.url } : {}
372
+ });
373
+ }
374
+ const by_island = {};
375
+ const slot = (fp) => by_island[fp] ??= {
376
+ clicks: 0,
377
+ slow: [],
378
+ requests: [],
379
+ mutations: 0
380
+ };
381
+ for (const c of s.clicks) if (c.fp) slot(c.fp).clicks++;
382
+ for (const i of chosen) {
383
+ const x = s.interactions[i];
384
+ if (x.fp && x.duration >= SLUGGISH) slot(x.fp).slow.push({
385
+ target: x.target,
386
+ duration: x.duration,
387
+ processing: x.processing
388
+ });
389
+ }
390
+ for (const r of s.requests) {
391
+ const c = s.clicks.filter((x) => x.t <= r.t && r.t - x.t <= 3e3).at(-1);
392
+ if (!c?.fp) continue;
393
+ slot(c.fp).requests.push({
394
+ url: path_of(r.url),
395
+ ms: r.ms,
396
+ server_ms: st(r, "ssr")?.ms ?? null,
397
+ net_ms: st(r, "net")?.ms ?? null,
398
+ up: st(r, "up1") ? `${st(r, "up1").desc} ${ms(st(r, "up1").ms)}` : null,
399
+ status: r.status
400
+ });
401
+ }
402
+ for (const m of s.mutations) if (m.fp && by_island[m.fp]) by_island[m.fp].mutations = m.count;
403
+ const woke = s.hooks.filter((e) => e.hook === "regionWoke");
404
+ if (woke.length) {
405
+ const done = /* @__PURE__ */ new Map();
406
+ for (const e of s.hooks) if (e.hook === "regionHydrated" && e.fp) done.set(e.fp, e.tDone - e.t0);
407
+ const list = woke.map((e) => {
408
+ const took = e.fp ? done.get(e.fp) : void 0;
409
+ return e.fp ? `${name_of(e.fp)}${took !== void 0 ? ` (${ms(took)})` : ""}` : "an island";
410
+ });
411
+ findings.push({
412
+ code: "islands-woke",
413
+ severity: "info",
414
+ message: `${woke.length} island${woke.length === 1 ? "" : "s"} woke during the session: ${[...new Set(list)].slice(0, 5).join(", ")}.`,
415
+ refs: woke.flatMap((e) => e.fp ? [e.fp] : []).slice(0, 6).map((fp) => ({
416
+ kind: "island",
417
+ fp
418
+ }))
419
+ });
420
+ }
421
+ for (const e of s.hooks) if (e.hook === "regionFailed") findings.push({
422
+ code: "hydrate-failed",
423
+ severity: "error",
424
+ message: `${name_of(e.fp ?? null)} failed to hydrate: ${e.message.split("\n")[0].slice(0, 160)}.`,
425
+ refs: e.fp ? [{
426
+ kind: "island",
427
+ fp: e.fp
428
+ }] : []
429
+ });
430
+ else if (e.hook === "regionMismatched" && e.kind === "recovered") findings.push({
431
+ code: "hydrate-recovered",
432
+ severity: "error",
433
+ message: `${name_of(e.fp ?? null)} threw away its server HTML and rendered again${e.reason ? `: ${e.reason}` : ""}.`,
434
+ refs: e.fp ? [{
435
+ kind: "island",
436
+ fp: e.fp
437
+ }] : []
438
+ });
439
+ else if (e.hook === "regionMismatched" && e.kind === "healed") findings.push({
440
+ code: "hydrate-healed",
441
+ severity: "warn",
442
+ message: `${name_of(e.fp ?? null)}'s markup was changed by another script before it woke; the runtime put the server markup back${e.reason ? ` (${e.reason})` : ""}.`,
443
+ refs: e.fp ? [{
444
+ kind: "island",
445
+ fp: e.fp
446
+ }] : []
447
+ });
448
+ else if (e.hook === "regionMismatched" && e.kind === "conflict") findings.push({
449
+ code: "hydrate-conflict",
450
+ severity: "warn",
451
+ message: `${name_of(e.fp ?? null)}: ${e.reason ?? "a web component"} changed its own children where Svelte's hydration reads, so the repair removed what it added (render it with {@html}, put it in a lake, or mark it data-ogygia-keep).`,
452
+ refs: e.fp ? [{
453
+ kind: "island",
454
+ fp: e.fp
455
+ }] : []
456
+ });
457
+ else if (e.hook === "criticalSettled" && e.outcome === "cap") findings.push({
458
+ code: "critical-cap",
459
+ severity: "warn",
460
+ message: `The page's critical resource${e.resources === 1 ? "" : "s"} (marked fetchpriority="high") took longer than ${e.waitedMs} ms; ogygia stopped holding its downloads back and let them start.`,
461
+ refs: []
462
+ });
463
+ const held = s.hooks.flatMap((e) => e.hook === "loadStarted" && e.class !== "user" && e.waitedMs > 0 ? [e.waitedMs] : []);
464
+ if (held.length) {
465
+ const most = Math.max(...held);
466
+ findings.push({
467
+ code: "loads-held",
468
+ severity: "info",
469
+ message: `ogygia held ${held.length} download${held.length === 1 ? "" : "s"} back (up to ${most} ms) so the page's critical resources and the visible islands went first.`,
470
+ refs: []
471
+ });
472
+ }
473
+ const errors = s.hooks.some((e) => e.hook === "regionFailed") ? s.errors.filter((e) => !(e.message.startsWith("console.error: OgygiaError: [ogygia] hydration failed") || e.message.includes("ogygiajs.dev/e/island_hydrate_failed"))) : s.errors;
474
+ if (errors.length) findings.push({
475
+ code: "errors",
476
+ severity: "error",
477
+ message: `${errors.length} error${errors.length === 1 ? "" : "s"}: ${[...new Set(errors.map((e) => e.message.split("\n")[0].trim()))].slice(0, 3).join(" · ")}.`,
478
+ refs: []
479
+ });
480
+ for (const m of s.mutations.slice(0, 3)) {
481
+ if (m.count < 300) break;
482
+ findings.push({
483
+ code: "dom-churn",
484
+ severity: "info",
485
+ message: `${m.fp ? name_of(m.fp) : "Code outside any island"} changed the DOM ${m.count} times during the session${m.fp ? "" : " (page scripts, a third-party tag)"}.`,
486
+ fix: "Lots of small changes often mean a re-render on every event: batch them, or key the list so unchanged rows stay.",
487
+ refs: m.fp ? [{
488
+ kind: "island",
489
+ fp: m.fp
490
+ }] : []
491
+ });
492
+ }
493
+ if (s.heap && s.heap.to - s.heap.from >= 5242880) findings.push({
494
+ code: "heap-growth",
495
+ severity: "info",
496
+ message: `The JS heap grew by ${kb(s.heap.to - s.heap.from)} during the session (${kb(s.heap.from)} → ${kb(s.heap.to)}). If it keeps growing across the same actions, something is kept (a listener, a cache, a closed island's state).`,
497
+ refs: []
498
+ });
499
+ for (const e of s.hooks) {
500
+ if (e.hook !== "navigated") continue;
501
+ const nav_ms = e.swapped - e.t;
502
+ if (nav_ms >= 500) findings.push({
503
+ code: "slow-navigation",
504
+ severity: "info",
505
+ message: `The navigation to ${e.to} took ${ms(nav_ms)}${e.reconciled ? "" : " (a full swap, not reconciled)"}.`,
506
+ refs: []
507
+ });
508
+ }
509
+ const order = {
510
+ error: 0,
511
+ warn: 1,
512
+ info: 2
513
+ };
514
+ findings.sort((a, b) => order[a.severity] - order[b.severity]);
515
+ return {
516
+ duration_ms: Math.round(s.to - s.from),
517
+ counts: {
518
+ interactions: chosen.length,
519
+ slow: slow.length,
520
+ longtasks: s.longtasks.length,
521
+ longtask_ms: Math.round(lt_ms),
522
+ requests: s.requests.length,
523
+ request_bytes: bytes,
524
+ errors: s.errors.length,
525
+ shifts: unexpected.length,
526
+ cls: Math.round(cls * 1e3) / 1e3,
527
+ mutations: s.mutations.reduce((a, m) => a + m.count, 0),
528
+ pages: Math.max(1, s.pages?.length ?? 1)
529
+ },
530
+ findings,
531
+ interactions: chosen.map((i) => ({
532
+ i,
533
+ t: s.interactions[i].t,
534
+ name: s.interactions[i].name,
535
+ duration: s.interactions[i].duration,
536
+ target: s.interactions[i].target,
537
+ fp: s.interactions[i].fp
538
+ })).sort((a, b) => b.duration - a.duration).slice(0, 12),
539
+ by_island,
540
+ requests: [...s.requests].filter((r) => r.type === "fetch" || r.type === "xmlhttprequest" || r.server?.length).sort((a, b) => b.ms - a.ms).slice(0, 12).map((r) => ({
541
+ url: path_of(r.url),
542
+ ms: r.ms,
543
+ status: r.status,
544
+ server_ms: st(r, "ssr")?.ms ?? null,
545
+ cpu_ms: st(r, "cpu")?.ms ?? null,
546
+ net_ms: st(r, "net")?.ms ?? null,
547
+ up: st(r, "up1") ? `${st(r, "up1").desc} ${ms(st(r, "up1").ms)}` : null
548
+ })),
549
+ failed: s.requests.filter((r) => r.status !== null && r.status >= 400).map((r) => ({
550
+ url: r.url,
551
+ status: r.status,
552
+ type: r.type,
553
+ t: r.t
554
+ })),
555
+ by_element: Object.values(s.interactions.reduce((acc, x) => {
556
+ const cur = acc[x.target];
557
+ if (!cur || x.duration > cur.duration) acc[x.target] = {
558
+ target: x.target,
559
+ duration: x.duration,
560
+ processing: x.processing,
561
+ t: x.t,
562
+ fp: x.fp
563
+ };
564
+ return acc;
565
+ }, Object.fromEntries(s.clicks.map((c) => [c.target, {
566
+ target: c.target,
567
+ duration: 0,
568
+ processing: 0,
569
+ t: c.t,
570
+ fp: c.fp
571
+ }])))).sort((a, b) => b.duration - a.duration),
572
+ cpu
573
+ };
574
+ }
575
+ export { analyze_session, session_timeline };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The report shape the page's testing engine answers (`window.__ogygia_testing.version`). The engine
3
+ * ships with the SITE's build and `@ogygia/testing` with the TEST's package, so the two can differ: the
4
+ * test side reads this from the page, fills in what it can for an older engine, and warns once.
5
+ *
6
+ * Each version, and what it DETECTS differently (results across two versions compare only where
7
+ * nothing below changed):
8
+ *
9
+ * 1 — 0.8.2.
10
+ * 2 — hydration `key`, session `navigations` (with what started each), finding `names`, `counts.cls`,
11
+ * `engine` on every report, hydration `t0` / `done`. Detection: a router navigation that never
12
+ * swapped the page no longer starts a new page for `page()`. Hydration status: unchanged from 1 (an
13
+ * island that reads `clean` on one and `changed` on the other differed in that run — input landing
14
+ * while it hydrated is the usual cause; 3 flags it as `input`).
15
+ * 3 — hydration `change` (`attributes` / `markup`), `attributes`, `input`, `ignoreAttributes`; page
16
+ * `ogygia` (what measuring cost). Detection: unchanged — `changed` means what it meant in 2; the new
17
+ * fields only say what kind of change it was.
18
+ */
19
+ export declare const TESTING_ENGINE_VERSION = 3;
@@ -0,0 +1,21 @@
1
+ // src/testing-version.ts
2
+ /**
3
+ * The report shape the page's testing engine answers (`window.__ogygia_testing.version`). The engine
4
+ * ships with the SITE's build and `@ogygia/testing` with the TEST's package, so the two can differ: the
5
+ * test side reads this from the page, fills in what it can for an older engine, and warns once.
6
+ *
7
+ * Each version, and what it DETECTS differently (results across two versions compare only where
8
+ * nothing below changed):
9
+ *
10
+ * 1 — 0.8.2.
11
+ * 2 — hydration `key`, session `navigations` (with what started each), finding `names`, `counts.cls`,
12
+ * `engine` on every report, hydration `t0` / `done`. Detection: a router navigation that never
13
+ * swapped the page no longer starts a new page for `page()`. Hydration status: unchanged from 1 (an
14
+ * island that reads `clean` on one and `changed` on the other differed in that run — input landing
15
+ * while it hydrated is the usual cause; 3 flags it as `input`).
16
+ * 3 — hydration `change` (`attributes` / `markup`), `attributes`, `input`, `ignoreAttributes`; page
17
+ * `ogygia` (what measuring cost). Detection: unchanged — `changed` means what it meant in 2; the new
18
+ * fields only say what kind of change it was.
19
+ */
20
+ const TESTING_ENGINE_VERSION = 3;
21
+ export { TESTING_ENGINE_VERSION };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * THIRD PARTIES — what other origins cost this page, from what the browser measured: their files and
3
+ * bytes (resource timing), the ones that held the first paint, the scripts that loaded more scripts
4
+ * at runtime (a tag manager's shape), and their main-thread time when there is a CPU trace. Pure, so
5
+ * the devtools Page tab and the profiler report run the same analysis on the same visit.
6
+ *
7
+ * Detection is by behavior (another origin; blocking; CPU; a script whose arrival is followed by
8
+ * scripts nothing in the page names). The host table only puts a readable label on well-known
9
+ * public services — a host it does not know is still measured, as "other".
10
+ */
11
+ export type ThirdPartyKind = "tag manager" | "analytics" | "ads" | "session replay" | "chat" | "a/b testing" | "consent" | "fonts" | "library cdn" | "other";
12
+ export declare function kind_of_host(host: string): ThirdPartyKind;
13
+ export interface ThirdPartyOrigin {
14
+ host: string;
15
+ kind: ThirdPartyKind;
16
+ files: number;
17
+ scripts: number;
18
+ /** decoded bytes of its scripts */
19
+ script_bytes: number;
20
+ /** its scripts the browser gave no size for (some engines hide every other origin's sizes,
21
+ * even with Timing-Allow-Origin): `script_bytes` leaves them out */
22
+ unsized: number;
23
+ /** every byte on the wire */
24
+ wire: number;
25
+ /** files that held the first paint */
26
+ blocking: number;
27
+ /** when its first file started (ms from navigation) */
28
+ first: number;
29
+ /** main-thread ms in its scripts (a CPU trace), else null */
30
+ cpu_ms: number | null;
31
+ }
32
+ export interface ThirdParty {
33
+ origins: ThirdPartyOrigin[];
34
+ script_bytes: number;
35
+ unsized: number;
36
+ /** scripts whose size the browser hid and that were weighed apart from the visit */
37
+ weighed: number;
38
+ wire: number;
39
+ blocking: number;
40
+ cpu_ms: number | null;
41
+ /** third-party scripts that started after another third-party script arrived and that no
42
+ * document ref names: loaded at runtime (by a tag manager, a loader) */
43
+ runtime_loaded: number;
44
+ }
45
+ interface Res {
46
+ url: string;
47
+ type: string;
48
+ start: number;
49
+ end: number;
50
+ transfer?: number;
51
+ size?: number;
52
+ blocking?: boolean;
53
+ /** a size the browser hid, weighed apart from the visit */
54
+ weighed?: true;
55
+ }
56
+ /** `named`: URLs the server's HTML references (its scripts, preloads, their imports) — another
57
+ * origin's script not among them came at runtime. Without it (the live page already holds the
58
+ * injected script elements), `parsed`: when the HTML was parsed (domInteractive) — a script that
59
+ * starts after that and after another origin's script ran was loaded by a script. `in_page`: the
60
+ * URLs the live document holds — a script no element names came by an import or a fetch (a
61
+ * self-loading library's parts), whenever it started. */
62
+ export declare function third_party(resources: readonly Res[], page_origin: string, cpu_by_host: ReadonlyMap<string, number> | null, named?: ReadonlySet<string>, parsed?: number, in_page?: ReadonlySet<string>): ThirdParty | null;
63
+ export interface ThirdPartyFinding {
64
+ code: string;
65
+ severity: "warn" | "info";
66
+ message: string;
67
+ fix?: string;
68
+ }
69
+ /** `edited`: islands that did not wake from the server's markup on this visit (changed, recovered,
70
+ * healed, failed), with when they woke (ms; Infinity when unknown or never). */
71
+ export declare function third_party_findings(tp: ThirdParty | null, edited?: readonly {
72
+ name: string;
73
+ done: number;
74
+ }[]): ThirdPartyFinding[];
75
+ export {};