@su-sws/synthetic-web-team 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.
- package/AGENTS.md +149 -0
- package/README.md +321 -0
- package/package.json +58 -0
- package/packages/cli/bin/sws.mjs +722 -0
- package/packages/cli/src/axe.mjs +164 -0
- package/packages/cli/src/browser.mjs +192 -0
- package/packages/cli/src/checks.mjs +1254 -0
- package/packages/cli/src/github.mjs +131 -0
- package/packages/cli/src/history.mjs +137 -0
- package/packages/cli/src/perf.mjs +245 -0
- package/packages/cli/src/preflight.mjs +185 -0
- package/packages/cli/src/report.mjs +315 -0
- package/packages/cli/src/states.mjs +556 -0
- package/packages/wizard/bin/wizard.mjs +767 -0
- package/packages/wizard/src/detect.mjs +135 -0
- package/packages/wizard/src/emit.mjs +553 -0
- package/skills/role-accessibility-lead/SKILL.md +183 -0
- package/skills/role-api-architect/SKILL.md +65 -0
- package/skills/role-backend-developer/SKILL.md +66 -0
- package/skills/role-compliance-officer/SKILL.md +73 -0
- package/skills/role-content-designer/SKILL.md +145 -0
- package/skills/role-devops/SKILL.md +200 -0
- package/skills/role-discoverability/SKILL.md +164 -0
- package/skills/role-frontend-developer/SKILL.md +167 -0
- package/skills/role-fullstack-developer/SKILL.md +56 -0
- package/skills/role-identity-engineer/SKILL.md +77 -0
- package/skills/role-information-architect/SKILL.md +136 -0
- package/skills/role-infrastructure-architect/SKILL.md +60 -0
- package/skills/role-qa-engineer/SKILL.md +81 -0
- package/skills/role-security-operations/SKILL.md +56 -0
- package/skills/role-software-architect/SKILL.md +75 -0
- package/skills/role-staff-technical-architect/SKILL.md +73 -0
- package/skills/role-strategist/SKILL.md +122 -0
- package/skills/role-user-researcher/SKILL.md +66 -0
- package/skills/role-ux-designer/SKILL.md +159 -0
- package/skills/sws-compliance-check/SKILL.md +153 -0
- package/skills/sws-decanter/SKILL.md +191 -0
- package/skills/sws-deploy/SKILL.md +162 -0
- package/skills/sws-diverge/SKILL.md +131 -0
- package/skills/sws-github/SKILL.md +171 -0
- package/skills/sws-install/SKILL.md +97 -0
- package/skills/sws-netlify/SKILL.md +110 -0
- package/skills/sws-onboard/SKILL.md +85 -0
- package/skills/sws-preflight/SKILL.md +87 -0
- package/skills/sws-prior-art/SKILL.md +137 -0
- package/skills/sws-vercel/SKILL.md +117 -0
- package/standards/fragments/global-footer.yml +137 -0
- package/standards/fragments/identity-bar.yml +180 -0
- package/standards/hosting/capabilities.yml +215 -0
- package/standards/hosting/github-pages.yml +306 -0
- package/standards/hosting/netlify.yml +234 -0
- package/standards/hosting/vercel.yml +284 -0
- package/standards/patterns/components.md +162 -0
- package/standards/patterns/content.md +130 -0
- package/standards/patterns/decanter.md +352 -0
- package/standards/patterns/discoverability.md +121 -0
- package/standards/patterns/forms.md +116 -0
- package/standards/patterns/ia.md +126 -0
- package/standards/patterns/motion.md +267 -0
- package/standards/patterns/sws-conventions.md +225 -0
- package/standards/policy/accessibility.md +241 -0
- package/standards/policy/brand.md +213 -0
- package/standards/policy/escalation.md +53 -0
- package/standards/policy/identity.md +96 -0
- package/standards/policy/minsec.md +119 -0
- package/standards/policy/minweb.md +87 -0
- package/standards/policy/privacy.md +114 -0
- package/standards/policy/procurement.md +79 -0
- package/standards/prior-art/README.md +205 -0
- package/standards/prior-art/catalog.yml +409 -0
- package/standards/prior-art/patterns/INDEX.md +53 -0
- package/standards/prior-art/repos.yml +734 -0
- package/standards/recipes/astro-ssr/RECIPE.md +274 -0
- package/standards/recipes/astro-ssr/acceptance.yml +168 -0
- package/standards/recipes/astro-static/RECIPE.md +468 -0
- package/standards/recipes/astro-static/acceptance.yml +800 -0
- package/standards/recipes/next-ssr/RECIPE.md +407 -0
- package/standards/recipes/next-ssr/acceptance.yml +187 -0
- package/standards/scope.md +111 -0
- package/standards/stack/performance-budget.yml +95 -0
- package/standards/stack/reference-versions.yml +168 -0
- package/standards/stack/requirements.yml +154 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Publishing the report where a reader will actually see it.
|
|
2
|
+
//
|
|
3
|
+
// Two destinations, chosen by how the change arrived, because pull requests are
|
|
4
|
+
// first-class here but never required:
|
|
5
|
+
//
|
|
6
|
+
// push to main one long-lived "Site health" issue, UPDATED IN PLACE
|
|
7
|
+
// pull request one collapsible comment, UPDATED IN PLACE
|
|
8
|
+
//
|
|
9
|
+
// "In place" is the whole design. A new comment per push turns a PR into a wall
|
|
10
|
+
// of bot noise that people mute, and a new issue per push is worse. Both are
|
|
11
|
+
// found by an `<!-- sws:... -->` marker, so a human can edit around them.
|
|
12
|
+
//
|
|
13
|
+
// NOTHING HERE MAY FAIL THE BUILD. Every function resolves to a result object
|
|
14
|
+
// describing what happened. A network blip must not turn an advisory report
|
|
15
|
+
// into a red build, because that is the fastest way to get the tool removed.
|
|
16
|
+
//
|
|
17
|
+
// No SDK, no dependency: Node's global fetch against the REST API.
|
|
18
|
+
|
|
19
|
+
import { readFileSync } from 'node:fs';
|
|
20
|
+
|
|
21
|
+
// Read at call time, not module load. Two reasons: GitHub Enterprise sets
|
|
22
|
+
// GITHUB_API_URL and a module-load read can happen before the caller sets it,
|
|
23
|
+
// and a load-time constant makes this module untestable against a stand-in.
|
|
24
|
+
const apiBase = () => process.env.GITHUB_API_URL || 'https://api.github.com';
|
|
25
|
+
|
|
26
|
+
export const PR_MARKER = '<!-- sws:report:pr -->';
|
|
27
|
+
export const ISSUE_MARKER = '<!-- sws:report:health -->';
|
|
28
|
+
export const ISSUE_TITLE = 'Site health';
|
|
29
|
+
|
|
30
|
+
/** What CI are we in, if any? Returns null outside Actions. */
|
|
31
|
+
export function context(env = process.env) {
|
|
32
|
+
if (!env.GITHUB_REPOSITORY) return null;
|
|
33
|
+
const [owner, repo] = env.GITHUB_REPOSITORY.split('/');
|
|
34
|
+
const token = env.GITHUB_TOKEN || env.GH_TOKEN || env.INPUT_GITHUB_TOKEN || null;
|
|
35
|
+
|
|
36
|
+
// A PR number is only reliably available from the event payload.
|
|
37
|
+
let pr = null;
|
|
38
|
+
if (env.GITHUB_EVENT_NAME?.startsWith('pull_request') && env.GITHUB_EVENT_PATH) {
|
|
39
|
+
try {
|
|
40
|
+
const ev = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8'));
|
|
41
|
+
pr = ev?.pull_request?.number ?? ev?.number ?? null;
|
|
42
|
+
} catch { /* fall through: no PR number, so no comment */ }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
owner, repo, token, pr,
|
|
47
|
+
event: env.GITHUB_EVENT_NAME ?? null,
|
|
48
|
+
sha: env.GITHUB_SHA ?? null,
|
|
49
|
+
ref: env.GITHUB_REF_NAME ?? env.GITHUB_REF ?? null,
|
|
50
|
+
runId: env.GITHUB_RUN_ID ?? null,
|
|
51
|
+
serverUrl: env.GITHUB_SERVER_URL || 'https://github.com',
|
|
52
|
+
get runUrl() {
|
|
53
|
+
return this.runId ? `${this.serverUrl}/${this.owner}/${this.repo}/actions/runs/${this.runId}` : null;
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function api(ctx, path, { method = 'GET', body } = {}) {
|
|
59
|
+
const res = await fetch(`${apiBase()}${path}`, {
|
|
60
|
+
method,
|
|
61
|
+
headers: {
|
|
62
|
+
accept: 'application/vnd.github+json',
|
|
63
|
+
authorization: `Bearer ${ctx.token}`,
|
|
64
|
+
'x-github-api-version': '2022-11-28',
|
|
65
|
+
...(body ? { 'content-type': 'application/json' } : {}),
|
|
66
|
+
},
|
|
67
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
68
|
+
});
|
|
69
|
+
if (!res.ok) {
|
|
70
|
+
const text = await res.text().catch(() => '');
|
|
71
|
+
// 403 here is almost always a missing permission in the workflow, which is
|
|
72
|
+
// worth naming rather than reporting as a generic failure.
|
|
73
|
+
const hint = res.status === 403
|
|
74
|
+
? ' (check the workflow has `issues: write` and `pull-requests: write`)'
|
|
75
|
+
: '';
|
|
76
|
+
throw new Error(`${method} ${path} -> ${res.status}${hint} ${text.slice(0, 200)}`);
|
|
77
|
+
}
|
|
78
|
+
return res.status === 204 ? null : res.json();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Upsert the PR comment. Resolves to { action, url } or { skipped } / { error }. */
|
|
82
|
+
export async function upsertPrComment(ctx, body) {
|
|
83
|
+
if (!ctx?.token) return { skipped: 'no GITHUB_TOKEN' };
|
|
84
|
+
if (!ctx.pr) return { skipped: 'not a pull request' };
|
|
85
|
+
try {
|
|
86
|
+
const comments = await api(ctx, `/repos/${ctx.owner}/${ctx.repo}/issues/${ctx.pr}/comments?per_page=100`);
|
|
87
|
+
const mine = comments.find((c) => typeof c.body === 'string' && c.body.includes(PR_MARKER));
|
|
88
|
+
const payload = { body: `${PR_MARKER}\n${body}` };
|
|
89
|
+
const r = mine
|
|
90
|
+
? await api(ctx, `/repos/${ctx.owner}/${ctx.repo}/issues/comments/${mine.id}`, { method: 'PATCH', body: payload })
|
|
91
|
+
: await api(ctx, `/repos/${ctx.owner}/${ctx.repo}/issues/${ctx.pr}/comments`, { method: 'POST', body: payload });
|
|
92
|
+
return { action: mine ? 'updated' : 'created', url: r.html_url };
|
|
93
|
+
} catch (err) {
|
|
94
|
+
return { error: err.message };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Find the persistent Site health issue, if it exists. Separated from the
|
|
100
|
+
* upsert so the caller can read its embedded history BEFORE composing the body
|
|
101
|
+
* it is about to write.
|
|
102
|
+
*/
|
|
103
|
+
export async function findHealthIssue(ctx) {
|
|
104
|
+
if (!ctx?.token) return { skipped: 'no GITHUB_TOKEN' };
|
|
105
|
+
try {
|
|
106
|
+
// List rather than use the search API. Search is eventually consistent, so
|
|
107
|
+
// a just-created issue can be missing from results for a short window --
|
|
108
|
+
// which for an upsert means creating a second one. Listing open issues
|
|
109
|
+
// reads current state. (Reasoned, not observed: this code has never run
|
|
110
|
+
// against a repo with an existing issue.)
|
|
111
|
+
const issues = await api(ctx, `/repos/${ctx.owner}/${ctx.repo}/issues?state=open&per_page=100`);
|
|
112
|
+
const found = issues.find((i) => !i.pull_request && typeof i.body === 'string' && i.body.includes(ISSUE_MARKER));
|
|
113
|
+
return { issue: found ?? null };
|
|
114
|
+
} catch (err) {
|
|
115
|
+
return { error: err.message };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Upsert the Site health issue in place. */
|
|
120
|
+
export async function upsertHealthIssue(ctx, body, existing) {
|
|
121
|
+
if (!ctx?.token) return { skipped: 'no GITHUB_TOKEN' };
|
|
122
|
+
try {
|
|
123
|
+
const payload = { title: ISSUE_TITLE, body: `${ISSUE_MARKER}\n${body}` };
|
|
124
|
+
const r = existing
|
|
125
|
+
? await api(ctx, `/repos/${ctx.owner}/${ctx.repo}/issues/${existing.number}`, { method: 'PATCH', body: payload })
|
|
126
|
+
: await api(ctx, `/repos/${ctx.owner}/${ctx.repo}/issues`, { method: 'POST', body: payload });
|
|
127
|
+
return { action: existing ? 'updated' : 'created', url: r.html_url, number: r.number };
|
|
128
|
+
} catch (err) {
|
|
129
|
+
return { error: err.message };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Score history, which is what makes the number a trend rather than a reading.
|
|
2
|
+
//
|
|
3
|
+
// THE STORAGE PROBLEM, and why there are two answers.
|
|
4
|
+
//
|
|
5
|
+
// A trend needs prior state, and this project deliberately has no database, no
|
|
6
|
+
// service, and nothing committed that a build regenerates. Four options were
|
|
7
|
+
// considered:
|
|
8
|
+
//
|
|
9
|
+
// committed file commit noise on every build, merge conflicts on every PR
|
|
10
|
+
// Actions artifact expires (90 days default), so the trend silently dies
|
|
11
|
+
// Actions cache evictable, so the trend is unreliable rather than absent
|
|
12
|
+
// the issue body needs a marker convention, and nothing else
|
|
13
|
+
//
|
|
14
|
+
// So: the shared history lives in the body of the persistent "Site health"
|
|
15
|
+
// issue, in a fenced JSON block. It costs no new storage, survives
|
|
16
|
+
// indefinitely, is human-readable, and reuses the mechanism section 9 of the
|
|
17
|
+
// plan already chose for "the report finds the reader."
|
|
18
|
+
//
|
|
19
|
+
// Separately, `sws doctor` shows a local "delta since last run". That is a
|
|
20
|
+
// per-developer convenience, not shared state, so it lives in a gitignored file
|
|
21
|
+
// and is never reconciled with the shared history. Conflating the two would put
|
|
22
|
+
// one person's local runs into the project's trend.
|
|
23
|
+
|
|
24
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
25
|
+
import { join } from 'node:path';
|
|
26
|
+
import { writeResults } from './browser.mjs';
|
|
27
|
+
|
|
28
|
+
export const LOCAL_PATH = join('.sws', 'score-history.json');
|
|
29
|
+
|
|
30
|
+
// Enough to see a direction without turning the issue body into a database.
|
|
31
|
+
const LOCAL_CAP = 30;
|
|
32
|
+
const SHARED_CAP = 50;
|
|
33
|
+
|
|
34
|
+
const MARKER_START = '<!-- sws:history';
|
|
35
|
+
const MARKER_END = 'sws:history -->';
|
|
36
|
+
|
|
37
|
+
// --- local, for `sws doctor` -------------------------------------------------
|
|
38
|
+
|
|
39
|
+
export function readLocal(root) {
|
|
40
|
+
const p = join(root, LOCAL_PATH);
|
|
41
|
+
if (!existsSync(p)) return [];
|
|
42
|
+
try {
|
|
43
|
+
const j = JSON.parse(readFileSync(p, 'utf8'));
|
|
44
|
+
return Array.isArray(j?.entries) ? j.entries : [];
|
|
45
|
+
} catch {
|
|
46
|
+
// A corrupt history is not worth a warning, let alone a failure. It is a
|
|
47
|
+
// convenience file; start again.
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function appendLocal(root, entry) {
|
|
53
|
+
const entries = [...readLocal(root), entry].slice(-LOCAL_CAP);
|
|
54
|
+
writeResults(root, LOCAL_PATH, {
|
|
55
|
+
note: 'Local only, gitignored. `sws doctor` reads this for the delta since your last run. The project trend lives in the Site health issue.',
|
|
56
|
+
entries,
|
|
57
|
+
});
|
|
58
|
+
return entries;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// --- shared, embedded in the Site health issue body -------------------------
|
|
62
|
+
|
|
63
|
+
/** Pull the history out of an issue body. Returns [] for a body without one. */
|
|
64
|
+
export function parseFromBody(body) {
|
|
65
|
+
if (!body) return [];
|
|
66
|
+
const i = body.indexOf(MARKER_START);
|
|
67
|
+
const j = body.indexOf(MARKER_END, i);
|
|
68
|
+
if (i === -1 || j === -1) return [];
|
|
69
|
+
const block = body.slice(i + MARKER_START.length, j);
|
|
70
|
+
try {
|
|
71
|
+
const j2 = JSON.parse(block.replace(/```/g, '').trim());
|
|
72
|
+
return Array.isArray(j2) ? j2 : [];
|
|
73
|
+
} catch {
|
|
74
|
+
return [];
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Append to the issue's history and return the block to embed. Kept as an HTML
|
|
80
|
+
* comment so it is invisible in the rendered issue: the body is something a
|
|
81
|
+
* person reads, and a wall of JSON in it would defeat the purpose.
|
|
82
|
+
*/
|
|
83
|
+
export function embedInBody(history) {
|
|
84
|
+
const trimmed = history.slice(-SHARED_CAP);
|
|
85
|
+
return `${MARKER_START}\n${JSON.stringify(trimmed)}\n${MARKER_END}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// --- the bit everyone actually reads ----------------------------------------
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* "94, up from 91". Returns null when there is nothing to compare against,
|
|
92
|
+
* because "94, up from nothing" is worse than saying only 94.
|
|
93
|
+
*/
|
|
94
|
+
export function trend(current, history) {
|
|
95
|
+
const prior = history.filter((h) => typeof h?.score === 'number');
|
|
96
|
+
if (!prior.length) return null;
|
|
97
|
+
const previous = prior[prior.length - 1];
|
|
98
|
+
const delta = current - previous.score;
|
|
99
|
+
const when = previous.sha ? ` (${String(previous.sha).slice(0, 7)})` : '';
|
|
100
|
+
|
|
101
|
+
if (delta === 0) return { delta, text: `unchanged from ${previous.score}${when}` };
|
|
102
|
+
return {
|
|
103
|
+
delta,
|
|
104
|
+
text: delta > 0
|
|
105
|
+
? `up from ${previous.score}${when}`
|
|
106
|
+
: `down from ${previous.score}${when}`,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A tiny sparkline, for the issue body. Cheap and surprisingly readable. */
|
|
111
|
+
export function sparkline(history) {
|
|
112
|
+
const vals = history.map((h) => h?.score).filter((v) => typeof v === 'number');
|
|
113
|
+
if (vals.length < 2) return null;
|
|
114
|
+
const blocks = '▁▂▃▄▅▆▇█';
|
|
115
|
+
// Fixed 0-100 domain, not min/max: a normalised sparkline makes a wobble
|
|
116
|
+
// between 98 and 100 look like a cliff, which is exactly the false alarm this
|
|
117
|
+
// project keeps trying to avoid.
|
|
118
|
+
return vals.slice(-24)
|
|
119
|
+
.map((v) => blocks[Math.min(blocks.length - 1, Math.floor((Math.max(0, v) / 100) * blocks.length))])
|
|
120
|
+
.join('');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function entryFor({ score, findings, sha, ref, runId }) {
|
|
124
|
+
return {
|
|
125
|
+
at: new Date().toISOString(),
|
|
126
|
+
score,
|
|
127
|
+
sha: sha ?? null,
|
|
128
|
+
ref: ref ?? null,
|
|
129
|
+
runId: runId ?? null,
|
|
130
|
+
counts: {
|
|
131
|
+
pass: findings.filter((f) => f.state === 'pass').length,
|
|
132
|
+
fail: findings.filter((f) => f.state === 'fail').length,
|
|
133
|
+
unknown: findings.filter((f) => f.state === 'unknown').length,
|
|
134
|
+
acknowledged: findings.filter((f) => f.state === 'acknowledged').length,
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// Performance budget runner. Measures first-party transfer bytes and request
|
|
2
|
+
// counts per route in real Chromium, using the same plumbing as the axe runner.
|
|
3
|
+
//
|
|
4
|
+
// Deliberately NOT Lighthouse. The reasoning is in
|
|
5
|
+
// standards/stack/performance-budget.yml and the short version is that a
|
|
6
|
+
// Lighthouse score moves ten points between runs on a shared CI runner, and a
|
|
7
|
+
// self-moving number in a trended compliance score teaches people to ignore the
|
|
8
|
+
// score. Bytes are exact.
|
|
9
|
+
//
|
|
10
|
+
// Same honesty rule as axe: anything that could not be measured writes a status
|
|
11
|
+
// other than `ok`, and the reader in checks.mjs turns that into `unknown`.
|
|
12
|
+
|
|
13
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
14
|
+
import { join, relative } from 'node:path';
|
|
15
|
+
import YAML from 'yaml';
|
|
16
|
+
import {
|
|
17
|
+
serve, launchChromium, settleAnimations, revealAll, routeFor, newestMtime, writeResults,
|
|
18
|
+
} from './browser.mjs';
|
|
19
|
+
|
|
20
|
+
export const RESULTS_PATH = join('.sws', 'perf-results.json');
|
|
21
|
+
export const SCHEMA = 1;
|
|
22
|
+
|
|
23
|
+
const KB = 1024;
|
|
24
|
+
|
|
25
|
+
/** Load the budget standard, then apply any project override from the manifest. */
|
|
26
|
+
export function loadBudget({ standards, manifest }) {
|
|
27
|
+
const p = standards ? join(standards, 'stack', 'performance-budget.yml') : null;
|
|
28
|
+
if (!p || !existsSync(p)) return { error: `no performance budget at ${p ?? 'standards/stack/performance-budget.yml'}` };
|
|
29
|
+
|
|
30
|
+
let doc;
|
|
31
|
+
try { doc = YAML.parse(readFileSync(p, 'utf8')); }
|
|
32
|
+
catch (err) { return { error: `performance-budget.yml is not valid YAML: ${err.message}` }; }
|
|
33
|
+
|
|
34
|
+
const b = doc?.budgets;
|
|
35
|
+
if (!b?.total_kb) return { error: 'performance-budget.yml has no budgets.total_kb' };
|
|
36
|
+
|
|
37
|
+
const limits = {
|
|
38
|
+
total_kb: b.total_kb,
|
|
39
|
+
requests: b.requests,
|
|
40
|
+
...(b.by_type ?? {}),
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// A project override is a recorded divergence, not a workaround, so track
|
|
44
|
+
// which keys came from the manifest and say so in the report.
|
|
45
|
+
const overrides = {};
|
|
46
|
+
const o = manifest?.performance_budget;
|
|
47
|
+
if (o && typeof o === 'object') {
|
|
48
|
+
for (const [k, v] of Object.entries(o)) {
|
|
49
|
+
if (k === 'reason') continue;
|
|
50
|
+
if (typeof v === 'number' && k in limits) { limits[k] = v; overrides[k] = v; }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
limits, overrides,
|
|
56
|
+
overrideReason: o?.reason ?? null,
|
|
57
|
+
thirdParty: doc.third_party ?? {},
|
|
58
|
+
version: doc.version ?? null,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Classify by content-type, falling back to the URL extension. Content-type is
|
|
63
|
+
// authoritative when present; a local server can be terse about unusual types.
|
|
64
|
+
function classify(contentType, url) {
|
|
65
|
+
const ct = (contentType || '').split(';')[0].trim().toLowerCase();
|
|
66
|
+
if (ct.startsWith('image/')) return 'images';
|
|
67
|
+
if (ct.startsWith('font/')) return 'fonts';
|
|
68
|
+
if (ct.includes('javascript') || ct.includes('ecmascript')) return 'js';
|
|
69
|
+
if (ct.includes('css')) return 'css';
|
|
70
|
+
if (ct.includes('html')) return 'html';
|
|
71
|
+
if (!ct) {
|
|
72
|
+
const ext = (url.split('?')[0].match(/\.([a-z0-9]+)$/i)?.[1] ?? '').toLowerCase();
|
|
73
|
+
if (['png', 'jpg', 'jpeg', 'webp', 'avif', 'gif', 'svg', 'ico'].includes(ext)) return 'images';
|
|
74
|
+
if (['woff', 'woff2', 'ttf', 'otf', 'eot'].includes(ext)) return 'fonts';
|
|
75
|
+
if (['js', 'mjs', 'cjs'].includes(ext)) return 'js';
|
|
76
|
+
if (ext === 'css') return 'css';
|
|
77
|
+
if (['html', 'htm'].includes(ext)) return 'html';
|
|
78
|
+
}
|
|
79
|
+
return 'other';
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Measure every built route. Always resolves; never throws.
|
|
84
|
+
*/
|
|
85
|
+
export async function runPerf({ root, dist, html, standards, manifest }) {
|
|
86
|
+
const started = new Date().toISOString();
|
|
87
|
+
const bail = (status, detail) => writeResults(root, RESULTS_PATH, {
|
|
88
|
+
schema: SCHEMA, status, detail, generated: started, routes: [],
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
if (!dist || !existsSync(dist)) return bail('no-build', 'no build output found; run the build first');
|
|
92
|
+
if (!html.length) {
|
|
93
|
+
return bail('no-build', `no HTML found in ${relative(root, dist) || dist}; run the build first`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const budget = loadBudget({ standards, manifest });
|
|
97
|
+
if (budget.error) return bail('no-budget', budget.error);
|
|
98
|
+
|
|
99
|
+
const { browser, playwrightPkg, error } = await launchChromium(root);
|
|
100
|
+
if (error) {
|
|
101
|
+
return bail(/Playwright package/.test(error) ? 'deps-missing' : 'browser-unavailable', error);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const srv = await serve(dist);
|
|
105
|
+
const routes = [];
|
|
106
|
+
|
|
107
|
+
try {
|
|
108
|
+
const context = await browser.newContext();
|
|
109
|
+
for (const file of html) {
|
|
110
|
+
const route = routeFor(dist, file);
|
|
111
|
+
const page = await context.newPage();
|
|
112
|
+
|
|
113
|
+
const bytes = { html: 0, css: 0, js: 0, images: 0, fonts: 0, other: 0 };
|
|
114
|
+
const thirdParty = new Map();
|
|
115
|
+
let firstPartyRequests = 0;
|
|
116
|
+
|
|
117
|
+
page.on('response', async (res) => {
|
|
118
|
+
const url = res.url();
|
|
119
|
+
const isFirstParty = url.startsWith(srv.origin);
|
|
120
|
+
let len = 0;
|
|
121
|
+
try {
|
|
122
|
+
// Uncompressed body length. The local server does not gzip, so for
|
|
123
|
+
// first-party assets this is the raw size, which is what the budget
|
|
124
|
+
// is calibrated against.
|
|
125
|
+
len = (await res.body()).length;
|
|
126
|
+
} catch {
|
|
127
|
+
// Redirects and aborted requests have no body. Not an error.
|
|
128
|
+
}
|
|
129
|
+
if (isFirstParty) {
|
|
130
|
+
firstPartyRequests++;
|
|
131
|
+
bytes[classify(res.headers()['content-type'], url)] += len;
|
|
132
|
+
} else {
|
|
133
|
+
const origin = (() => { try { return new URL(url).origin; } catch { return url; } })();
|
|
134
|
+
const prev = thirdParty.get(origin) ?? { bytes: 0, requests: 0 };
|
|
135
|
+
thirdParty.set(origin, { bytes: prev.bytes + len, requests: prev.requests + 1 });
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
try {
|
|
140
|
+
const resp = await page.goto(`${srv.origin}${route}`, { waitUntil: 'load', timeout: 30_000 });
|
|
141
|
+
if (!resp || !resp.ok()) throw new Error(`HTTP ${resp ? resp.status() : 'no response'}`);
|
|
142
|
+
|
|
143
|
+
// SCROLL THE PAGE BEFORE MEASURING, or the budget lies by omission.
|
|
144
|
+
//
|
|
145
|
+
// Lazily hydrated islands (`client:visible`) do not request their
|
|
146
|
+
// JavaScript until they approach the viewport. Measuring only the
|
|
147
|
+
// initial load therefore reports the page as if that code did not
|
|
148
|
+
// exist. On this project's own site the difference was 52.9 KB and 2
|
|
149
|
+
// requests versus the truth once the islands hydrate -- and the whole
|
|
150
|
+
// point of a js budget here is to catch a client-side framework being
|
|
151
|
+
// shipped for static content, which is precisely what it was missing.
|
|
152
|
+
//
|
|
153
|
+
// What is budgeted is therefore "what a reader who reads the page
|
|
154
|
+
// downloads", not "what the first paint costs". Deferred bytes are
|
|
155
|
+
// still bytes.
|
|
156
|
+
await revealAll(page);
|
|
157
|
+
await settleAnimations(page);
|
|
158
|
+
|
|
159
|
+
// Unscored context only. See the header: lab timings on a build server
|
|
160
|
+
// are not evidence about a reader on campus wifi.
|
|
161
|
+
const timings = await page.evaluate(() => {
|
|
162
|
+
const n = performance.getEntriesByType('navigation')[0];
|
|
163
|
+
return n ? {
|
|
164
|
+
domContentLoaded: Math.round(n.domContentLoadedEventEnd),
|
|
165
|
+
load: Math.round(n.loadEventEnd),
|
|
166
|
+
} : null;
|
|
167
|
+
}).catch(() => null);
|
|
168
|
+
|
|
169
|
+
const total = Object.values(bytes).reduce((a, b) => a + b, 0);
|
|
170
|
+
routes.push({
|
|
171
|
+
route,
|
|
172
|
+
file: relative(root, file),
|
|
173
|
+
status: 'ok',
|
|
174
|
+
firstParty: {
|
|
175
|
+
total_kb: +(total / KB).toFixed(1),
|
|
176
|
+
requests: firstPartyRequests,
|
|
177
|
+
by_type_kb: Object.fromEntries(
|
|
178
|
+
Object.entries(bytes).map(([k, v]) => [k, +(v / KB).toFixed(1)])),
|
|
179
|
+
},
|
|
180
|
+
thirdParty: [...thirdParty.entries()]
|
|
181
|
+
.map(([origin, v]) => ({ origin, kb: +(v.bytes / KB).toFixed(1), requests: v.requests }))
|
|
182
|
+
.sort((a, b) => b.kb - a.kb),
|
|
183
|
+
timings_ms_unscored: timings,
|
|
184
|
+
});
|
|
185
|
+
} catch (err) {
|
|
186
|
+
routes.push({ route, file: relative(root, file), status: 'error', error: err.message });
|
|
187
|
+
} finally {
|
|
188
|
+
await page.close();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
} finally {
|
|
192
|
+
await browser.close().catch(() => {});
|
|
193
|
+
await srv.stop();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const failedRoutes = routes.filter((r) => r.status !== 'ok');
|
|
197
|
+
const okRoutes = routes.filter((r) => r.status === 'ok');
|
|
198
|
+
|
|
199
|
+
// Evaluate the budget per route. The worst route decides, because a reader
|
|
200
|
+
// lands on one page, not on an average.
|
|
201
|
+
const breaches = [];
|
|
202
|
+
for (const r of okRoutes) {
|
|
203
|
+
const checks = [
|
|
204
|
+
['total_kb', r.firstParty.total_kb],
|
|
205
|
+
['requests', r.firstParty.requests],
|
|
206
|
+
...Object.entries(r.firstParty.by_type_kb).map(([k, v]) => [`${k}_kb`, v]),
|
|
207
|
+
];
|
|
208
|
+
for (const [key, actual] of checks) {
|
|
209
|
+
const limit = budget.limits[key];
|
|
210
|
+
if (typeof limit === 'number' && actual > limit) {
|
|
211
|
+
breaches.push({ route: r.route, key, actual, limit, overridden: key in budget.overrides });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const origins = new Set(okRoutes.flatMap((r) => r.thirdParty.map((t) => t.origin)));
|
|
217
|
+
|
|
218
|
+
return writeResults(root, RESULTS_PATH, {
|
|
219
|
+
schema: SCHEMA,
|
|
220
|
+
status: failedRoutes.length === 0 ? 'ok'
|
|
221
|
+
: (failedRoutes.length === routes.length ? 'error' : 'partial'),
|
|
222
|
+
detail: failedRoutes.length ? `${failedRoutes.length} of ${routes.length} route(s) could not be measured` : undefined,
|
|
223
|
+
generated: started,
|
|
224
|
+
finished: new Date().toISOString(),
|
|
225
|
+
distMtime: newestMtime(dist),
|
|
226
|
+
versions: { playwright: playwrightPkg, browser: browser.version() },
|
|
227
|
+
budget: {
|
|
228
|
+
version: budget.version,
|
|
229
|
+
limits: budget.limits,
|
|
230
|
+
overrides: budget.overrides,
|
|
231
|
+
overrideReason: budget.overrideReason,
|
|
232
|
+
measures: 'first-party uncompressed bytes',
|
|
233
|
+
},
|
|
234
|
+
totals: {
|
|
235
|
+
routes: routes.length,
|
|
236
|
+
breaches: breaches.length,
|
|
237
|
+
worst_total_kb: okRoutes.length ? Math.max(...okRoutes.map((r) => r.firstParty.total_kb)) : null,
|
|
238
|
+
third_party_origins: origins.size,
|
|
239
|
+
third_party_kb: +(okRoutes.reduce((a, r) => a + r.thirdParty.reduce((x, t) => x + t.kb, 0), 0)).toFixed(1),
|
|
240
|
+
},
|
|
241
|
+
breaches,
|
|
242
|
+
thirdPartyOrigins: [...origins].sort(),
|
|
243
|
+
routes,
|
|
244
|
+
});
|
|
245
|
+
}
|