@a.incantalupo/web-tools 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 (50) hide show
  1. package/README.md +45 -2
  2. package/dist/audit/cli.d.ts +1 -0
  3. package/dist/audit/cli.js +238 -0
  4. package/dist/audit/crux.d.ts +6 -0
  5. package/dist/audit/crux.js +29 -0
  6. package/dist/audit/fetch.d.ts +17 -0
  7. package/dist/audit/fetch.js +51 -0
  8. package/dist/audit/findings.d.ts +9 -0
  9. package/dist/audit/findings.js +514 -0
  10. package/dist/audit/index.d.ts +6 -0
  11. package/dist/audit/index.js +3 -0
  12. package/dist/audit/lighthouse.d.ts +2 -0
  13. package/dist/audit/lighthouse.js +84 -0
  14. package/dist/audit/page.d.ts +10 -0
  15. package/dist/audit/page.js +156 -0
  16. package/dist/audit/profile.d.ts +11 -0
  17. package/dist/audit/profile.js +21 -0
  18. package/dist/audit/render.d.ts +8 -0
  19. package/dist/audit/render.js +63 -0
  20. package/dist/audit/rerender.d.ts +1 -0
  21. package/dist/audit/rerender.js +55 -0
  22. package/dist/audit/reviews.d.ts +2 -0
  23. package/dist/audit/reviews.js +36 -0
  24. package/dist/audit/scores.d.ts +3 -0
  25. package/dist/audit/scores.js +51 -0
  26. package/dist/audit/site.d.ts +19 -0
  27. package/dist/audit/site.js +78 -0
  28. package/dist/audit/summary.d.ts +2 -0
  29. package/dist/audit/summary.js +59 -0
  30. package/dist/audit/types.d.ts +132 -0
  31. package/dist/audit/types.js +1 -0
  32. package/dist/browser/cli.d.ts +1 -0
  33. package/dist/browser/cli.js +11 -0
  34. package/dist/browser/index.d.ts +15 -0
  35. package/dist/browser/index.js +63 -0
  36. package/dist/cli.d.ts +2 -0
  37. package/dist/cli.js +34 -0
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +4 -0
  40. package/dist/refs/cli.d.ts +1 -0
  41. package/dist/refs/cli.js +193 -0
  42. package/dist/refs/glyphs.d.ts +1 -0
  43. package/dist/refs/glyphs.js +101 -0
  44. package/dist/refs/images.d.ts +1 -0
  45. package/dist/refs/images.js +163 -0
  46. package/dist/refs/snapshot.d.ts +1 -0
  47. package/dist/refs/snapshot.js +243 -0
  48. package/dist/refs/text.d.ts +1 -0
  49. package/dist/refs/text.js +487 -0
  50. package/package.json +34 -5
