sugikit 0.0.0-stage → 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 -0
  2. package/README.md +44 -2
  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 +63 -3
  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,357 @@
1
+ // Polish checks on a Playwright-like page. Shared by the CLI (Node Playwright) and the web check
2
+ // (@cloudflare/playwright). No node:* imports and no playwright import: the caller owns the browser.
3
+ import { CLICK_BASELINE_MS, armClick, clickOutcome, fireClick, guardSubmits, heroProbe, lcpProbe, overlayProbe, sinceLoad } from "./convert-probe.js";
4
+ import { INCONCLUSIVE_STATUS, REQUEST_HEADERS, defaultFetch, isLoopbackUrl } from "./http.js";
5
+ import { probePage, runAxe, runningMotion, scrollThrough, scrollToTop } from "./probe.js";
6
+ import { HERO_STATES, convertRenderRules, } from "./rules/convert-render.js";
7
+ import { REDUCED_MOTION_STATE, REQUIRED_STATES, STATE_NAMES, polishRules, } from "./rules/polish.js";
8
+ import { result } from "./rules/types.js";
9
+ const DESKTOP = { viewport: { width: 1440, height: 900 } };
10
+ const PHONE = { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, deviceScaleFactor: 2 };
11
+ export const POLISH_STATES = {
12
+ "desktop-light": { name: "desktop-light", ...DESKTOP, colorScheme: "light" },
13
+ "desktop-dark": { name: "desktop-dark", ...DESKTOP, colorScheme: "dark" },
14
+ "phone-light": { name: "phone-light", ...PHONE, colorScheme: "light" },
15
+ "phone-dark": { name: "phone-dark", ...PHONE, colorScheme: "dark" },
16
+ };
17
+ export const REDUCED_MOTION = { ...POLISH_STATES["phone-light"], name: REDUCED_MOTION_STATE, reducedMotion: "reduce" };
18
+ // Browser context options for a state, for browser.newContext() in a PolishSource factory.
19
+ export function stateContextOptions(state) {
20
+ return {
21
+ viewport: state.viewport,
22
+ colorScheme: state.colorScheme,
23
+ ...(state.isMobile !== undefined ? { isMobile: state.isMobile } : {}),
24
+ ...(state.hasTouch !== undefined ? { hasTouch: state.hasTouch } : {}),
25
+ ...(state.deviceScaleFactor !== undefined ? { deviceScaleFactor: state.deviceScaleFactor } : {}),
26
+ ...(state.reducedMotion ? { reducedMotion: state.reducedMotion } : {}),
27
+ };
28
+ }
29
+ // Run order: the two required states first, so a slow page still gets the checks most rules need.
30
+ const RUN_ORDER = ["desktop-light", "phone-light", "desktop-dark", "phone-dark"];
31
+ export function slowPageResult(budget, skipped) {
32
+ return result("polish/slow-page", "info", false, `The check hit its ${budget.seconds} s time budget, so some browser checks were skipped`, { evidence: `skipped: ${skipped.join(", ")}` });
33
+ }
34
+ export const NETWORK_IDLE_MS = 15_000;
35
+ export const SETTLE_MS = 500;
36
+ export const NAVIGATION_MS = 30_000;
37
+ const MAX_SHOT_DEVICE_PX = 16_000;
38
+ // convert/arrival-popup samples overlays this long after the load event: the early sample on desktop-light and
39
+ // phone-light, the late one on phone-light only (it costs a wait of up to a few seconds per state).
40
+ export const EARLY_POPUP_MS = 1_000;
41
+ export const LATE_POPUP_MS = 4_000;
42
+ // convert/cta-works: how long a clicked button gets to do something, and how long its fresh page may settle.
43
+ export const CLICK_WAIT_MS = 2_000;
44
+ const CLICK_IDLE_MS = 3_000;
45
+ const CTA_LINK_TIMEOUT_MS = 5_000;
46
+ export async function settle(page) {
47
+ await page.waitForLoadState("networkidle", { timeout: NETWORK_IDLE_MS }).catch(() => undefined);
48
+ await page.waitForTimeout(SETTLE_MS);
49
+ }
50
+ function axeTarget(target) {
51
+ const first = Array.isArray(target) ? target[0] : target;
52
+ if (typeof first === "string")
53
+ return first;
54
+ if (Array.isArray(first) && typeof first[0] === "string")
55
+ return first.join(" >>> ");
56
+ return undefined;
57
+ }
58
+ async function loadAxeSource() {
59
+ const axe = await import("axe-core");
60
+ return axe.default.source;
61
+ }
62
+ // Injects axe-core into the main frame once per document. Frames are not checked (iframes: false).
63
+ async function axe(page, source, options) {
64
+ const loaded = await page.evaluate('typeof window.axe?.run === "function"');
65
+ if (!loaded)
66
+ await page.evaluate(source);
67
+ return page.evaluate(runAxe, { ...options, iframes: false });
68
+ }
69
+ async function contrastHits(page, source) {
70
+ const violations = await axe(page, source, { runOnly: { type: "rule", values: ["color-contrast"] } });
71
+ return violations.flatMap((v) => v.nodes.map((node) => ({
72
+ selector: axeTarget(node.target) ?? "unknown",
73
+ ...(node.contrastRatio ? { detail: `${node.contrastRatio}:1` } : {}),
74
+ })));
75
+ }
76
+ async function axeViolations(page, source) {
77
+ const violations = await axe(page, source, { rules: { "color-contrast": { enabled: false } } });
78
+ return violations.map((v) => {
79
+ const selector = axeTarget(v.nodes[0]?.target);
80
+ return { id: v.id, impact: v.impact ?? "unknown", count: v.nodes.length, ...(selector ? { selector } : {}) };
81
+ });
82
+ }
83
+ async function screenshotTop(page, name) {
84
+ const state = POLISH_STATES[name];
85
+ const scrollY = await page.evaluate(scrollToTop);
86
+ const width = state.viewport.width;
87
+ const maxHeight = Math.floor(MAX_SHOT_DEVICE_PX / (state.deviceScaleFactor ?? 1));
88
+ const height = Math.min(await page.evaluate(() => document.documentElement.scrollHeight), maxHeight);
89
+ const png = await page.screenshot({ fullPage: true, clip: { x: 0, y: 0, width, height } });
90
+ return { state: name, png, scrollY };
91
+ }
92
+ async function withPage(source, url, state, run, prepare) {
93
+ if (typeof source === "function") {
94
+ const opened = await source(state);
95
+ try {
96
+ await prepare?.(opened.page);
97
+ await opened.page.goto(url, { waitUntil: "load", timeout: NAVIGATION_MS });
98
+ return await run(opened.page);
99
+ }
100
+ finally {
101
+ await opened.close();
102
+ }
103
+ }
104
+ await source.setViewportSize(state.viewport);
105
+ await source.emulateMedia({ colorScheme: state.colorScheme, reducedMotion: state.reducedMotion ?? "no-preference" });
106
+ await prepare?.(source);
107
+ await source.goto(url, { waitUntil: "load", timeout: NAVIGATION_MS });
108
+ return run(source);
109
+ }
110
+ async function sampleOverlays(page, state, atMs) {
111
+ const since = await page.evaluate(sinceLoad);
112
+ if (since < atMs)
113
+ await page.waitForTimeout(atMs - since);
114
+ const at = Math.round(await page.evaluate(sinceLoad));
115
+ return { state, at, hits: await page.evaluate(overlayProbe) };
116
+ }
117
+ async function linkStatus(fetcher, url, follow) {
118
+ const request = async (method) => {
119
+ const res = await fetcher(url, {
120
+ method,
121
+ // Off-site targets (checkout, app stores) get one request and no redirects followed.
122
+ redirect: follow ? "follow" : "manual",
123
+ signal: AbortSignal.timeout(CTA_LINK_TIMEOUT_MS),
124
+ headers: { ...REQUEST_HEADERS },
125
+ });
126
+ await res.text().catch(() => "");
127
+ return res.status;
128
+ };
129
+ const code = await request("HEAD");
130
+ return code === 405 ? request("GET") : code;
131
+ }
132
+ // Clicks a button (or a link to "#", "" or javascript:) in a fresh page and reports what happened. Nothing is
133
+ // sent: guardSubmits blocks every form submit before any page script runs, and every request that is not GET
134
+ // or HEAD (fetch, XMLHttpRequest, sendBeacon, form posts) gets a fake empty answer and never leaves the browser.
135
+ // Requests sent before the click (load, idle and the baseline: analytics timers) are noise: a request after the
136
+ // click counts only when its method and path were not seen before the click.
137
+ // A reused page (no factory) is tested only when its route host can unroute; the guard init script is removed
138
+ // too when addInitScript returns a Disposable (recent Playwright).
139
+ async function clickTest(source, url, target) {
140
+ const held = [];
141
+ const noise = new Set();
142
+ let clicked = false;
143
+ let unroute;
144
+ let removeScript;
145
+ const prepare = async (page) => {
146
+ const host = page.context?.() ?? (page.route ? page : undefined);
147
+ if (!page.addInitScript || !host)
148
+ throw new Error("this browser page cannot block form submits");
149
+ if (typeof source !== "function" && !host.unroute)
150
+ throw new Error("a reused page cannot remove the click test's request block");
151
+ const handler = async (route) => {
152
+ const request = route.request();
153
+ const method = request.method().toUpperCase();
154
+ if (method === "GET" || method === "HEAD")
155
+ return route.fallback();
156
+ let where = request.url();
157
+ try {
158
+ const parsed = new URL(where);
159
+ where = parsed.origin === new URL(url).origin ? parsed.pathname : `${parsed.origin}${parsed.pathname}`;
160
+ }
161
+ catch {
162
+ // keep the raw URL
163
+ }
164
+ const line = `${method} ${where}`;
165
+ if (!clicked)
166
+ noise.add(line);
167
+ else if (!noise.has(line) && !held.includes(line))
168
+ held.push(line);
169
+ return route.fulfill({ status: 204, body: "" });
170
+ };
171
+ await host.route("**/*", handler);
172
+ if (host.unroute)
173
+ unroute = async () => void (await host.unroute?.("**/*", handler));
174
+ const script = (await page.addInitScript(guardSubmits));
175
+ if (typeof script?.dispose === "function")
176
+ removeScript = async () => void (await script.dispose?.());
177
+ };
178
+ try {
179
+ return await withPage(source, url, POLISH_STATES["desktop-light"], async (page) => {
180
+ await page.waitForLoadState("networkidle", { timeout: CLICK_IDLE_MS }).catch(() => undefined);
181
+ const armed = await page.evaluate(armClick, { index: target.index, label: target.label, baselineMs: CLICK_BASELINE_MS });
182
+ if (!armed.armed)
183
+ return { target, ok: undefined, detail: `not tested: ${armed.reason ?? "could not arm the click"}` };
184
+ // Everything sent until now (load, idle, baseline) is noise; only what the click sends counts.
185
+ clicked = true;
186
+ let outcome;
187
+ try {
188
+ await page.evaluate(fireClick);
189
+ outcome = await page.evaluate(clickOutcome, CLICK_WAIT_MS);
190
+ }
191
+ catch (error) {
192
+ if (!/context was destroyed|navigat/i.test(firstLine(error)))
193
+ throw error;
194
+ outcome = { effects: ["navigation"], errors: [] };
195
+ }
196
+ if (held.length > 0)
197
+ outcome = { ...outcome, effects: [...outcome.effects, `would send ${held.slice(0, 3).join(", ")} (blocked, nothing sent)`] };
198
+ if (outcome.errors.length > 0)
199
+ return { target, ok: false, detail: `click threw an uncaught error: ${outcome.errors[0]}` };
200
+ if (outcome.effects.length > 0)
201
+ return { target, ok: true, detail: `click: ${outcome.effects.join(", ")}` };
202
+ const dead = target.rawHref !== undefined ? `links to "${target.rawHref || "(empty)"}" and ` : "";
203
+ return { target, ok: false, detail: `${dead}the click did nothing within ${CLICK_WAIT_MS / 1000} s (no navigation, new page, dialog, copy or visible change)` };
204
+ }, prepare);
205
+ }
206
+ catch (error) {
207
+ return { target, ok: undefined, detail: `not tested: ${firstLine(error)}` };
208
+ }
209
+ finally {
210
+ await unroute?.().catch(() => undefined);
211
+ await removeScript?.().catch(() => undefined);
212
+ }
213
+ }
214
+ async function checkCta(source, url, target, fetcher) {
215
+ const raw = (target.rawHref ?? "").trim();
216
+ if (target.tag !== "a" || raw === "" || raw === "#" || /^javascript:/i.test(raw))
217
+ return clickTest(source, url, target);
218
+ if (/^(mailto|tel|sms):/i.test(raw))
219
+ return { target, ok: true, detail: "opens mail or phone" };
220
+ if (raw.startsWith("#")) {
221
+ return target.hashTarget
222
+ ? { target, ok: true, detail: `scrolls to ${raw}` }
223
+ : { target, ok: false, detail: `no element with id "${raw.slice(1)}" on the page` };
224
+ }
225
+ const href = target.href ?? raw;
226
+ let parsed;
227
+ try {
228
+ parsed = new URL(href, url);
229
+ }
230
+ catch {
231
+ return { target, ok: false, detail: "the href is not a valid URL" };
232
+ }
233
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
234
+ return { target, ok: undefined, detail: `not tested: ${parsed.protocol} link` };
235
+ const sameOrigin = parsed.origin === new URL(url).origin;
236
+ try {
237
+ const code = await linkStatus(fetcher, parsed.href, sameOrigin);
238
+ if (code >= 200 && code < 400)
239
+ return { target, ok: true, detail: `HTTP ${code}` };
240
+ if (code === 0 && !sameOrigin)
241
+ return { target, ok: true, detail: "redirects (not followed)" };
242
+ if (INCONCLUSIVE_STATUS.has(code))
243
+ return { target, ok: undefined, detail: `HTTP ${code}; bot protection or a login may block automated checks` };
244
+ return { target, ok: false, detail: `HTTP ${code}` };
245
+ }
246
+ catch (error) {
247
+ // An off-site target (checkout, app store) that times out or refuses the connection may block automated
248
+ // requests or be down for a moment: not proof the CTA is broken.
249
+ if (!sameOrigin)
250
+ return { target, ok: undefined, detail: `not tested: no response: ${firstLine(error)}` };
251
+ return { target, ok: false, detail: `no response: ${firstLine(error)}` };
252
+ }
253
+ }
254
+ function polishFailure(message) {
255
+ return { results: [result("polish/browser", "error", false, message)] };
256
+ }
257
+ export function firstLine(error) {
258
+ return error.message.split("\n")[0] ?? "unknown error";
259
+ }
260
+ // Runs the four states and the reduced motion state, then the polish rules. A load or browser error becomes
261
+ // one polish/browser error result; it never throws.
262
+ export async function runPolishChecks(source, options) {
263
+ const { url } = options;
264
+ const wanted = options.screenshots ?? true;
265
+ const shotStates = new Set(wanted === true ? STATE_NAMES : wanted === false ? [] : wanted);
266
+ const { budget } = options;
267
+ const skipped = [];
268
+ const inTime = () => !budget || Date.now() < budget.deadline;
269
+ try {
270
+ const axeSource = options.axeSource ?? (await loadAxeSource());
271
+ const probes = {};
272
+ const contrast = {};
273
+ const screenshots = [];
274
+ let axeFound = [];
275
+ const hero = {};
276
+ const overlays = [];
277
+ let lcp;
278
+ const heroStates = new Set(HERO_STATES);
279
+ for (const name of RUN_ORDER) {
280
+ if (!REQUIRED_STATES.includes(name) && !inTime()) {
281
+ skipped.push(name);
282
+ continue;
283
+ }
284
+ const state = POLISH_STATES[name];
285
+ await withPage(source, url, state, async (page) => {
286
+ const heroState = heroStates.has(name) ? name : undefined;
287
+ if (heroState)
288
+ overlays.push(await sampleOverlays(page, heroState, EARLY_POPUP_MS));
289
+ await settle(page);
290
+ if (name === "phone-light")
291
+ overlays.push(await sampleOverlays(page, "phone-light", LATE_POPUP_MS));
292
+ if (name === "phone-light")
293
+ lcp = await page.evaluate(lcpProbe);
294
+ await page.evaluate(scrollThrough);
295
+ await page.evaluate(scrollToTop);
296
+ probes[name] = await page.evaluate(probePage);
297
+ if (heroState)
298
+ hero[heroState] = await page.evaluate(heroProbe);
299
+ contrast[name] = await contrastHits(page, axeSource);
300
+ if (name === "desktop-light")
301
+ axeFound = await axeViolations(page, axeSource);
302
+ if (shotStates.has(name))
303
+ screenshots.push(await screenshotTop(page, name));
304
+ });
305
+ }
306
+ const motion = !inTime() ? undefined : await withPage(source, url, REDUCED_MOTION, async (page) => {
307
+ const early = await page.evaluate(runningMotion);
308
+ await settle(page);
309
+ const late = await page.evaluate(runningMotion);
310
+ const seen = new Set();
311
+ return [...early, ...late].filter((hit) => {
312
+ const key = `${hit.selector} ${hit.detail ?? ""}`;
313
+ if (seen.has(key))
314
+ return false;
315
+ seen.add(key);
316
+ return true;
317
+ });
318
+ });
319
+ if (!motion)
320
+ skipped.push("reduced motion run");
321
+ const desktop = probes["desktop-light"];
322
+ const phone = probes["phone-light"];
323
+ if (!desktop || !phone)
324
+ throw new Error("the desktop-light or phone-light state did not run");
325
+ const data = { probes: { ...probes, "desktop-light": desktop, "phone-light": phone }, contrast, axe: axeFound, ...(motion ? { motion } : {}) };
326
+ const fetcher = options.fetch ?? defaultFetch;
327
+ const ctas = [];
328
+ const untried = [];
329
+ for (const target of hero["desktop-light"]?.targets ?? []) {
330
+ if (!inTime()) {
331
+ untried.push(target.label);
332
+ ctas.push({ target, ok: undefined, detail: "not tested: the check ran out of time" });
333
+ continue;
334
+ }
335
+ ctas.push(await checkCta(source, url, target, fetcher));
336
+ }
337
+ if (untried.length > 0)
338
+ skipped.push(`CTA checks (${untried.length})`);
339
+ const convert = { hero, overlays, ctas, local: options.local ?? isLoopbackUrl(url), ...(lcp ? { lcp } : {}) };
340
+ const order = (name) => STATE_NAMES.indexOf(name);
341
+ screenshots.sort((a, b) => order(a.state) - order(b.state));
342
+ return {
343
+ results: [...polishRules(data), ...convertRenderRules(convert), ...(budget && skipped.length > 0 ? [slowPageResult(budget, skipped)] : [])],
344
+ convert,
345
+ states: [...STATE_NAMES.filter((name) => probes[name] !== undefined), ...(motion ? [REDUCED_MOTION_STATE] : [])],
346
+ ...(screenshots.length > 0 ? { screenshots } : {}),
347
+ };
348
+ }
349
+ catch (error) {
350
+ const reason = firstLine(error);
351
+ const cert = /net::ERR_CERT_\w+/.exec(reason)?.[0];
352
+ if (cert) {
353
+ return polishFailure(`Browser checks could not load ${url}: the browser does not trust its TLS certificate (${cert}). For a local dev server, trust the dev CA in the system trust store (for example mkcert -install or your dev proxy's trust command) and check again.`);
354
+ }
355
+ return polishFailure(`Browser checks could not load ${url}: ${reason}`);
356
+ }
357
+ }
@@ -0,0 +1,14 @@
1
+ import type { Hit, Probe } from "./rules/polish.js";
2
+ export declare function scrollToTop(): Promise<number>;
3
+ export declare function scrollThrough(): Promise<void>;
4
+ export declare function probePage(): Probe;
5
+ export declare function runningMotion(): Hit[];
6
+ export interface AxeHit {
7
+ id: string;
8
+ impact: string | null;
9
+ nodes: {
10
+ target: unknown;
11
+ contrastRatio?: number;
12
+ }[];
13
+ }
14
+ export declare function runAxe(options: unknown): Promise<AxeHit[]>;