sugikit 0.0.1 → 0.1.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.
Files changed (72) hide show
  1. package/LICENSE +29 -21
  2. package/README.md +45 -0
  3. package/dist/api/browser.d.ts +5 -0
  4. package/dist/api/browser.js +5 -0
  5. package/dist/api/rules.d.ts +12 -0
  6. package/dist/api/rules.js +14 -0
  7. package/dist/auth.d.ts +156 -0
  8. package/dist/auth.js +547 -0
  9. package/dist/browser.d.ts +25 -0
  10. package/dist/browser.js +120 -0
  11. package/dist/check.d.ts +21 -0
  12. package/dist/check.js +89 -0
  13. package/dist/convert-probe.d.ts +21 -0
  14. package/dist/convert-probe.js +647 -0
  15. package/dist/fetch.d.ts +6 -0
  16. package/dist/fetch.js +22 -0
  17. package/dist/framework.d.ts +2 -0
  18. package/dist/framework.js +17 -0
  19. package/dist/gather.d.ts +48 -0
  20. package/dist/gather.js +211 -0
  21. package/dist/html.d.ts +17 -0
  22. package/dist/html.js +43 -0
  23. package/dist/http.d.ts +36 -0
  24. package/dist/http.js +57 -0
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.js +331 -0
  27. package/dist/links.d.ts +8 -0
  28. package/dist/links.js +69 -0
  29. package/dist/polish-run.d.ts +115 -0
  30. package/dist/polish-run.js +357 -0
  31. package/dist/probe.d.ts +14 -0
  32. package/dist/probe.js +457 -0
  33. package/dist/psi-scores.d.ts +4 -0
  34. package/dist/psi-scores.js +7 -0
  35. package/dist/psi.d.ts +56 -0
  36. package/dist/psi.js +192 -0
  37. package/dist/release.d.ts +1 -0
  38. package/dist/release.js +5 -0
  39. package/dist/render.d.ts +28 -0
  40. package/dist/render.js +270 -0
  41. package/dist/report.d.ts +227 -0
  42. package/dist/report.js +69 -0
  43. package/dist/rules/convert-render.d.ts +100 -0
  44. package/dist/rules/convert-render.js +279 -0
  45. package/dist/rules/convert.d.ts +15 -0
  46. package/dist/rules/convert.js +322 -0
  47. package/dist/rules/fixes.d.ts +16 -0
  48. package/dist/rules/fixes.js +536 -0
  49. package/dist/rules/geo.d.ts +15 -0
  50. package/dist/rules/geo.js +112 -0
  51. package/dist/rules/polish.d.ts +59 -0
  52. package/dist/rules/polish.js +223 -0
  53. package/dist/rules/robots.d.ts +14 -0
  54. package/dist/rules/robots.js +69 -0
  55. package/dist/rules/seo.d.ts +31 -0
  56. package/dist/rules/seo.js +208 -0
  57. package/dist/rules/types.d.ts +55 -0
  58. package/dist/rules/types.js +78 -0
  59. package/dist/score.d.ts +6 -0
  60. package/dist/score.js +23 -0
  61. package/dist/skills.d.ts +9 -0
  62. package/dist/skills.js +22 -0
  63. package/package.json +64 -4
  64. package/skills/INSTALL_PROMPT.md +9 -0
  65. package/skills/sugikit/SKILL.md +147 -0
  66. package/skills/sugikit/references/convert.md +127 -0
  67. package/skills/sugikit/references/geo.md +97 -0
  68. package/skills/sugikit/references/next.md +254 -0
  69. package/skills/sugikit/references/pagespeed.md +94 -0
  70. package/skills/sugikit/references/polish.md +123 -0
  71. package/skills/sugikit/references/seo.md +150 -0
  72. package/skills/sugikit/references/tanstack-start.md +246 -0