@@ -0,0 +1,163 @@
1
+ // Which image file each slot on a page downloads, on a 3x phone, a 2x laptop and a 1x
2
+ // monitor, and what that weighs. The Lighthouse score doesn't show this: it measures one
3
+ // mid-range phone, and a page can score well while a retina laptop downloads four times
4
+ // the photos.
5
+ //
6
+ // Usage: stack-tools images <url...> [--budget 600]
7
+ //
8
+ // Fails (exit 1) on what is always wrong: an image that didn't load, or a lazy-loaded
9
+ // largest image (LCP). Warns on what is usually wrong: a file much larger than its slot,
10
+ // a photo stretched past its pixels, images over the budget (KB) before any scroll.
11
+ import { chromium } from "playwright-core";
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { parseArgs } from "node:util";
15
+ const { values, positionals: urls } = parseArgs({
16
+ allowPositionals: true,
17
+ options: { budget: { type: "string", default: "600" } },
18
+ });
19
+ if (!urls.length) {
20
+ console.error("Usage: stack-tools images <url...> [--budget 600]");
21
+ process.exit(1);
22
+ }
23
+ const budget = Number(values.budget);
24
+ const screens = {
25
+ "phone 390 @3x": {
26
+ viewport: { width: 390, height: 844 },
27
+ deviceScaleFactor: 3,
28
+ isMobile: true,
29
+ hasTouch: true,
30
+ },
31
+ "laptop 1440 @2x": {
32
+ viewport: { width: 1440, height: 900 },
33
+ deviceScaleFactor: 2,
34
+ },
35
+ "monitor 1920 @1x": {
36
+ viewport: { width: 1920, height: 1080 },
37
+ deviceScaleFactor: 1,
38
+ },
39
+ };
40
+ const browser = await chromium.launch({
41
+ executablePath: process.env.CHROME_PATH ??
42
+ join(homedir(), ".cache/ms-playwright/chromium-1194/chrome-linux/chrome"),
43
+ });
44
+ let failures = 0;
45
+ let warnings = 0;
46
+ const kb = (bytes) => `${Math.round(bytes / 1024)} KB`;
47
+ for (const url of urls) {
48
+ console.log(`\n${url}`);
49
+ for (const [name, options] of Object.entries(screens)) {
50
+ const context = await browser.newContext(options);
51
+ const page = await context.newPage();
52
+ // A check is not a visit: keep it out of the site's own analytics.
53
+ await page.route("**/api/t", (route) => route.abort());
54
+ const bytes = new Map();
55
+ const failed = new Set();
56
+ page.on("response", (response) => {
57
+ if (response.request().resourceType() !== "image")
58
+ return;
59
+ if (response.ok())
60
+ bytes.set(response.url(), Number(response.headers()["content-length"] ?? 0));
61
+ else
62
+ failed.add(response.url());
63
+ });
64
+ await page.goto(url, { waitUntil: "networkidle" });
65
+ const first = [...bytes.values()].reduce((a, b) => a + b, 0);
66
+ const lcp = await page.evaluate(() => new Promise((done) => {
67
+ new PerformanceObserver((list) => {
68
+ const entry = list.getEntries().at(-1);
69
+ const el = entry?.element;
70
+ done(el
71
+ ? {
72
+ lazy: el instanceof HTMLImageElement && el.loading === "lazy",
73
+ what: el instanceof HTMLImageElement
74
+ ? `image ${(entry?.url ?? "").split("/").pop()}`
75
+ : `text <${el.tagName.toLowerCase()}>`,
76
+ }
77
+ : null);
78
+ }).observe({ type: "largest-contentful-paint", buffered: true });
79
+ setTimeout(() => done(null), 1500);
80
+ }));
81
+ // Scroll through, so lazy images below the fold load too.
82
+ await page.evaluate(async () => {
83
+ for (let y = 0; y < document.body.scrollHeight; y += 500) {
84
+ scrollTo(0, y);
85
+ await new Promise((r) => setTimeout(r, 120));
86
+ }
87
+ await new Promise((r) => setTimeout(r, 800));
88
+ });
89
+ const slots = await page.evaluate(() => [...document.images]
90
+ .filter((img) => img.currentSrc && !img.currentSrc.startsWith("data:"))
91
+ .map((img) => {
92
+ // The chosen file's width: from its srcset entry (the <img>'s or a <source>'s in
93
+ // the same <picture>), else from a `-<width>.` in its name, else what the browser
94
+ // reports.
95
+ const sets = [
96
+ img.srcset,
97
+ ...[...(img.parentElement?.querySelectorAll("source") ?? [])].map((s) => s.srcset),
98
+ ];
99
+ const entry = sets
100
+ .flatMap((set) => set.split(",").map((s) => s.trim().split(/\s+/)))
101
+ .find(([u]) => u && new URL(u, location.href).href === img.currentSrc);
102
+ const named = img.currentSrc.match(/-m?(\d{3,4})\.\w+$/)?.[1];
103
+ return {
104
+ url: img.currentSrc,
105
+ css: Math.round(img.getBoundingClientRect().width),
106
+ file: entry?.[1]?.endsWith("w")
107
+ ? parseInt(entry[1])
108
+ : named
109
+ ? Number(named)
110
+ : img.naturalWidth,
111
+ eager: img.loading !== "lazy",
112
+ broken: img.complete && img.naturalWidth === 0,
113
+ };
114
+ }));
115
+ const total = [...bytes.values()].reduce((a, b) => a + b, 0);
116
+ const dpr = options.deviceScaleFactor;
117
+ const notes = [];
118
+ const broken = slots.filter((s) => s.broken || failed.has(s.url));
119
+ if (broken.length) {
120
+ failures++;
121
+ notes.push(`FAIL ${broken.length} image(s) didn't load, e.g. ${broken[0].url.split("/").slice(-2).join("/")}`);
122
+ }
123
+ if (lcp?.lazy) {
124
+ failures++;
125
+ notes.push(`FAIL the largest image is lazy-loaded (${lcp.what})`);
126
+ }
127
+ // Much more file than the slot can show, and heavy enough to matter.
128
+ const big = slots.filter((s) => s.css > 0 &&
129
+ s.file / (s.css * dpr) > 2 &&
130
+ (bytes.get(s.url) ?? 0) > 40_000);
131
+ if (big.length) {
132
+ warnings++;
133
+ notes.push(`warn ${big.length} file(s) over twice their slot, e.g. ${big[0].file} px for ${big[0].css} px shown (${kb(bytes.get(big[0].url) ?? 0)})`);
134
+ }
135
+ // Stretched: under 1.5 file pixels per CSS pixel on a dense screen (the eye stops
136
+ // gaining around 2x, so a 3x phone isn't held to 3x), under 0.9 on a 1x one.
137
+ const soft = slots.filter((s) => s.css >= 200 &&
138
+ s.file > 0 &&
139
+ s.file / s.css < (dpr >= 2 ? 1.5 : 0.9));
140
+ if (soft.length) {
141
+ warnings++;
142
+ notes.push(`warn ${soft.length} photo(s) stretched, e.g. ${soft[0].file} px for ${soft[0].css} px at ${dpr}x`);
143
+ }
144
+ if (first / 1024 > budget) {
145
+ warnings++;
146
+ notes.push(`warn images before any scroll over ${budget} KB`);
147
+ }
148
+ const picks = new Map();
149
+ for (const s of slots.filter((s) => s.css >= 60 && bytes.has(s.url))) {
150
+ const key = `${s.css}→${s.file}`;
151
+ picks.set(key, (picks.get(key) ?? 0) + 1);
152
+ }
153
+ console.log(` ${name.padEnd(17)} first screen ${kb(first).padStart(7)}, whole page ${kb(total).padStart(7)}, largest: ${lcp?.what ?? "?"}`);
154
+ console.log(` ${"".padEnd(17)} shown→file px: ${[...picks].map(([k, n]) => `${n}× ${k}`).join(", ") || "none"}`);
155
+ for (const note of notes)
156
+ console.log(` ${"".padEnd(17)} ${note}`);
157
+ await context.close();
158
+ }
159
+ }
160
+ await browser.close();
161
+ console.log(`\n${failures} failure(s), ${warnings} warning(s) on ${urls.length} page(s).`);
162
+ if (failures)
163
+ process.exitCode = 1;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,243 @@
1
+ // "Did the look change?" for a refactor that must not change it (tokens, themes, a
2
+ // component rewrite). `snap` records every element's computed styles and box, plus a
3
+ // full-page screenshot, for each page in each theme on desktop and mobile; `diff`
4
+ // compares two such folders.
5
+ //
6
+ // Usage:
7
+ // stack-tools snap <out dir> <url...> [--themes adventure,showroom]
8
+ // stack-tools diff <before dir> <after dir> [--verbose]
9
+ //
10
+ // Take the "before" on the old code and the "after" on the new, against the same server
11
+ // and data. Two runs of the same code give identical files, so any difference is the
12
+ // change. `?tema=<theme>` is added to each URL (the site's theme preview).
13
+ import { chromium } from "playwright-core";
14
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
15
+ import { homedir } from "node:os";
16
+ import { join, resolve } from "node:path";
17
+ import { parseArgs } from "node:util";
18
+ const { values, positionals } = parseArgs({
19
+ allowPositionals: true,
20
+ options: {
21
+ themes: { type: "string", default: "adventure,showroom" },
22
+ verbose: { type: "boolean", default: false },
23
+ },
24
+ });
25
+ const [command, ...rest] = positionals;
26
+ // Paths are relative to where you ran pnpm, not this package.
27
+ const at = (dir) => resolve(process.env.INIT_CWD ?? process.cwd(), dir);
28
+ // Computed values that differ without changing a pixel at rest. They are counted, not
29
+ // listed: the screenshots are the proof.
30
+ const INERT = new Set(["transition-property", "transition-duration"]);
31
+ if (command === "snap" && rest.length >= 2)
32
+ await snap(at(rest[0]), rest.slice(1));
33
+ else if (command === "diff" && rest.length === 2)
34
+ await diff(at(rest[0]), at(rest[1]));
35
+ else {
36
+ console.error("Usage: stack-tools snap <out dir> <url...> [--themes a,b]\n stack-tools diff <before dir> <after dir> [--verbose]");
37
+ process.exit(1);
38
+ }
39
+ async function snap(out, urls) {
40
+ const devices = {
41
+ desktop: { viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 },
42
+ mobile: {
43
+ viewport: { width: 390, height: 844 },
44
+ deviceScaleFactor: 2,
45
+ isMobile: true,
46
+ hasTouch: true,
47
+ },
48
+ };
49
+ const browser = await chromium.launch({
50
+ executablePath: process.env.CHROME_PATH ??
51
+ join(homedir(), ".cache/ms-playwright/chromium-1194/chrome-linux/chrome"),
52
+ });
53
+ await mkdir(out, { recursive: true });
54
+ let count = 0;
55
+ for (const [device, options] of Object.entries(devices)) {
56
+ const context = await browser.newContext({
57
+ ...options,
58
+ reducedMotion: "reduce",
59
+ });
60
+ const page = await context.newPage();
61
+ // A snapshot is not a visit: keep it out of the site's own analytics.
62
+ await page.route("**/api/t", (route) => route.abort());
63
+ for (const theme of values.themes.split(",")) {
64
+ for (const address of urls) {
65
+ const url = new URL(address);
66
+ const name = (url.pathname + url.search)
67
+ .replace(/[^a-z0-9]+/gi, "-")
68
+ .replace(/^-|-$/g, "") || "home";
69
+ url.searchParams.set("tema", theme);
70
+ const response = await page.goto(url.href, { waitUntil: "networkidle" });
71
+ if (!response?.ok())
72
+ throw new Error(`${response?.status()} ${url.href}`);
73
+ // Load lazy images and let the layout settle, then go back to the top.
74
+ await page.evaluate(async () => {
75
+ for (let y = 0; y < document.body.scrollHeight; y += 600) {
76
+ scrollTo(0, y);
77
+ await new Promise((r) => setTimeout(r, 60));
78
+ }
79
+ scrollTo(0, 0);
80
+ await document.fonts.ready;
81
+ await new Promise((r) => setTimeout(r, 250));
82
+ });
83
+ const id = `${name}.${theme}.${device}`;
84
+ await writeFile(join(out, `${id}.json`), JSON.stringify(await page.evaluate(collect)));
85
+ await page.screenshot({
86
+ path: join(out, `${id}.jpg`),
87
+ fullPage: true,
88
+ quality: 70,
89
+ type: "jpeg",
90
+ });
91
+ count++;
92
+ }
93
+ }
94
+ await context.close();
95
+ }
96
+ await browser.close();
97
+ console.log(`${count} snapshots in ${out}`);
98
+ }
99
+ /** Runs in the page: one row per visible element. */
100
+ function collect() {
101
+ const props = [
102
+ "color",
103
+ "background-color",
104
+ "background-image",
105
+ "border-top-width",
106
+ "border-right-width",
107
+ "border-bottom-width",
108
+ "border-left-width",
109
+ "border-top-color",
110
+ "border-right-color",
111
+ "border-bottom-color",
112
+ "border-left-color",
113
+ "border-top-left-radius",
114
+ "border-top-right-radius",
115
+ "border-bottom-right-radius",
116
+ "border-bottom-left-radius",
117
+ "font-family",
118
+ "font-size",
119
+ "font-weight",
120
+ "font-stretch",
121
+ "text-transform",
122
+ "letter-spacing",
123
+ "word-spacing",
124
+ "line-height",
125
+ "padding-top",
126
+ "padding-right",
127
+ "padding-bottom",
128
+ "padding-left",
129
+ "margin-top",
130
+ "margin-right",
131
+ "margin-bottom",
132
+ "margin-left",
133
+ "box-shadow",
134
+ "opacity",
135
+ "overflow-x",
136
+ "overflow-y",
137
+ "text-decoration-color",
138
+ "outline-color",
139
+ "outline-width",
140
+ "transition-property",
141
+ "transition-duration",
142
+ "position",
143
+ ];
144
+ const rows = [];
145
+ const walk = (el, path) => {
146
+ const style = getComputedStyle(el);
147
+ // Hidden elements don't show; skipping them also keeps the paths of their siblings
148
+ // stable when a refactor stops rendering a hidden branch.
149
+ if (style.display === "none")
150
+ return;
151
+ const r = el.getBoundingClientRect();
152
+ const row = {
153
+ path,
154
+ text: el.children.length
155
+ ? ""
156
+ : (el.textContent ?? "").trim().slice(0, 40),
157
+ box: [r.x + scrollX, r.y + scrollY, r.width, r.height].map((n) => Math.round(n * 10) / 10),
158
+ };
159
+ for (const p of props)
160
+ row[p] = style.getPropertyValue(p);
161
+ // Generated content has a colour too (the placeholder's watermark).
162
+ const before = getComputedStyle(el, "::before");
163
+ if (before.content !== "none")
164
+ row["::before"] = `${before.color} ${before.content}`;
165
+ rows.push(row);
166
+ let i = 0;
167
+ for (const child of el.children) {
168
+ if (["SCRIPT", "STYLE", "VITE-ERROR-OVERLAY"].includes(child.tagName))
169
+ continue;
170
+ if (getComputedStyle(child).display === "none")
171
+ continue;
172
+ walk(child, `${path}>${child.tagName.toLowerCase()}[${i++}]`);
173
+ }
174
+ };
175
+ walk(document.body, "body");
176
+ return rows;
177
+ }
178
+ async function diff(a, b) {
179
+ const files = (await readdir(a)).sort();
180
+ const common = new Map();
181
+ const inert = new Map();
182
+ let total = 0;
183
+ for (const file of files.filter((f) => f.endsWith(".json"))) {
184
+ const before = JSON.parse(await readFile(join(a, file), "utf8"));
185
+ const after = JSON.parse(await readFile(join(b, file), "utf8"));
186
+ const byPath = new Map(after.map((r) => [r.path, r]));
187
+ const found = [];
188
+ if (before.length !== after.length)
189
+ found.push(`elements: ${before.length} -> ${after.length}`);
190
+ for (const row of before) {
191
+ const other = byPath.get(row.path);
192
+ if (!other) {
193
+ found.push(`missing ${row.path}`);
194
+ continue;
195
+ }
196
+ for (const key of Object.keys(row)) {
197
+ if (key === "path")
198
+ continue;
199
+ const x = JSON.stringify(row[key]);
200
+ const y = JSON.stringify(other[key]);
201
+ if (x === y)
202
+ continue;
203
+ // A border's colour doesn't show while its width is 0 on both sides.
204
+ const side = key.match(/^border-(top|right|bottom|left)-color$/)?.[1];
205
+ if (side &&
206
+ row[`border-${side}-width`] === "0px" &&
207
+ other[`border-${side}-width`] === "0px")
208
+ continue;
209
+ if (INERT.has(key)) {
210
+ inert.set(key, (inert.get(key) ?? 0) + 1);
211
+ continue;
212
+ }
213
+ const change = `${key}: ${x} -> ${y}`;
214
+ found.push(`${change} @ ${row.path.split(">").slice(-3).join(">")} "${row.text}"`);
215
+ common.set(change, (common.get(change) ?? 0) + 1);
216
+ }
217
+ }
218
+ total += found.length;
219
+ if (found.length || values.verbose)
220
+ console.log(`${found.length ? "DIFF" : "same"} ${file.replace(".json", "")}${found.length ? ` (${found.length})` : ""}`);
221
+ if (values.verbose)
222
+ for (const line of found.slice(0, 40))
223
+ console.log(` ${line}`);
224
+ }
225
+ const shots = files.filter((f) => f.endsWith(".jpg"));
226
+ const changed = [];
227
+ for (const file of shots) {
228
+ const [x, y] = await Promise.all([
229
+ readFile(join(a, file)),
230
+ readFile(join(b, file)).catch(() => null),
231
+ ]);
232
+ if (!y || !x.equals(y))
233
+ changed.push(file.replace(".jpg", ""));
234
+ }
235
+ console.log(`\n${total} style or layout differences`);
236
+ if (inert.size)
237
+ console.log(`not counted (no pixel changes at rest): ${[...inert].map(([k, n]) => `${k} ×${n}`).join(", ")}`);
238
+ for (const [change, n] of [...common].sort((x, y) => y[1] - x[1]).slice(0, 25))
239
+ console.log(` ${n}× ${change}`);
240
+ console.log(`${shots.length} screenshots, ${changed.length} not identical${changed.length ? `: ${changed.join(", ")}` : ""}`);
241
+ if (total || changed.length)
242
+ process.exitCode = 1;
243
+ }
@@ -0,0 +1 @@
1
+ export {};