@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.
- package/README.md +45 -2
- package/dist/audit/cli.d.ts +1 -0
- package/dist/audit/cli.js +238 -0
- package/dist/audit/crux.d.ts +6 -0
- package/dist/audit/crux.js +29 -0
- package/dist/audit/fetch.d.ts +17 -0
- package/dist/audit/fetch.js +51 -0
- package/dist/audit/findings.d.ts +9 -0
- package/dist/audit/findings.js +514 -0
- package/dist/audit/index.d.ts +6 -0
- package/dist/audit/index.js +3 -0
- package/dist/audit/lighthouse.d.ts +2 -0
- package/dist/audit/lighthouse.js +84 -0
- package/dist/audit/page.d.ts +10 -0
- package/dist/audit/page.js +156 -0
- package/dist/audit/profile.d.ts +11 -0
- package/dist/audit/profile.js +21 -0
- package/dist/audit/render.d.ts +8 -0
- package/dist/audit/render.js +63 -0
- package/dist/audit/rerender.d.ts +1 -0
- package/dist/audit/rerender.js +55 -0
- package/dist/audit/reviews.d.ts +2 -0
- package/dist/audit/reviews.js +36 -0
- package/dist/audit/scores.d.ts +3 -0
- package/dist/audit/scores.js +51 -0
- package/dist/audit/site.d.ts +19 -0
- package/dist/audit/site.js +78 -0
- package/dist/audit/summary.d.ts +2 -0
- package/dist/audit/summary.js +59 -0
- package/dist/audit/types.d.ts +132 -0
- package/dist/audit/types.js +1 -0
- package/dist/browser/cli.d.ts +1 -0
- package/dist/browser/cli.js +11 -0
- package/dist/browser/index.d.ts +15 -0
- package/dist/browser/index.js +63 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +34 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -0
- package/dist/refs/cli.d.ts +1 -0
- package/dist/refs/cli.js +193 -0
- package/dist/refs/glyphs.d.ts +1 -0
- package/dist/refs/glyphs.js +101 -0
- package/dist/refs/images.d.ts +1 -0
- package/dist/refs/images.js +163 -0
- package/dist/refs/snapshot.d.ts +1 -0
- package/dist/refs/snapshot.js +243 -0
- package/dist/refs/text.d.ts +1 -0
- package/dist/refs/text.js +487 -0
- package/package.json +34 -5
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @a.incantalupo/web-tools
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Checks and captures for any website, as one command: `stack-tools`. Part of [web-stack-kb](../../README.md); the rules behind the checks are its topic skills (readability, performance, SEO, design, browser).
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
stack-tools # the list of commands
|
|
7
|
+
stack-tools browser [url] # your own Chromium window: sign in by hand, tools use it with --mine
|
|
8
|
+
stack-tools refs <url...> [--full] [--mine] [--out dir | --out-root dir] # desktop + mobile screenshots -> ./design-refs/<date>
|
|
9
|
+
stack-tools snap <dir> <url...> # computed styles + screenshots of pages, in every theme
|
|
10
|
+
stack-tools diff <before> <after>
|
|
11
|
+
stack-tools text <url...> [--verbose] [--login <email>] # reading ease (Gulpease), text size, contrast, fields, tap targets
|
|
12
|
+
stack-tools glyphs <url...> # characters the page fonts don't cover
|
|
13
|
+
stack-tools images <url...> # which image file each slot downloads (3x phone, 2x laptop, 1x monitor)
|
|
14
|
+
stack-tools audit <url> [--profile file.ts] [--render] [--teaser] [--reviews a.json...] [--preview] [--header 'Name: value'] [--keys .env] [--out dir | --out-root dir]
|
|
15
|
+
stack-tools audit-rerender <dir> [--profile file.ts] [--teaser] # rebuild a report from its findings.json, no new crawl
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Outputs go where you run the command (`./design-refs`, `./site-eval/<host>/<date>`) unless `--out` or `--out-root` says otherwise. A project keeps its own outputs; nothing is written inside this package.
|
|
19
|
+
|
|
20
|
+
## Setup
|
|
21
|
+
|
|
22
|
+
- In a project: `pnpm add -D @a.incantalupo/web-tools`, then scripts like `"check:text": "stack-tools text"`. The templates ship it.
|
|
23
|
+
- Chromium: the tools use Playwright's (`CHROME_PATH`, default `~/.cache/ms-playwright/chromium-1194/chrome-linux/chrome`). On WSL see the KB's `browser/gotcha/chromium-on-wsl`.
|
|
24
|
+
- `stack-tools browser` keeps its profile in `~/.cache/stack-tools/chrome-profile` (or the older `~/.cache/dealer-platform/chrome-profile` if it exists, so sign-ins survive the move).
|
|
25
|
+
|
|
26
|
+
## The audit and its profiles
|
|
27
|
+
|
|
28
|
+
`stack-tools audit` crawls a site the way a phone, Google and the AI assistants get it, runs Lighthouse, and writes `findings.json` (every check with its evidence) and `summary.md`. What it checks and how it grades: [docs/audit-checks.md](docs/audit-checks.md).
|
|
29
|
+
|
|
30
|
+
A **profile** adapts it to a niche and writes that niche's reports. It lives in the project that sells to the niche, so its wording and sales notes stay private:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
// tools/site-eval/src/profile.ts in dealer-platform
|
|
34
|
+
import type { AuditProfile } from '@a.incantalupo/web-tools/audit';
|
|
35
|
+
export default {
|
|
36
|
+
name: 'dealer',
|
|
37
|
+
types: { business: ['AutoDealer', 'LocalBusiness'], items: ['Vehicle', 'Offer'] }, // replace the defaults
|
|
38
|
+
async write(result, outDir, { teaser }) { /* dealer.it.md, prospect.md, teaser.pdf */ }
|
|
39
|
+
} satisfies AuditProfile;
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`@a.incantalupo/web-tools/audit` exports the result types, `computeScores`, `buildFindings`, `renderSummary`. The package root exports the own-browser connection (`connectMyChrome`, `openMyChrome`, `isOpen`) and the polite fetch helpers (`timedFetch`, `tryFetch`, `mapLimit`) for a project's own scrapers.
|
|
43
|
+
|
|
44
|
+
## Releasing
|
|
45
|
+
|
|
46
|
+
Bump `version`, add a line to the KB's `CHANGELOG.md`, commit, then `npm publish --access public` here (it builds first; npm asks for the passkey). Renovate brings it to every project.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { extraHeaders, mapLimit, timedFetch, tryFetch } from "./fetch.js";
|
|
6
|
+
import { queryCrux } from "./crux.js";
|
|
7
|
+
import { buildFindings } from "./findings.js";
|
|
8
|
+
import { runLighthouse } from "./lighthouse.js";
|
|
9
|
+
import { analyzePage, withRendered } from "./page.js";
|
|
10
|
+
import { openRenderer } from "./render.js";
|
|
11
|
+
import { AI_BOTS, botAccess, parseRobots, readSitemap } from "./site.js";
|
|
12
|
+
import { readReviews } from "./reviews.js";
|
|
13
|
+
import { computeScores } from "./scores.js";
|
|
14
|
+
import { loadProfile } from "./profile.js";
|
|
15
|
+
import { renderSummary } from "./summary.js";
|
|
16
|
+
const { values, positionals } = parseArgs({
|
|
17
|
+
allowPositionals: true,
|
|
18
|
+
options: {
|
|
19
|
+
pages: { type: "string", default: "25" },
|
|
20
|
+
lighthouse: { type: "string", default: "3" },
|
|
21
|
+
out: { type: "string" },
|
|
22
|
+
// Reports go to <out-root>/<host>/<date> (default ./site-eval) unless --out is given.
|
|
23
|
+
"out-root": { type: "string" },
|
|
24
|
+
// A module in your project that adds niche checks and writes its own reports
|
|
25
|
+
// (see AuditProfile in profile.ts): e.g. a dealer's Italian report and teaser.
|
|
26
|
+
profile: { type: "string" },
|
|
27
|
+
// An env file with keys for outside data (GOOGLE_API_KEY for CrUX) and the profile (a sender box).
|
|
28
|
+
// Not `--env-file`: Node reads that flag anywhere on the command line, even after the script.
|
|
29
|
+
keys: { type: "string" },
|
|
30
|
+
reviews: { type: "string", multiple: true, default: [] },
|
|
31
|
+
teaser: { type: "boolean", default: false },
|
|
32
|
+
// A preview host (our demos on *.vercel.app) that blocks indexing on purpose.
|
|
33
|
+
preview: { type: "boolean", default: false },
|
|
34
|
+
// Also open every page in a real browser, as a visitor: widgets added by
|
|
35
|
+
// JavaScript (WhatsApp, chat, prices) count for the contact checks.
|
|
36
|
+
render: { type: "boolean", default: false },
|
|
37
|
+
// "Name: value", sent with every request: the site owner's firewall allowlist.
|
|
38
|
+
header: { type: "string", multiple: true, default: [] },
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
const envFile = values.keys && resolve(process.env.INIT_CWD ?? process.cwd(), values.keys);
|
|
42
|
+
if (envFile && existsSync(envFile))
|
|
43
|
+
process.loadEnvFile(envFile);
|
|
44
|
+
for (const h of values.header ?? []) {
|
|
45
|
+
const i = h.indexOf(":");
|
|
46
|
+
if (i > 0)
|
|
47
|
+
extraHeaders[h.slice(0, i).trim()] = h.slice(i + 1).trim();
|
|
48
|
+
}
|
|
49
|
+
const target = positionals[0];
|
|
50
|
+
if (!target) {
|
|
51
|
+
console.error("Usage: stack-tools audit <url> [--pages 25] [--lighthouse 3] [--out dir | --out-root dir] [--profile file.ts] [--reviews business.json [--reviews competitor.json]...] [--teaser] [--preview] [--render] [--header 'Name: value']");
|
|
52
|
+
process.exit(1);
|
|
53
|
+
}
|
|
54
|
+
const startedAt = new Date().toISOString();
|
|
55
|
+
const base = new URL(target);
|
|
56
|
+
// The home page first: www.example.it often redirects to example.it (or back), and
|
|
57
|
+
// every same-site check below must use the origin the site actually answers on.
|
|
58
|
+
const homeRes = await timedFetch(base.toString());
|
|
59
|
+
if (homeRes.status !== 200) {
|
|
60
|
+
// A 403/429 here is usually bot protection: every check below would report the
|
|
61
|
+
// block, not the site. Better no report than a wrong one in front of a client.
|
|
62
|
+
console.error(`The home page answered ${homeRes.status} (${homeRes.finalUrl}): the site blocks automated checks or is down. No report written. On a site you run, let the audit through the firewall (a secret header, then --header "Name: value"; see the tool's README).`);
|
|
63
|
+
process.exit(2);
|
|
64
|
+
}
|
|
65
|
+
const origin = new URL(homeRes.finalUrl).origin;
|
|
66
|
+
const maxPages = Number(values.pages);
|
|
67
|
+
const cwd = process.env.INIT_CWD ?? process.cwd();
|
|
68
|
+
const outDir = values.out
|
|
69
|
+
? resolve(cwd, values.out)
|
|
70
|
+
: resolve(cwd, values["out-root"] ?? "site-eval", new URL(origin).host, startedAt.slice(0, 10));
|
|
71
|
+
const profile = await loadProfile(values.profile && resolve(cwd, values.profile));
|
|
72
|
+
await mkdir(outDir, { recursive: true });
|
|
73
|
+
console.log(`audit ${origin} -> ${outDir}${profile ? ` (profile ${profile.name})` : ""}`);
|
|
74
|
+
const httpRes = await tryFetch(`http://${base.host}/`);
|
|
75
|
+
const https = !!httpRes?.finalUrl.startsWith("https:");
|
|
76
|
+
const robotsRes = await tryFetch(`${origin}/robots.txt`);
|
|
77
|
+
const robotsTxt = robotsRes?.status === 200 ? robotsRes.body : null;
|
|
78
|
+
const robots = parseRobots(robotsTxt ?? "");
|
|
79
|
+
const aiBots = Object.fromEntries(AI_BOTS.map((b) => [b, botAccess(robots.groups, b)]));
|
|
80
|
+
const sitemapUrls = robots.sitemaps.length
|
|
81
|
+
? robots.sitemaps
|
|
82
|
+
: [`${origin}/sitemap.xml`];
|
|
83
|
+
const sitemaps = (await Promise.all(sitemapUrls.map((u) => readSitemap(u)))).flat();
|
|
84
|
+
const llmsRes = await tryFetch(`${origin}/llms.txt`);
|
|
85
|
+
const llmsTxt = llmsRes?.status === 200 && !/<html/i.test(llmsRes.body);
|
|
86
|
+
const renderer = values.render ? await openRenderer() : null;
|
|
87
|
+
/** The page as the server sent it, plus (with --render) what a visitor's browser shows. */
|
|
88
|
+
async function visit(url, res) {
|
|
89
|
+
if (!res)
|
|
90
|
+
return { ...emptyPage(url), status: 0 };
|
|
91
|
+
if (!(res.headers.get("content-type") ?? "").includes("text/html"))
|
|
92
|
+
return null;
|
|
93
|
+
const raw = analyzePage(res, origin);
|
|
94
|
+
if (!renderer || res.status !== 200)
|
|
95
|
+
return raw;
|
|
96
|
+
const seen = await renderer.render(res.finalUrl);
|
|
97
|
+
return seen?.status === 200
|
|
98
|
+
? withRendered(raw, analyzePage({ ...seen, body: seen.dom }, origin))
|
|
99
|
+
: raw;
|
|
100
|
+
}
|
|
101
|
+
const home = (await visit(homeRes.url, homeRes));
|
|
102
|
+
const queue = [
|
|
103
|
+
...new Set([
|
|
104
|
+
home.finalUrl,
|
|
105
|
+
...home.internalLinks,
|
|
106
|
+
// Sitemaps may list the other spelling of the host (www or not): same site.
|
|
107
|
+
...sitemaps
|
|
108
|
+
.flatMap((s) => s.locs)
|
|
109
|
+
.map((u) => sameSite(u))
|
|
110
|
+
.filter((u) => u !== null),
|
|
111
|
+
]),
|
|
112
|
+
].filter((u) => !/\.(pdf|jpe?g|png|webp|gif|svg|zip|xml)(\?|$)/i.test(u));
|
|
113
|
+
console.log(`crawling ${Math.min(queue.length, maxPages)} of ${queue.length} discovered URLs`);
|
|
114
|
+
const pages = [home];
|
|
115
|
+
// With a browser, one page at a time (a visitor's pace); without, three at once.
|
|
116
|
+
const rest = await mapLimit(queue.slice(1, maxPages), renderer ? 1 : 3, async (url) => visit(url, await tryFetch(url)));
|
|
117
|
+
pages.push(...rest.filter((p) => p !== null));
|
|
118
|
+
await renderer?.close();
|
|
119
|
+
const lhCount = Number(values.lighthouse);
|
|
120
|
+
const lhTargets = pickLighthouseTargets(pages.filter((p) => p.status === 200), lhCount);
|
|
121
|
+
const lighthouse = lhTargets.length
|
|
122
|
+
? await runLighthouse(lhTargets, outDir)
|
|
123
|
+
: [];
|
|
124
|
+
// Real visitors: needs GOOGLE_API_KEY (tools/site-eval/.env); without it the report says so.
|
|
125
|
+
const apiKey = process.env.GOOGLE_API_KEY;
|
|
126
|
+
let crux = null;
|
|
127
|
+
if (apiKey) {
|
|
128
|
+
try {
|
|
129
|
+
crux = {
|
|
130
|
+
home: await queryCrux(apiKey, { url: home.finalUrl }),
|
|
131
|
+
origin: await queryCrux(apiKey, {
|
|
132
|
+
origin: new URL(home.finalUrl).origin,
|
|
133
|
+
}),
|
|
134
|
+
error: null,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
catch (e) {
|
|
138
|
+
crux = { home: null, origin: null, error: e.message };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
else
|
|
142
|
+
console.log("no GOOGLE_API_KEY: skipping real-visitor data (CrUX)");
|
|
143
|
+
const reviews = await Promise.all((values.reviews ?? []).map((f) => readReviews(resolve(cwd, f))));
|
|
144
|
+
const partial = {
|
|
145
|
+
target: base.toString(),
|
|
146
|
+
preview: values.preview ?? false,
|
|
147
|
+
rendered: !!renderer,
|
|
148
|
+
startedAt,
|
|
149
|
+
pagesAnalyzed: pages.length,
|
|
150
|
+
site: {
|
|
151
|
+
https,
|
|
152
|
+
robotsTxt,
|
|
153
|
+
sitemaps: sitemaps.map(({ locs, ...s }) => s),
|
|
154
|
+
llmsTxt,
|
|
155
|
+
aiBots,
|
|
156
|
+
},
|
|
157
|
+
pages,
|
|
158
|
+
lighthouse,
|
|
159
|
+
crux,
|
|
160
|
+
reviews,
|
|
161
|
+
};
|
|
162
|
+
const findings = buildFindings(partial, profile?.types);
|
|
163
|
+
const result = {
|
|
164
|
+
...partial,
|
|
165
|
+
findings,
|
|
166
|
+
scores: computeScores(findings, lighthouse),
|
|
167
|
+
finishedAt: new Date().toISOString(),
|
|
168
|
+
};
|
|
169
|
+
await writeFile(join(outDir, "findings.json"), JSON.stringify(result, null, 2));
|
|
170
|
+
await writeFile(join(outDir, "summary.md"), renderSummary(result));
|
|
171
|
+
if (profile)
|
|
172
|
+
await profile.write(result, outDir, { teaser: values.teaser ?? false });
|
|
173
|
+
console.log(`done: score ${result.scores.overall}/100, ${result.findings.filter((f) => f.severity === "high").length} high, ${result.findings.filter((f) => f.severity === "medium").length} medium -> ${join(outDir, "summary.md")}`);
|
|
174
|
+
function pickLighthouseTargets(ok, n) {
|
|
175
|
+
if (n <= 0 || !ok.length)
|
|
176
|
+
return [];
|
|
177
|
+
const picks = [ok[0].finalUrl];
|
|
178
|
+
const richest = [...ok.slice(1)].sort((a, b) => b.images - a.images)[0];
|
|
179
|
+
if (richest)
|
|
180
|
+
picks.push(richest.finalUrl);
|
|
181
|
+
const contact = ok.find((p) => /contatt|contact/i.test(p.url) && !picks.includes(p.finalUrl));
|
|
182
|
+
if (contact)
|
|
183
|
+
picks.push(contact.finalUrl);
|
|
184
|
+
for (const p of ok)
|
|
185
|
+
if (picks.length < n && !picks.includes(p.finalUrl))
|
|
186
|
+
picks.push(p.finalUrl);
|
|
187
|
+
return picks.slice(0, n);
|
|
188
|
+
}
|
|
189
|
+
function emptyPage(url) {
|
|
190
|
+
return {
|
|
191
|
+
url,
|
|
192
|
+
finalUrl: url,
|
|
193
|
+
status: 0,
|
|
194
|
+
ttfbMs: 0,
|
|
195
|
+
htmlBytes: 0,
|
|
196
|
+
contentEncoding: null,
|
|
197
|
+
cacheControl: null,
|
|
198
|
+
title: "",
|
|
199
|
+
metaDescription: "",
|
|
200
|
+
h1Count: 0,
|
|
201
|
+
canonical: null,
|
|
202
|
+
noindex: false,
|
|
203
|
+
lang: null,
|
|
204
|
+
jsonLdTypes: [],
|
|
205
|
+
jsonLdErrors: 0,
|
|
206
|
+
images: 0,
|
|
207
|
+
imagesWithoutAlt: 0,
|
|
208
|
+
legacyImageFormats: 0,
|
|
209
|
+
scripts: 0,
|
|
210
|
+
thirdPartyHosts: [],
|
|
211
|
+
telLinks: 0,
|
|
212
|
+
whatsappLinks: 0,
|
|
213
|
+
mailtoLinks: 0,
|
|
214
|
+
forms: 0,
|
|
215
|
+
wordCount: 0,
|
|
216
|
+
hasPrice: false,
|
|
217
|
+
mapsLinks: 0,
|
|
218
|
+
insecureResources: 0,
|
|
219
|
+
internalLinks: [],
|
|
220
|
+
shareLinks: [],
|
|
221
|
+
generator: null,
|
|
222
|
+
builtWith: [],
|
|
223
|
+
credits: null,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
/** The URL on the site's own origin when it's the same site with or without www. */
|
|
227
|
+
function sameSite(url) {
|
|
228
|
+
try {
|
|
229
|
+
const u = new URL(url);
|
|
230
|
+
const bare = (h) => h.replace(/^www\./, "");
|
|
231
|
+
if (bare(u.host) !== bare(new URL(origin).host))
|
|
232
|
+
return null;
|
|
233
|
+
return origin + u.pathname + u.search;
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const ENDPOINT = "https://chromeuxreport.googleapis.com/v1/records:queryRecord";
|
|
2
|
+
const p75 = (m) => m?.percentiles?.p75 == null ? null : Number(m.percentiles.p75);
|
|
3
|
+
const day = (d) => `${d.year}-${String(d.month).padStart(2, "0")}-${String(d.day).padStart(2, "0")}`;
|
|
4
|
+
export async function queryCrux(key, target, formFactor = "PHONE") {
|
|
5
|
+
const res = await fetch(`${ENDPOINT}?key=${encodeURIComponent(key)}`, {
|
|
6
|
+
method: "POST",
|
|
7
|
+
headers: { "content-type": "application/json" },
|
|
8
|
+
body: JSON.stringify({ ...target, formFactor }),
|
|
9
|
+
signal: AbortSignal.timeout(20_000),
|
|
10
|
+
});
|
|
11
|
+
if (res.status === 404)
|
|
12
|
+
return null; // not enough visits for Google to publish
|
|
13
|
+
if (!res.ok)
|
|
14
|
+
throw new Error(`CrUX ${res.status}: ${(await res.text()).slice(0, 200).replace(/\s+/g, " ")}`);
|
|
15
|
+
const { record } = (await res.json());
|
|
16
|
+
const m = record.metrics;
|
|
17
|
+
const period = record.collectionPeriod;
|
|
18
|
+
return {
|
|
19
|
+
scope: "url" in target ? "url" : "origin",
|
|
20
|
+
key: record.key.url ?? record.key.origin ?? "",
|
|
21
|
+
formFactor,
|
|
22
|
+
period: period ? `${day(period.firstDate)} / ${day(period.lastDate)}` : "",
|
|
23
|
+
lcpMs: p75(m.largest_contentful_paint),
|
|
24
|
+
inpMs: p75(m.interaction_to_next_paint),
|
|
25
|
+
cls: p75(m.cumulative_layout_shift),
|
|
26
|
+
ttfbMs: p75(m.experimental_time_to_first_byte),
|
|
27
|
+
lcpGood: m.largest_contentful_paint?.histogram?.[0]?.density ?? null,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sent with every request (--header): for a site whose owner lets site-eval through
|
|
3
|
+
* their firewall with a secret header, instead of turning bot protection off.
|
|
4
|
+
*/
|
|
5
|
+
export declare const extraHeaders: Record<string, string>;
|
|
6
|
+
export type FetchResult = {
|
|
7
|
+
url: string;
|
|
8
|
+
finalUrl: string;
|
|
9
|
+
status: number;
|
|
10
|
+
ttfbMs: number;
|
|
11
|
+
headers: Headers;
|
|
12
|
+
body: string;
|
|
13
|
+
bytes: number;
|
|
14
|
+
};
|
|
15
|
+
export declare function timedFetch(url: string, init?: RequestInit): Promise<FetchResult>;
|
|
16
|
+
export declare function tryFetch(url: string, init?: RequestInit): Promise<FetchResult | null>;
|
|
17
|
+
export declare function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const USER_AGENT = "Mozilla/5.0 (compatible; site-eval/0.1; +https://github.com/Alessandro-Incantalupo)";
|
|
2
|
+
/**
|
|
3
|
+
* Sent with every request (--header): for a site whose owner lets site-eval through
|
|
4
|
+
* their firewall with a secret header, instead of turning bot protection off.
|
|
5
|
+
*/
|
|
6
|
+
export const extraHeaders = {};
|
|
7
|
+
export async function timedFetch(url, init = {}) {
|
|
8
|
+
const started = performance.now();
|
|
9
|
+
const res = await fetch(url, {
|
|
10
|
+
redirect: "follow",
|
|
11
|
+
signal: AbortSignal.timeout(20_000),
|
|
12
|
+
...init,
|
|
13
|
+
headers: {
|
|
14
|
+
"user-agent": USER_AGENT,
|
|
15
|
+
"accept-encoding": "gzip, br",
|
|
16
|
+
...extraHeaders,
|
|
17
|
+
...init.headers,
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
const ttfbMs = Math.round(performance.now() - started);
|
|
21
|
+
const body = init.method === "HEAD" ? "" : await res.text();
|
|
22
|
+
return {
|
|
23
|
+
url,
|
|
24
|
+
finalUrl: res.url,
|
|
25
|
+
status: res.status,
|
|
26
|
+
ttfbMs,
|
|
27
|
+
headers: res.headers,
|
|
28
|
+
body,
|
|
29
|
+
bytes: Buffer.byteLength(body),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
export async function tryFetch(url, init) {
|
|
33
|
+
try {
|
|
34
|
+
return await timedFetch(url, init);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export async function mapLimit(items, limit, fn) {
|
|
41
|
+
const results = new Array(items.length);
|
|
42
|
+
let next = 0;
|
|
43
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
44
|
+
while (next < items.length) {
|
|
45
|
+
const i = next++;
|
|
46
|
+
results[i] = await fn(items[i]);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
await Promise.all(workers);
|
|
50
|
+
return results;
|
|
51
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { EvalResult, Finding } from "./types.ts";
|
|
2
|
+
/** Schema.org types that count as "the business" and as "an item it sells"; a profile can replace them. */
|
|
3
|
+
export declare const DEFAULT_BUSINESS_TYPES: string[];
|
|
4
|
+
export declare const DEFAULT_ITEM_TYPES: string[];
|
|
5
|
+
export interface FindingTypes {
|
|
6
|
+
business?: string[];
|
|
7
|
+
items?: string[];
|
|
8
|
+
}
|
|
9
|
+
export declare function buildFindings(r: Omit<EvalResult, "findings" | "finishedAt" | "scores">, types?: FindingTypes): Finding[];
|