@@ -0,0 +1,647 @@
1
+ // Conversion probes. Like probe.ts, these run inside the page through page.evaluate, so each one is
2
+ // self-contained (no imports at runtime, only types).
3
+ //
4
+ // Primary CTA detection (shared by every render convert check):
5
+ // 1. Clickables are a[href], button, [role=button], input type submit or button that are visible and have
6
+ // their center in the first screen (scrollY 0). Boxes over 40% of the screen (card links) do not count.
7
+ // 2. Filled: the element paints its own background (alpha 0.5 or more, or a gradient) and that fill differs
8
+ // from the background behind it (contrast 1.2:1 or more). Outlined and text buttons are not filled.
9
+ // 3. The primary CTA is the largest filled clickable whose label has an action word (get, start, try, buy,
10
+ // sign up, join, download, install, book, request, subscribe, create). Without one, it is the most salient
11
+ // filled clickable. Without a filled clickable there is no primary CTA.
12
+ // Salience is box area x contrast: the fill contrast for filled elements, a fifth of the text contrast for
13
+ // text links (text covers only part of its box).
14
+ export function heroProbe() {
15
+ const CLICKABLE_SELECTOR = 'a[href], button, [role="button"], input[type="submit" i], input[type="button" i]';
16
+ const ACTION = /\b(get|start|try|buy|sign ?up|join|download|install|book|request|subscribe|create)\b/i;
17
+ const PRICE = /[$€£]\s?\d[\d.,]*|\d[\d.,]*\s?(USD|EUR|GBP)\b/;
18
+ const PRICING = /pricing|plans?\b|price/i;
19
+ const FLOOR_BAND = 0.15;
20
+ const root = document.documentElement;
21
+ const body = document.body;
22
+ const vw = window.innerWidth;
23
+ const vh = window.innerHeight;
24
+ const scrollY = window.scrollY;
25
+ const describe = (el) => {
26
+ const parts = [];
27
+ for (let node = el; node && node !== root && parts.length < 3; node = node.parentElement) {
28
+ if (node.id) {
29
+ parts.unshift(`#${CSS.escape(node.id)}`);
30
+ break;
31
+ }
32
+ const classes = Array.from(node.classList)
33
+ .filter((c) => c.length <= 30)
34
+ .slice(0, 2)
35
+ .map((c) => `.${CSS.escape(c)}`)
36
+ .join("");
37
+ parts.unshift(`${node.tagName.toLowerCase()}${classes}`);
38
+ if (node === body)
39
+ break;
40
+ }
41
+ return parts.join(" > ");
42
+ };
43
+ const boxOf = (el) => {
44
+ const r = el.getBoundingClientRect();
45
+ return { top: r.top + scrollY, bottom: r.bottom + scrollY, left: r.left, right: r.right, width: r.width, height: r.height };
46
+ };
47
+ const visible = (el) => {
48
+ const r = el.getBoundingClientRect();
49
+ if (r.width <= 1 || r.height <= 1)
50
+ return false;
51
+ if (!el.checkVisibility({ opacityProperty: true, visibilityProperty: true }))
52
+ return false;
53
+ return !el.closest("[aria-hidden='true'], [inert]");
54
+ };
55
+ const squash = (text) => text.replace(/\s+/g, " ").trim();
56
+ const labelOf = (el) => {
57
+ const aria = el.getAttribute("aria-label");
58
+ const text = el instanceof HTMLInputElement ? el.value : el.innerText;
59
+ return squash(aria || text || el.getAttribute("title") || "").slice(0, 60);
60
+ };
61
+ // Colors through a 1x1 canvas, so oklch(), color() and named colors all come back as sRGB bytes.
62
+ const canvas = document.createElement("canvas");
63
+ canvas.width = 1;
64
+ canvas.height = 1;
65
+ const paint = canvas.getContext("2d", { willReadFrequently: true });
66
+ const rgba = (color) => {
67
+ if (!paint)
68
+ return [0, 0, 0, 0];
69
+ paint.clearRect(0, 0, 1, 1);
70
+ paint.fillStyle = "rgba(0, 0, 0, 0)";
71
+ paint.fillStyle = color;
72
+ paint.fillRect(0, 0, 1, 1);
73
+ const [r = 0, g = 0, b = 0, a = 0] = paint.getImageData(0, 0, 1, 1).data;
74
+ return [r, g, b, a / 255];
75
+ };
76
+ const over = (top, under) => {
77
+ const a = top[3];
78
+ return [top[0] * a + under[0] * (1 - a), top[1] * a + under[1] * (1 - a), top[2] * a + under[2] * (1 - a), 1];
79
+ };
80
+ const luminance = (c) => {
81
+ const ch = (v) => {
82
+ const s = v / 255;
83
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
84
+ };
85
+ return 0.2126 * ch(c[0]) + 0.7152 * ch(c[1]) + 0.0722 * ch(c[2]);
86
+ };
87
+ const contrast = (a, b) => {
88
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
89
+ return (hi + 0.05) / (lo + 0.05);
90
+ };
91
+ // The average of the color stops of a gradient, or undefined for images.
92
+ const gradientColor = (image) => {
93
+ if (!/gradient\(/.test(image))
94
+ return undefined;
95
+ const stops = image.match(/(rgba?|oklch|oklab|lab|lch|hsla?|color)\([^()]*\)|#[0-9a-f]{3,8}\b/gi) ?? [];
96
+ if (stops.length === 0)
97
+ return undefined;
98
+ const colors = stops.map(rgba);
99
+ const sum = colors.reduce((acc, c) => [acc[0] + c[0], acc[1] + c[1], acc[2] + c[2], acc[3] + c[3]], [0, 0, 0, 0]);
100
+ return [sum[0] / colors.length, sum[1] / colors.length, sum[2] / colors.length, sum[3] / colors.length];
101
+ };
102
+ // The element's own fill: its background color, or the average of its gradient.
103
+ const fillOf = (el) => {
104
+ const style = getComputedStyle(el);
105
+ const gradient = gradientColor(style.backgroundImage);
106
+ if (gradient && gradient[3] >= 0.5)
107
+ return gradient;
108
+ const color = rgba(style.backgroundColor);
109
+ return color[3] >= 0.5 ? color : undefined;
110
+ };
111
+ // The opaque color behind an element: ancestor backgrounds composed from the root down, over white.
112
+ // undefined when an ancestor paints an image (the real color behind is unknown).
113
+ const behind = (el) => {
114
+ const layers = [];
115
+ for (let node = el.parentElement; node; node = node.parentElement) {
116
+ const style = getComputedStyle(node);
117
+ const gradient = gradientColor(style.backgroundImage);
118
+ if (gradient) {
119
+ layers.push(gradient);
120
+ if (gradient[3] >= 1)
121
+ break;
122
+ }
123
+ else if (style.backgroundImage !== "none") {
124
+ return undefined;
125
+ }
126
+ const color = rgba(style.backgroundColor);
127
+ if (color[3] > 0)
128
+ layers.push(color);
129
+ if (color[3] >= 1)
130
+ break;
131
+ }
132
+ let base = [255, 255, 255, 1];
133
+ for (const layer of layers.reverse())
134
+ base = over(layer, base);
135
+ return base;
136
+ };
137
+ const all = Array.from(document.querySelectorAll(CLICKABLE_SELECTOR));
138
+ const screenArea = vw * vh;
139
+ const measure = (el, index) => {
140
+ if (!visible(el))
141
+ return undefined;
142
+ const box = boxOf(el);
143
+ const area = box.width * box.height;
144
+ if (area > 0.4 * screenArea)
145
+ return undefined;
146
+ const back = behind(el);
147
+ const fill = fillOf(el);
148
+ const text = rgba(getComputedStyle(el).color);
149
+ const fillOnBack = fill && back ? over(fill, back) : undefined;
150
+ const fillContrast = fillOnBack && back ? contrast(fillOnBack, back) : 0;
151
+ const filled = fill !== undefined && (back === undefined || fillContrast >= 1.2);
152
+ const textBack = fillOnBack ?? back;
153
+ const labelContrast = textBack ? contrast(over(text, textBack), textBack) : 0;
154
+ const label = labelOf(el);
155
+ const salience = filled ? area * Math.max(fillContrast, 1) : area * Math.max(labelContrast, 1) * 0.2;
156
+ const href = el instanceof HTMLAnchorElement ? el.href : undefined;
157
+ const rawHref = el.getAttribute("href") ?? undefined;
158
+ return {
159
+ selector: describe(el),
160
+ index,
161
+ tag: el.tagName.toLowerCase(),
162
+ label,
163
+ ...(href !== undefined ? { href } : {}),
164
+ ...(rawHref !== undefined ? { rawHref } : {}),
165
+ box,
166
+ filled,
167
+ labelContrast: Math.round(labelContrast * 100) / 100,
168
+ fillContrast: Math.round(fillContrast * 100) / 100,
169
+ salience,
170
+ action: ACTION.test(label),
171
+ };
172
+ };
173
+ const centerInFirstScreen = (box) => {
174
+ const cy = (box.top + box.bottom) / 2;
175
+ const cx = (box.left + box.right) / 2;
176
+ return cy >= 0 && cy < vh && cx >= 0 && cx < vw;
177
+ };
178
+ const measured = all.map((el, index) => (el.parentElement?.closest(CLICKABLE_SELECTOR) ? undefined : measure(el, index)));
179
+ const first = measured.filter((c) => c !== undefined && centerInFirstScreen(c.box) && c.label !== "");
180
+ const bySalience = (a, b) => b.salience - a.salience;
181
+ const filled = first.filter((c) => c.filled).sort(bySalience);
182
+ const withAction = filled.filter((c) => c.action).sort((a, b) => b.box.width * b.box.height - a.box.width * a.box.height);
183
+ const primaryPick = withAction[0] ?? filled[0];
184
+ const primary = primaryPick ? { ...primaryPick, reason: withAction[0] ? "action" : "salient" } : undefined;
185
+ const h1El = Array.from(document.querySelectorAll("h1")).find(visible);
186
+ const h1 = h1El ? { selector: describe(h1El), text: squash(h1El.innerText).slice(0, 80), box: boxOf(h1El) } : undefined;
187
+ // False floor: what shows in the bottom band of the first screen (fixed and sticky layers do not count).
188
+ const floor = [];
189
+ const pinned = new Map();
190
+ const isPinned = (el) => {
191
+ if (!el || el === root)
192
+ return false;
193
+ const known = pinned.get(el);
194
+ if (known !== undefined)
195
+ return known;
196
+ const position = getComputedStyle(el).position;
197
+ const value = position === "fixed" || position === "sticky" || isPinned(el.parentElement);
198
+ pinned.set(el, value);
199
+ return value;
200
+ };
201
+ const bandTop = scrollY + vh * (1 - FLOOR_BAND);
202
+ const bandBottom = scrollY + vh;
203
+ const inBand = (box) => box.top < bandBottom && box.bottom > bandTop;
204
+ if (body) {
205
+ const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
206
+ for (let node = walker.nextNode(); node && floor.length < 3; node = walker.nextNode()) {
207
+ const parent = node.parentElement;
208
+ const text = squash(node.textContent ?? "");
209
+ if (!parent || !text || parent.closest("script, style, noscript, template"))
210
+ continue;
211
+ const range = document.createRange();
212
+ range.selectNodeContents(node);
213
+ const r = range.getBoundingClientRect();
214
+ if (r.width <= 1 || r.height <= 1)
215
+ continue;
216
+ const box = { top: r.top + scrollY, bottom: r.bottom + scrollY, left: r.left, right: r.right, width: r.width, height: r.height };
217
+ if (inBand(box) && visible(parent) && !isPinned(parent))
218
+ floor.push(`text "${text.slice(0, 40)}"`);
219
+ }
220
+ for (const el of Array.from(body.querySelectorAll("img, svg, video, canvas, picture, iframe, input, button, hr"))) {
221
+ if (floor.length >= 3)
222
+ break;
223
+ if (el.parentElement?.closest("svg, picture, button"))
224
+ continue;
225
+ if (visible(el) && !isPinned(el) && inBand(boxOf(el)))
226
+ floor.push(`${el.tagName.toLowerCase()} ${describe(el)}`);
227
+ }
228
+ // A section with its own background whose top edge shows in the band.
229
+ for (const el of Array.from(body.querySelectorAll("section, header, footer, article, aside, div"))) {
230
+ if (floor.length >= 3)
231
+ break;
232
+ const box = boxOf(el);
233
+ if (box.top < bandTop || box.top >= bandBottom || !visible(el) || isPinned(el))
234
+ continue;
235
+ const style = getComputedStyle(el);
236
+ const painted = rgba(style.backgroundColor)[3] > 0 || style.backgroundImage !== "none" || parseFloat(style.borderTopWidth) > 0;
237
+ if (painted)
238
+ floor.push(`section top ${describe(el)}`);
239
+ }
240
+ }
241
+ // CTA targets: the primary CTA, then CTAs inside a pricing section (filled or with an action word).
242
+ const targets = [];
243
+ const seen = new Set();
244
+ const addTarget = (c, kind) => {
245
+ if (targets.length >= 4)
246
+ return;
247
+ const el = all[c.index];
248
+ const key = c.href ?? `${c.tag}:${c.label}`;
249
+ if (!el || seen.has(key))
250
+ return;
251
+ seen.add(key);
252
+ let hashTarget;
253
+ if (el instanceof HTMLAnchorElement && c.rawHref?.startsWith("#") && c.rawHref.length > 1) {
254
+ let id = c.rawHref.slice(1);
255
+ try {
256
+ id = decodeURIComponent(id);
257
+ }
258
+ catch {
259
+ // keep the raw fragment
260
+ }
261
+ hashTarget = document.getElementById(id) !== null || document.getElementsByName(id).length > 0;
262
+ }
263
+ targets.push({
264
+ kind,
265
+ selector: c.selector,
266
+ index: c.index,
267
+ tag: c.tag,
268
+ label: c.label,
269
+ ...(c.href !== undefined ? { href: c.href } : {}),
270
+ ...(c.rawHref !== undefined ? { rawHref: c.rawHref } : {}),
271
+ ...(hashTarget !== undefined ? { hashTarget } : {}),
272
+ });
273
+ };
274
+ if (primary)
275
+ addTarget(primary, "primary");
276
+ const pricingSections = Array.from(document.querySelectorAll("section, div, article")).filter((el) => {
277
+ if (PRICING.test(`${el.id} ${typeof el.className === "string" ? el.className : ""}`))
278
+ return true;
279
+ const heading = el.querySelector("h1, h2, h3");
280
+ return el.tagName !== "DIV" && heading !== null && PRICING.test(heading.textContent ?? "");
281
+ });
282
+ for (const section of pricingSections) {
283
+ for (const el of Array.from(section.querySelectorAll(CLICKABLE_SELECTOR))) {
284
+ const index = all.indexOf(el);
285
+ const c = index >= 0 ? measured[index] : undefined;
286
+ if (c && c.label && (c.filled || c.action))
287
+ addTarget(c, "pricing");
288
+ }
289
+ }
290
+ const price = body ? PRICE.exec(body.innerText)?.[0] : undefined;
291
+ return {
292
+ viewport: { width: vw, height: vh },
293
+ scrollY,
294
+ ...(h1 ? { h1 } : {}),
295
+ ...(primary ? { primary } : {}),
296
+ filled: filled.slice(0, 8),
297
+ salient: [...first].sort(bySalience).slice(0, 5),
298
+ pageHeight: Math.max(root.scrollHeight, body?.scrollHeight ?? 0),
299
+ floor,
300
+ targets,
301
+ ...(price ? { price: price.replace(/[.,]$/, "") } : {}),
302
+ };
303
+ }
304
+ // Overlays covering more than 30% of the viewport: fixed elements, and dialogs or modal-like absolute
305
+ // elements. Decorative layers (pointer-events: none, negative z-index) and a fixed layer that holds the h1
306
+ // (a page that scrolls inside a fixed container) do not count. A layer counts only when it is on top: it (or
307
+ // an element inside it) is the topmost hit at half or more of a 3x3 grid of points inside its own visible
308
+ // rect (clipped to the viewport), and the visible h1 does not paint above it (a full-screen background under
309
+ // the content).
310
+ export function overlayProbe() {
311
+ const GRID = 3;
312
+ const MAX_SHARE = 0.3;
313
+ const MODALISH = /modal|popup|pop-up|overlay|dialog|cookie|consent|newsletter|subscribe|interstitial|lightbox/i;
314
+ const vw = window.innerWidth;
315
+ const vh = window.innerHeight;
316
+ const h1 = document.querySelector("h1");
317
+ const topAt = (x, y) => document.elementsFromPoint(x, y)[0];
318
+ const h1Box = h1 && h1.checkVisibility({ opacityProperty: true, visibilityProperty: true }) ? h1.getBoundingClientRect() : undefined;
319
+ const h1Point = h1Box && h1Box.width > 1 && h1Box.height > 1
320
+ ? { x: (h1Box.left + h1Box.right) / 2, y: (h1Box.top + h1Box.bottom) / 2 }
321
+ : undefined;
322
+ const onTop = (el, r) => {
323
+ const left = Math.max(r.left, 0);
324
+ const right = Math.min(r.right, vw);
325
+ const upper = Math.max(r.top, 0);
326
+ const lower = Math.min(r.bottom, vh);
327
+ let top = 0;
328
+ for (let i = 0; i < GRID; i++) {
329
+ for (let j = 0; j < GRID; j++) {
330
+ const hit = topAt(left + ((right - left) * (i + 0.5)) / GRID, upper + ((lower - upper) * (j + 0.5)) / GRID);
331
+ if (hit !== undefined && el.contains(hit))
332
+ top++;
333
+ }
334
+ }
335
+ if (top * 2 < GRID * GRID)
336
+ return false;
337
+ if (h1Point && h1Point.x >= Math.max(r.left, 0) && h1Point.x < Math.min(r.right, vw) && h1Point.y >= Math.max(r.top, 0) && h1Point.y < Math.min(r.bottom, vh)) {
338
+ const hit = topAt(h1Point.x, h1Point.y);
339
+ if (hit && !el.contains(hit))
340
+ return false;
341
+ }
342
+ return true;
343
+ };
344
+ const hits = [];
345
+ const describe = (el) => {
346
+ const id = el.id ? `#${CSS.escape(el.id)}` : "";
347
+ const classes = Array.from(el.classList)
348
+ .filter((c) => c.length <= 30)
349
+ .slice(0, 2)
350
+ .map((c) => `.${CSS.escape(c)}`)
351
+ .join("");
352
+ return `${el.tagName.toLowerCase()}${id}${classes}`;
353
+ };
354
+ for (const el of Array.from(document.body?.querySelectorAll("*") ?? [])) {
355
+ if (hits.some((h) => h.el.contains(el)))
356
+ continue;
357
+ const style = getComputedStyle(el);
358
+ const semantic = el.matches("dialog[open], [role='dialog'], [role='alertdialog'], [aria-modal='true']");
359
+ const named = MODALISH.test(`${el.id} ${typeof el.className === "string" ? el.className : ""}`);
360
+ const fixed = style.position === "fixed";
361
+ if (!fixed && !semantic && !(style.position === "absolute" && named))
362
+ continue;
363
+ if (style.pointerEvents === "none" || parseInt(style.zIndex, 10) < 0)
364
+ continue;
365
+ if (!el.checkVisibility({ opacityProperty: true, visibilityProperty: true }))
366
+ continue;
367
+ if (h1 && el.contains(h1))
368
+ continue;
369
+ const r = el.getBoundingClientRect();
370
+ const w = Math.max(0, Math.min(r.right, vw) - Math.max(r.left, 0));
371
+ const h = Math.max(0, Math.min(r.bottom, vh) - Math.max(r.top, 0));
372
+ const share = (w * h) / (vw * vh);
373
+ if (share <= MAX_SHARE)
374
+ continue;
375
+ if (!onTop(el, r))
376
+ continue;
377
+ const text = el.innerText?.replace(/\s+/g, " ").trim().slice(0, 50) ?? "";
378
+ const kind = semantic ? "dialog" : fixed ? "fixed layer" : "modal";
379
+ hits.push({ el, hit: { selector: describe(el), share: Math.round(share * 100) / 100, detail: text ? `${kind}: "${text}"` : kind } });
380
+ }
381
+ return hits.map((h) => h.hit);
382
+ }
383
+ // Milliseconds since the load event ended (0 before it).
384
+ export function sinceLoad() {
385
+ const nav = performance.getEntriesByType("navigation")[0];
386
+ const loaded = nav?.loadEventEnd || nav?.domContentLoadedEventEnd || 0;
387
+ return loaded > 0 ? performance.now() - loaded : 0;
388
+ }
389
+ // The last largest-contentful-paint entry so far (buffered). Read it before scrolling: scrolling paints
390
+ // below-the-fold content that is not part of the first screen.
391
+ export async function lcpProbe() {
392
+ const entries = await new Promise((resolve) => {
393
+ const found = [];
394
+ try {
395
+ const observer = new PerformanceObserver((list) => found.push(...list.getEntries()));
396
+ observer.observe({ type: "largest-contentful-paint", buffered: true });
397
+ setTimeout(() => {
398
+ observer.disconnect();
399
+ resolve(found);
400
+ }, 100);
401
+ }
402
+ catch {
403
+ resolve(found);
404
+ }
405
+ });
406
+ const last = entries[entries.length - 1];
407
+ if (!last)
408
+ return undefined;
409
+ const el = last.element;
410
+ const describe = (node) => {
411
+ const id = node.id ? `#${CSS.escape(node.id)}` : "";
412
+ const classes = Array.from(node.classList)
413
+ .filter((c) => c.length <= 30)
414
+ .slice(0, 2)
415
+ .map((c) => `.${CSS.escape(c)}`)
416
+ .join("");
417
+ return `${node.tagName.toLowerCase()}${id}${classes}`;
418
+ };
419
+ const r = el?.getBoundingClientRect();
420
+ return {
421
+ ms: Math.round(last.renderTime || last.loadTime || last.startTime),
422
+ ...(el ? { selector: describe(el), tag: el.tagName.toLowerCase() } : {}),
423
+ ...(last.url ? { url: last.url } : {}),
424
+ ...(r ? { box: { top: r.top + window.scrollY, bottom: r.bottom + window.scrollY, left: r.left, right: r.right, width: r.width, height: r.height } } : {}),
425
+ viewportHeight: window.innerHeight,
426
+ };
427
+ }
428
+ // An init script for the click test page (page.addInitScript), so it runs before any page script. Blocks every
429
+ // way a form can be submitted: form.submit() and form.requestSubmit() only record, and a window capture-phase
430
+ // submit listener stops the event before any page handler sees it (a JS handler would post the form data
431
+ // itself). navigator.sendBeacon only records too. The click test also answers every request that is not GET or
432
+ // HEAD itself, so fetch and XMLHttpRequest posts never leave the browser. armClick sets window.__sugikitEffect.
433
+ // Beacons sent before the click (analytics timers) are noise: a beacon after the click counts only when its
434
+ // target was not seen before the click.
435
+ export function guardSubmits() {
436
+ const w = window;
437
+ if (w.__sugikitGuard)
438
+ return;
439
+ w.__sugikitGuard = true;
440
+ const note = (name) => w.__sugikitEffect?.(name);
441
+ const beaconNoise = new Set();
442
+ const blocked = "form submit (blocked, nothing sent)";
443
+ HTMLFormElement.prototype.submit = function () {
444
+ note(blocked);
445
+ };
446
+ HTMLFormElement.prototype.requestSubmit = function () {
447
+ note(blocked);
448
+ };
449
+ window.addEventListener("submit", (event) => {
450
+ event.stopImmediatePropagation();
451
+ event.preventDefault();
452
+ note(blocked);
453
+ }, true);
454
+ if (typeof navigator.sendBeacon === "function") {
455
+ navigator.sendBeacon = (target) => {
456
+ let where = String(target);
457
+ try {
458
+ const parsed = new URL(where, location.href);
459
+ where = parsed.origin === location.origin ? parsed.pathname : `${parsed.origin}${parsed.pathname}`;
460
+ }
461
+ catch {
462
+ // keep the raw target
463
+ }
464
+ if (!w.__sugikitClicked)
465
+ beaconNoise.add(where);
466
+ else if (!beaconNoise.has(where))
467
+ note(`would send beacon ${where} (blocked, nothing sent)`);
468
+ return true;
469
+ };
470
+ }
471
+ }
472
+ // Arms a click test on the clickable at `index` (checked against its label); fireClick then clicks it. Records
473
+ // what the click does in window.__sugikitClick: navigation, a new page, a dialog, a clipboard write, a form
474
+ // submit (always blocked by guardSubmits: no form is ever sent), a visible DOM change outside the button, and
475
+ // uncaught errors. Elements that change by themselves (carousels, tickers) and beacons sent during a baseline
476
+ // do not count; nothing counts as an effect until fireClick runs. Without guardSubmits installed it does not
477
+ // arm.
478
+ export const CLICK_BASELINE_MS = 1_000;
479
+ export async function armClick(arg) {
480
+ const SELECTOR = 'a[href], button, [role="button"], input[type="submit" i], input[type="button" i]';
481
+ const squash = (text) => text.replace(/\s+/g, " ").trim();
482
+ const labelOf = (el) => {
483
+ const aria = el.getAttribute("aria-label");
484
+ const text = el instanceof HTMLInputElement ? el.value : el.innerText;
485
+ return squash(aria || text || el.getAttribute("title") || "").slice(0, 60);
486
+ };
487
+ const guarded = window;
488
+ if (!guarded.__sugikitGuard)
489
+ return { armed: false, reason: "form submits could not be blocked" };
490
+ const all = Array.from(document.querySelectorAll(SELECTOR));
491
+ const target = all[arg.index] && labelOf(all[arg.index]) === arg.label ? all[arg.index] : all.find((el) => labelOf(el) === arg.label);
492
+ if (!(target instanceof HTMLElement))
493
+ return { armed: false, reason: "could not find the element again after a reload" };
494
+ const state = { effects: [], errors: [], start: location.href, clicked: false };
495
+ window.__sugikitClick = state;
496
+ const effect = (name) => {
497
+ if (state.clicked && !state.effects.includes(name))
498
+ state.effects.push(name);
499
+ };
500
+ window.addEventListener("error", (event) => {
501
+ if (state.clicked)
502
+ state.errors.push(squash(event.message || "error").slice(0, 120));
503
+ });
504
+ window.addEventListener("unhandledrejection", (event) => {
505
+ if (state.clicked)
506
+ state.errors.push(squash(String(event.reason)).slice(0, 120));
507
+ });
508
+ window.addEventListener("pagehide", () => effect("navigation"));
509
+ window.addEventListener("beforeunload", () => effect("navigation"));
510
+ window.addEventListener("hashchange", () => {
511
+ const id = location.hash.slice(1);
512
+ if (id && document.getElementById(id))
513
+ effect("scroll to a section");
514
+ });
515
+ const history = window.history;
516
+ for (const name of ["pushState", "replaceState"]) {
517
+ const original = history[name].bind(history);
518
+ history[name] = (data, unused, url) => {
519
+ if (url !== undefined && url !== null && new URL(String(url), location.href).href !== location.href)
520
+ effect("navigation");
521
+ original(data, unused, url);
522
+ };
523
+ }
524
+ window.open = () => {
525
+ effect("new page");
526
+ return null;
527
+ };
528
+ window.alert = () => effect("dialog");
529
+ window.confirm = () => {
530
+ effect("dialog");
531
+ return false;
532
+ };
533
+ window.prompt = () => {
534
+ effect("dialog");
535
+ return null;
536
+ };
537
+ const dialog = HTMLDialogElement.prototype;
538
+ const showModal = dialog.showModal;
539
+ const show = dialog.show;
540
+ dialog.showModal = function () {
541
+ effect("dialog");
542
+ showModal.call(this);
543
+ };
544
+ dialog.show = function () {
545
+ effect("dialog");
546
+ show.call(this);
547
+ };
548
+ if (navigator.clipboard) {
549
+ navigator.clipboard.writeText = async () => effect("clipboard write");
550
+ navigator.clipboard.write = async () => effect("clipboard write");
551
+ }
552
+ const execCommand = document.execCommand.bind(document);
553
+ document.execCommand = (command, ui, value) => {
554
+ if (command.toLowerCase() === "copy" || command.toLowerCase() === "cut") {
555
+ effect("clipboard write");
556
+ return true;
557
+ }
558
+ return execCommand(command, ui, value);
559
+ };
560
+ guarded.__sugikitEffect = effect;
561
+ // Baseline: elements that change without a click.
562
+ const noisy = new Set();
563
+ const baseline = new MutationObserver((records) => records.forEach((r) => noisy.add(r.target)));
564
+ baseline.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });
565
+ await new Promise((resolve) => setTimeout(resolve, arg.baselineMs));
566
+ baseline.disconnect();
567
+ const shown = (node) => {
568
+ const el = node instanceof Element ? node : node.parentElement;
569
+ if (!el || ["SCRIPT", "STYLE", "LINK", "META"].includes(el.tagName))
570
+ return false;
571
+ const r = el.getBoundingClientRect();
572
+ return r.width > 1 && r.height > 1 && el.checkVisibility({ opacityProperty: true, visibilityProperty: true });
573
+ };
574
+ const changed = new Set();
575
+ const watcher = new MutationObserver((records) => {
576
+ for (const r of records) {
577
+ if (noisy.has(r.target))
578
+ continue;
579
+ const inside = target.contains(r.target);
580
+ if (r.type === "characterData") {
581
+ if (inside)
582
+ effect("button label changed");
583
+ else
584
+ changed.add(r.target);
585
+ }
586
+ else if (r.type === "childList") {
587
+ const added = Array.from(r.addedNodes).filter((n) => n.nodeType === Node.ELEMENT_NODE || squash(n.textContent ?? "") !== "");
588
+ if (inside) {
589
+ if (added.some((n) => squash(n.textContent ?? "") !== ""))
590
+ effect("button label changed");
591
+ }
592
+ else {
593
+ added.forEach((n) => changed.add(n));
594
+ if (Array.from(r.removedNodes).some((n) => squash(n.textContent ?? "") !== ""))
595
+ effect("visible DOM change");
596
+ }
597
+ }
598
+ else if (r.type === "attributes") {
599
+ if (inside && r.attributeName !== "aria-expanded" && r.attributeName !== "aria-pressed")
600
+ continue;
601
+ if (r.target === target && (r.attributeName === "aria-expanded" || r.attributeName === "aria-pressed"))
602
+ effect("toggle state change");
603
+ else
604
+ changed.add(r.target);
605
+ }
606
+ }
607
+ if ([...changed].some(shown))
608
+ effect("visible DOM change");
609
+ });
610
+ watcher.observe(document.documentElement, {
611
+ subtree: true,
612
+ childList: true,
613
+ characterData: true,
614
+ attributes: true,
615
+ attributeFilter: ["class", "style", "hidden", "open", "aria-hidden", "aria-expanded", "aria-pressed"],
616
+ });
617
+ guarded.__sugikitFire = () => {
618
+ state.clicked = true;
619
+ window.__sugikitClicked = true;
620
+ const submit = (target instanceof HTMLButtonElement || target instanceof HTMLInputElement) && target.type === "submit" && target.form !== null;
621
+ if (submit) {
622
+ // A form's submit button: it works when the form has a target. Never click it, so nothing is sent.
623
+ effect("submits its form (not sent)");
624
+ return false;
625
+ }
626
+ target.click();
627
+ return true;
628
+ };
629
+ return { armed: true };
630
+ }
631
+ // Clicks the target armClick armed. From here on effects, errors and beacons count.
632
+ export function fireClick() {
633
+ const fire = window.__sugikitFire;
634
+ return fire ? fire() : false;
635
+ }
636
+ // Waits up to `ms` for an effect of the armed click. Missing state means the page navigated.
637
+ export async function clickOutcome(ms) {
638
+ const state = window.__sugikitClick;
639
+ if (!state)
640
+ return { effects: ["navigation"], errors: [], navigated: true };
641
+ const deadline = Date.now() + ms;
642
+ while (state.effects.length === 0 && Date.now() < deadline)
643
+ await new Promise((resolve) => setTimeout(resolve, 50));
644
+ await new Promise((resolve) => setTimeout(resolve, 100));
645
+ const navigated = location.href.split("#")[0] !== state.start.split("#")[0];
646
+ return { effects: navigated ? [...state.effects, "navigation"] : state.effects, errors: state.errors, navigated };
647
+ }
@@ -0,0 +1,6 @@
1
+ import { Agent } from "undici";
2
+ import { type FetchLike, type FetchResult } from "./http.js";
3
+ export { BROWSER_USER_AGENT, REQUEST_HEADERS, isBlockedResponse, isChallengePage, isLocalHost, isLoopbackUrl, type FetchResult, } from "./http.js";
4
+ export declare function localDispatcher(): Agent;
5
+ export declare const cliFetch: FetchLike;
6
+ export declare function fetchText(url: string): Promise<FetchResult>;
package/dist/fetch.js ADDED
@@ -0,0 +1,22 @@
1
+ import { Agent, buildConnector, fetch as undiciFetch } from "undici";
2
+ import { fetchPageWith, isLocalHost, isLocalHostname } from "./http.js";
3
+ export { BROWSER_USER_AGENT, REQUEST_HEADERS, isBlockedResponse, isChallengePage, isLocalHost, isLoopbackUrl, } from "./http.js";
4
+ let localAgent;
5
+ // Dev proxies (portless and similar) serve local hosts with a private CA. TLS checks stay on for every other
6
+ // host, also when a local URL redirects to a public one.
7
+ export function localDispatcher() {
8
+ if (!localAgent) {
9
+ const strict = buildConnector({});
10
+ const lax = buildConnector({ rejectUnauthorized: false });
11
+ localAgent = new Agent({
12
+ connect: (options, callback) => (isLocalHostname(options.hostname) ? lax : strict)(options, callback),
13
+ });
14
+ }
15
+ return localAgent;
16
+ }
17
+ // The CLI fetch: undici with the lax local dispatcher for local hosts, the global fetch for everything else.
18
+ export const cliFetch = (url, init) => isLocalHost(url) ? undiciFetch(url, { ...init, dispatcher: localDispatcher() }) : fetch(url, init);
19
+ // The page fetch, with one retry on a timeout or network error.
20
+ export async function fetchText(url) {
21
+ return fetchPageWith(cliFetch, url);
22
+ }
@@ -0,0 +1,2 @@
1
+ import type { Framework } from "./report.js";
2
+ export declare function detectFramework(projectDir: string): Promise<Framework>;