@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,156 @@
1
+ import * as cheerio from "cheerio";
2
+ const SHARE_HOSTS = [
3
+ "facebook.com/sharer",
4
+ "linkedin.com/shareArticle",
5
+ "twitter.com/share",
6
+ "x.com/intent",
7
+ "pinterest.com/pin",
8
+ "tumblr.com/share",
9
+ ];
10
+ function collectJsonLdTypes(node, out) {
11
+ if (Array.isArray(node))
12
+ return node.forEach((n) => collectJsonLdTypes(n, out));
13
+ if (!node || typeof node !== "object")
14
+ return;
15
+ const obj = node;
16
+ const type = obj["@type"];
17
+ if (typeof type === "string")
18
+ out.push(type);
19
+ else if (Array.isArray(type))
20
+ out.push(...type.filter((t) => typeof t === "string"));
21
+ for (const value of Object.values(obj))
22
+ if (value && typeof value === "object")
23
+ collectJsonLdTypes(value, out);
24
+ }
25
+ /** What the site is built with, from fingerprints in the HTML: who we'd be replacing. */
26
+ const BUILT_WITH = [
27
+ ["WordPress", /wp-content\/|wp-includes\//i],
28
+ ["Joomla", /\/media\/(jui|system)\/|Joomla!/i],
29
+ ["Wix", /static\.wixstatic\.com|wix\.com/i],
30
+ ["Squarespace", /squarespace\.com|static1\.squarespace/i],
31
+ ["Shopify", /cdn\.shopify\.com/i],
32
+ ["Webflow", /webflow\.(com|io)/i],
33
+ ["Jimdo", /jimdo/i],
34
+ ["MotorK / DealerK", /motork|dealerk/i],
35
+ ["GestionaleAuto", /gestionaleauto/i],
36
+ ["AutoScout24 dealer page", /autoscout24\.[a-z]+\/(concessionari|haendler)/i],
37
+ ["Elementor", /elementor/i],
38
+ ["Divi", /et_pb_|\/Divi\//i],
39
+ ["Next.js", /__NEXT_DATA__|\/_next\//],
40
+ ["Nuxt", /__NUXT__|\/_nuxt\//],
41
+ ];
42
+ const CREDITS = /(?:realizzat[oa]|sviluppat[oa]|progettat[oa]|creat[oa]|powered|design(?:ed)?|sito web|web design)\s+(?:da|by)\s*:?\s*([A-Za-z0-9][\w .&'-]{1,40}?)(?=\s*(?:[|·©\n]|$|\.(?:\s|$)|-\s))/i;
43
+ export function analyzePage(res, origin) {
44
+ const $ = cheerio.load(res.body);
45
+ const pageHost = new URL(res.finalUrl).host;
46
+ const jsonLdTypes = [];
47
+ let jsonLdErrors = 0;
48
+ $('script[type="application/ld+json"]').each((_, el) => {
49
+ try {
50
+ collectJsonLdTypes(JSON.parse($(el).text()), jsonLdTypes);
51
+ }
52
+ catch {
53
+ jsonLdErrors++;
54
+ }
55
+ });
56
+ const thirdPartyHosts = new Set();
57
+ $("script[src]").each((_, el) => {
58
+ try {
59
+ const host = new URL($(el).attr("src"), res.finalUrl).host;
60
+ if (host !== pageHost)
61
+ thirdPartyHosts.add(host);
62
+ }
63
+ catch {
64
+ /* ignore malformed src */
65
+ }
66
+ });
67
+ const hrefs = $("a[href]")
68
+ .map((_, el) => $(el).attr("href").trim())
69
+ .get();
70
+ const internalLinks = new Set();
71
+ for (const href of hrefs) {
72
+ try {
73
+ const u = new URL(href, res.finalUrl);
74
+ if (u.origin === origin && /^https?:$/.test(u.protocol)) {
75
+ u.hash = "";
76
+ internalLinks.add(u.toString());
77
+ }
78
+ }
79
+ catch {
80
+ /* ignore malformed href */
81
+ }
82
+ }
83
+ const imgs = $("img");
84
+ const text = $("body")
85
+ .clone()
86
+ .find("script,style,noscript")
87
+ .remove()
88
+ .end()
89
+ .text();
90
+ const footerText = ($("footer").text() || text.slice(-1500))
91
+ .replace(/\s+/g, " ")
92
+ .trim();
93
+ return {
94
+ url: res.url,
95
+ finalUrl: res.finalUrl,
96
+ status: res.status,
97
+ ttfbMs: res.ttfbMs,
98
+ htmlBytes: res.bytes,
99
+ contentEncoding: res.headers.get("content-encoding"),
100
+ cacheControl: res.headers.get("cache-control"),
101
+ title: $("head > title").first().text().trim(),
102
+ metaDescription: $('meta[name="description"]').attr("content")?.trim() ?? "",
103
+ h1Count: $("h1").length,
104
+ canonical: $('link[rel="canonical"]').attr("href") ?? null,
105
+ noindex: /noindex/i.test($('meta[name="robots"]').attr("content") ?? ""),
106
+ lang: $("html").attr("lang") ?? null,
107
+ jsonLdTypes: [...new Set(jsonLdTypes)],
108
+ jsonLdErrors,
109
+ images: imgs.length,
110
+ imagesWithoutAlt: imgs.filter((_, el) => !($(el).attr("alt") ?? "").trim())
111
+ .length,
112
+ legacyImageFormats: imgs.filter((_, el) => /\.(jpe?g|png|gif)(\?|$)/i.test($(el).attr("src") ?? "")).length,
113
+ scripts: $("script[src]").length,
114
+ thirdPartyHosts: [...thirdPartyHosts],
115
+ telLinks: hrefs.filter((h) => h.startsWith("tel:")).length,
116
+ whatsappLinks: hrefs.filter((h) => /wa\.me|api\.whatsapp\.com|whatsapp:/i.test(h)).length,
117
+ mailtoLinks: hrefs.filter((h) => h.startsWith("mailto:")).length,
118
+ forms: $("form").length,
119
+ wordCount: text.split(/\s+/).filter(Boolean).length,
120
+ hasPrice: /€\s?\d|\d[\d.,]*\s?€|\bprezzo\b/i.test(text),
121
+ mapsLinks: hrefs.filter((h) => /google\.[a-z.]+\/maps|maps\.app\.goo\.gl|goo\.gl\/maps/i.test(h)).length + $('iframe[src*="google.com/maps"]').length,
122
+ insecureResources: res.finalUrl.startsWith("https:")
123
+ ? $('script[src^="http:"], img[src^="http:"], link[href^="http:"][rel="stylesheet"], iframe[src^="http:"]').length
124
+ : 0,
125
+ internalLinks: [...internalLinks],
126
+ shareLinks: hrefs.filter((h) => SHARE_HOSTS.some((s) => h.includes(s))),
127
+ generator: $('meta[name="generator"]').attr("content")?.trim() || null,
128
+ builtWith: BUILT_WITH.filter(([, re]) => re.test(res.body)).map(([name]) => name),
129
+ credits: footerText.match(CREDITS)?.[1].trim() ?? null,
130
+ };
131
+ }
132
+ /** Fields a visitor sees: taken from the page after JavaScript ran. */
133
+ const VISITOR = [
134
+ ["telLinks", "tel"],
135
+ ["whatsappLinks", "whatsapp"],
136
+ ["forms", "forms"],
137
+ ["mapsLinks", "maps"],
138
+ ["hasPrice", "price"],
139
+ ];
140
+ /**
141
+ * Merges what the server sent (what Google and AI crawlers read first) with what a
142
+ * visitor's browser shows after JavaScript (chat widgets, WhatsApp buttons, prices
143
+ * loaded later). Contact checks use the rendered page, so a widget isn't reported
144
+ * missing; anything only there after JavaScript is listed in `jsOnly`.
145
+ */
146
+ export function withRendered(raw, dom) {
147
+ const jsOnly = VISITOR.filter(([field]) => !raw[field] && dom[field]).map(([, label]) => label);
148
+ const merged = { ...raw, rendered: true, jsOnly };
149
+ for (const [field] of VISITOR)
150
+ merged[field] = dom[field];
151
+ merged.shareLinks = dom.shareLinks;
152
+ merged.internalLinks = [
153
+ ...new Set([...raw.internalLinks, ...dom.internalLinks]),
154
+ ];
155
+ return merged;
156
+ }
@@ -0,0 +1,11 @@
1
+ import type { FindingTypes } from "./findings.ts";
2
+ import type { EvalResult } from "./types.ts";
3
+ export interface AuditProfile {
4
+ name: string;
5
+ types?: FindingTypes;
6
+ /** Writes the profile's own files next to findings.json and summary.md. */
7
+ write(result: EvalResult, outDir: string, options: {
8
+ teaser: boolean;
9
+ }): Promise<void>;
10
+ }
11
+ export declare function loadProfile(path?: string): Promise<AuditProfile | null>;
@@ -0,0 +1,21 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // A profile adapts the generic audit to a niche: extra schema.org types that count as the
10
+ // business and its items, and the reports for that niche's readers (e.g. a dealer's Italian
11
+ // report, a prospect sheet, a one-page teaser). It lives in the project that sells to that
12
+ // niche, not here: `stack-tools audit <url> --profile tools/site-eval/profile.ts`.
13
+ import { pathToFileURL } from "node:url";
14
+ export async function loadProfile(path) {
15
+ if (!path)
16
+ return null;
17
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(path).href)));
18
+ if (!mod.default?.write)
19
+ throw new Error(`${path} has no default export with write()`);
20
+ return mod.default;
21
+ }
@@ -0,0 +1,8 @@
1
+ import { type FetchResult } from "./fetch.ts";
2
+ export type Rendered = FetchResult & {
3
+ dom: string;
4
+ };
5
+ export declare function openRenderer(pauseMs?: number): Promise<{
6
+ render: (url: string) => Promise<Rendered | null>;
7
+ close: () => Promise<void>;
8
+ }>;
@@ -0,0 +1,63 @@
1
+ // Opens pages in a real browser (headless Chromium, its own honest user agent), the way
2
+ // a visitor gets them: JavaScript runs, chat and WhatsApp widgets appear, prices loaded
3
+ // later show up. Used with --render so contact checks don't report as missing what a
4
+ // visitor does see. One page at a time with a pause: a visitor's pace, not a crawler's.
5
+ // No stealth and no tricks: a site that refuses a browser it can see is automated is
6
+ // reported as blocked (see the 200 check in cli.ts).
7
+ import { existsSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { chromium } from "playwright-core";
11
+ import { extraHeaders } from "./fetch.js";
12
+ const PLAYWRIGHT_CHROMIUM = join(homedir(), ".cache/ms-playwright/chromium-1194/chrome-linux/chrome");
13
+ export async function openRenderer(pauseMs = 1500) {
14
+ const browser = await chromium.launch({
15
+ executablePath: process.env.CHROME_PATH ??
16
+ (existsSync(PLAYWRIGHT_CHROMIUM) ? PLAYWRIGHT_CHROMIUM : undefined),
17
+ headless: true,
18
+ });
19
+ const context = await browser.newContext({
20
+ locale: "it-IT",
21
+ viewport: { width: 412, height: 915 },
22
+ isMobile: true,
23
+ hasTouch: true,
24
+ extraHTTPHeaders: extraHeaders,
25
+ });
26
+ async function render(url) {
27
+ const page = await context.newPage();
28
+ try {
29
+ const started = performance.now();
30
+ const res = await page.goto(url, {
31
+ waitUntil: "load",
32
+ timeout: 30_000,
33
+ });
34
+ if (!res)
35
+ return null;
36
+ const timing = res.request().timing();
37
+ // Widgets (chat, WhatsApp, cookie banners) often arrive after "load".
38
+ await page.waitForTimeout(pauseMs);
39
+ const body = await res.text().catch(() => "");
40
+ const dom = await page.content();
41
+ const headers = new Headers(res.headers());
42
+ return {
43
+ url,
44
+ finalUrl: page.url(),
45
+ status: res.status(),
46
+ ttfbMs: Math.round(timing.responseStart > 0
47
+ ? timing.responseStart
48
+ : performance.now() - started),
49
+ headers,
50
+ body,
51
+ bytes: Buffer.byteLength(body),
52
+ dom,
53
+ };
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ finally {
59
+ await page.close();
60
+ }
61
+ }
62
+ return { render, close: () => browser.close() };
63
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,55 @@
1
+ import { existsSync } from "node:fs";
2
+ // Re-renders an existing report with today's checks and wording: findings and scores are
3
+ // rebuilt from the stored measurements, so a change to the checks, the grades or a profile's
4
+ // sentences doesn't need a new crawl.
5
+ // Usage: stack-tools audit-rerender <report dir> [--profile file.ts] [--teaser] [--reviews business.json [--reviews competitor.json]...] [--preview]
6
+ import { readFile, writeFile } from "node:fs/promises";
7
+ import { join, resolve } from "node:path";
8
+ import { parseArgs } from "node:util";
9
+ import { buildFindings } from "./findings.js";
10
+ import { readReviews } from "./reviews.js";
11
+ import { computeScores } from "./scores.js";
12
+ import { loadProfile } from "./profile.js";
13
+ import { renderSummary } from "./summary.js";
14
+ const { values, positionals } = parseArgs({
15
+ allowPositionals: true,
16
+ options: {
17
+ reviews: { type: "string", multiple: true },
18
+ preview: { type: "boolean" },
19
+ profile: { type: "string" },
20
+ // An env file with keys for outside data (GOOGLE_API_KEY for CrUX) and the profile (a sender box).
21
+ // Not `--env-file`: Node reads that flag anywhere on the command line, even after the script.
22
+ keys: { type: "string" },
23
+ teaser: { type: "boolean", default: false },
24
+ },
25
+ });
26
+ const envFile = values.keys && resolve(process.env.INIT_CWD ?? process.cwd(), values.keys);
27
+ if (envFile && existsSync(envFile))
28
+ process.loadEnvFile(envFile);
29
+ const here = (p) => resolve(process.env.INIT_CWD ?? ".", p);
30
+ const dir = positionals[0] && here(positionals[0]);
31
+ if (!dir) {
32
+ console.error("Usage: stack-tools audit-rerender <report dir> [--profile file.ts] [--teaser] [--reviews business.json [--reviews competitor.json]...] [--preview]");
33
+ process.exit(1);
34
+ }
35
+ const stored = JSON.parse(await readFile(join(dir, "findings.json"), "utf8"));
36
+ const r = {
37
+ ...stored,
38
+ preview: values.preview ?? stored.preview ?? false,
39
+ crux: stored.crux ?? null,
40
+ reviews: values.reviews
41
+ ? await Promise.all(values.reviews.map((f) => readReviews(here(f))))
42
+ : (stored.reviews ?? []),
43
+ lighthouse: stored.lighthouse.map((l) => ({
44
+ ...l,
45
+ screenshot: l.screenshot ?? null,
46
+ })),
47
+ };
48
+ const profile = await loadProfile(values.profile && here(values.profile));
49
+ r.findings = buildFindings(r, profile?.types);
50
+ r.scores = computeScores(r.findings, r.lighthouse);
51
+ await writeFile(join(dir, "findings.json"), JSON.stringify(r, null, 2));
52
+ await writeFile(join(dir, "summary.md"), renderSummary(r));
53
+ if (profile)
54
+ await profile.write(r, dir, { teaser: values.teaser ?? false });
55
+ console.log(`score ${r.scores.overall}/100 -> ${dir}`);
@@ -0,0 +1,2 @@
1
+ import type { Reviews } from "./types.ts";
2
+ export declare function readReviews(path: string): Promise<Reviews>;
@@ -0,0 +1,36 @@
1
+ // Google reviews, read from a file written by `pnpm reviews:scrape` (Takeout format):
2
+ // { name, rating, count, scrapedAt, reviews: [{ starRating, comment, createTime, reviewReply? }] }.
3
+ // Dates are approximate ("3 mesi fa" on Maps), good enough for "last 3 / 12 months".
4
+ import { readFile } from "node:fs/promises";
5
+ const STARS = {
6
+ ONE: 1,
7
+ TWO: 2,
8
+ THREE: 3,
9
+ FOUR: 4,
10
+ FIVE: 5,
11
+ };
12
+ export async function readReviews(path) {
13
+ const file = JSON.parse(await readFile(path, "utf8"));
14
+ const reviews = file.reviews ?? [];
15
+ const at = Date.parse(file.scrapedAt ?? "") || Date.now();
16
+ const within = (iso, months) => iso ? at - Date.parse(iso) < months * 30.5 * 86_400_000 : false;
17
+ const recent = reviews.filter((r) => within(r.createTime, 12));
18
+ const recentLow = recent.filter((r) => (STARS[r.starRating ?? ""] ?? 5) <= 3);
19
+ // Older scrapes didn't look for the owner's answers: unknown, not zero.
20
+ const knowsReplies = file.repliesRead === true || reviews.some((r) => r.reviewReply);
21
+ return {
22
+ name: file.name ?? path,
23
+ rating: file.rating ?? NaN,
24
+ count: file.count ?? reviews.length,
25
+ scrapedAt: file.scrapedAt ?? "",
26
+ read: reviews.length,
27
+ last12Months: recent.length,
28
+ last3Months: reviews.filter((r) => within(r.createTime, 3)).length,
29
+ withText: reviews.filter((r) => r.comment).length,
30
+ replied: knowsReplies ? reviews.filter((r) => r.reviewReply).length : null,
31
+ recentLow: recentLow.length,
32
+ recentLowReplied: knowsReplies
33
+ ? recentLow.filter((r) => r.reviewReply).length
34
+ : null,
35
+ };
36
+ }
@@ -0,0 +1,3 @@
1
+ import type { Area, EvalResult, Finding, Scores } from "./types.ts";
2
+ export declare const WEIGHTS: Record<Area, number>;
3
+ export declare function computeScores(findings: Finding[], lighthouse: EvalResult["lighthouse"]): Scores;
@@ -0,0 +1,51 @@
1
+ const PENALTY = {
2
+ high: 30,
3
+ medium: 12,
4
+ low: 4,
5
+ info: 0,
6
+ pass: 0,
7
+ };
8
+ const RANK = ["pass", "info", "low", "medium", "high"];
9
+ export const WEIGHTS = {
10
+ performance: 20,
11
+ conversion: 15,
12
+ reputation: 15,
13
+ crawl: 15,
14
+ "structured-data": 10,
15
+ "ai-visibility": 10,
16
+ content: 10,
17
+ local: 3,
18
+ hygiene: 2,
19
+ };
20
+ export function computeScores(findings, lighthouse) {
21
+ // Worst severity per (area, kind of problem).
22
+ const worst = new Map();
23
+ for (const f of findings) {
24
+ const k = `${f.area}:${f.id}`;
25
+ const prev = worst.get(k);
26
+ if (!prev || RANK.indexOf(f.severity) > RANK.indexOf(prev.severity))
27
+ worst.set(k, f);
28
+ }
29
+ const areas = {};
30
+ for (const f of worst.values())
31
+ areas[f.area] = Math.max(0, (areas[f.area] ?? 100) - PENALTY[f.severity]);
32
+ // Speed: Lighthouse's own mobile score already weighs LCP, CLS and blocking time,
33
+ // so it replaces the penalties (counting them again would take it to 0). Server
34
+ // response and real visitors' numbers, which Lighthouse doesn't see, still count.
35
+ const perf = lighthouse
36
+ .filter((l) => l.formFactor === "mobile" && l.scores.performance != null)
37
+ .map((l) => l.scores.performance);
38
+ if (perf.length) {
39
+ const extra = [...worst.values()]
40
+ .filter((f) => f.area === "performance" && /^(ttfb|crux-)/.test(f.id))
41
+ .reduce((n, f) => n + PENALTY[f.severity], 0);
42
+ areas.performance = Math.max(0, Math.round(perf.reduce((a, b) => a + b, 0) / perf.length) - extra);
43
+ }
44
+ let total = 0;
45
+ let weight = 0;
46
+ for (const [area, score] of Object.entries(areas)) {
47
+ total += score * WEIGHTS[area];
48
+ weight += WEIGHTS[area];
49
+ }
50
+ return { overall: weight ? Math.round(total / weight) : 0, areas };
51
+ }
@@ -0,0 +1,19 @@
1
+ export declare const AI_BOTS: readonly ["Googlebot", "Bingbot", "OAI-SearchBot", "ChatGPT-User", "GPTBot", "Claude-SearchBot", "Claude-User", "ClaudeBot", "PerplexityBot", "Google-Extended", "CCBot"];
2
+ type RobotsGroup = {
3
+ agents: string[];
4
+ disallow: string[];
5
+ allow: string[];
6
+ };
7
+ export declare function parseRobots(text: string): {
8
+ groups: RobotsGroup[];
9
+ sitemaps: string[];
10
+ };
11
+ export declare function botAccess(groups: RobotsGroup[], bot: string): "allowed" | "blocked";
12
+ export type SitemapInfo = {
13
+ url: string;
14
+ urls: number;
15
+ newestLastmod: string | null;
16
+ locs: string[];
17
+ };
18
+ export declare function readSitemap(url: string, depth?: number): Promise<SitemapInfo[]>;
19
+ export {};
@@ -0,0 +1,78 @@
1
+ import * as cheerio from "cheerio";
2
+ import { tryFetch } from "./fetch.js";
3
+ export const AI_BOTS = [
4
+ "Googlebot",
5
+ "Bingbot",
6
+ "OAI-SearchBot",
7
+ "ChatGPT-User",
8
+ "GPTBot",
9
+ "Claude-SearchBot",
10
+ "Claude-User",
11
+ "ClaudeBot",
12
+ "PerplexityBot",
13
+ "Google-Extended",
14
+ "CCBot",
15
+ ];
16
+ export function parseRobots(text) {
17
+ const groups = [];
18
+ const sitemaps = [];
19
+ let current = null;
20
+ let lastWasAgent = false;
21
+ for (const raw of text.split(/\r?\n/)) {
22
+ const line = raw.replace(/#.*/, "").trim();
23
+ const m = line.match(/^([A-Za-z-]+)\s*:\s*(.*)$/);
24
+ if (!m)
25
+ continue;
26
+ const key = m[1].toLowerCase();
27
+ const value = m[2].trim();
28
+ if (key === "user-agent") {
29
+ if (!current || !lastWasAgent) {
30
+ current = { agents: [], disallow: [], allow: [] };
31
+ groups.push(current);
32
+ }
33
+ current.agents.push(value.toLowerCase());
34
+ lastWasAgent = true;
35
+ continue;
36
+ }
37
+ lastWasAgent = false;
38
+ if (key === "sitemap")
39
+ sitemaps.push(value);
40
+ else if (current && key === "disallow" && value)
41
+ current.disallow.push(value);
42
+ else if (current && key === "allow" && value)
43
+ current.allow.push(value);
44
+ }
45
+ return { groups, sitemaps };
46
+ }
47
+ export function botAccess(groups, bot) {
48
+ const group = groups.find((g) => g.agents.includes(bot.toLowerCase())) ??
49
+ groups.find((g) => g.agents.includes("*"));
50
+ if (!group)
51
+ return "allowed";
52
+ return group.disallow.includes("/") && !group.allow.includes("/")
53
+ ? "blocked"
54
+ : "allowed";
55
+ }
56
+ export async function readSitemap(url, depth = 0) {
57
+ const res = await tryFetch(url);
58
+ if (!res || res.status !== 200 || !res.body.includes("<"))
59
+ return [];
60
+ const $ = cheerio.load(res.body, { xml: true });
61
+ const children = $("sitemapindex > sitemap > loc")
62
+ .map((_, el) => $(el).text().trim())
63
+ .get();
64
+ if (children.length && depth < 2) {
65
+ const nested = await Promise.all(children.slice(0, 10).map((c) => readSitemap(c, depth + 1)));
66
+ return nested.flat();
67
+ }
68
+ const locs = $("urlset > url > loc")
69
+ .map((_, el) => $(el).text().trim())
70
+ .get();
71
+ const lastmods = $("urlset > url > lastmod")
72
+ .map((_, el) => $(el).text().trim())
73
+ .get()
74
+ .sort();
75
+ return [
76
+ { url, urls: locs.length, newestLastmod: lastmods.at(-1) ?? null, locs },
77
+ ];
78
+ }
@@ -0,0 +1,2 @@
1
+ import type { EvalResult } from "./types.ts";
2
+ export declare function renderSummary(r: EvalResult): string;
@@ -0,0 +1,59 @@
1
+ const ORDER = ["high", "medium", "low", "info", "pass"];
2
+ export function renderSummary(r) {
3
+ const lines = [];
4
+ const count = (s) => r.findings.filter((f) => f.severity === s).length;
5
+ lines.push(`# site-eval: ${r.target}`, "");
6
+ lines.push(`Run ${r.startedAt} - ${r.finishedAt}. Pages analyzed: ${r.pagesAnalyzed}.`, "");
7
+ lines.push(`**Score ${r.scores?.overall ?? "-"}/100** (${Object.entries(r.scores?.areas ?? {})
8
+ .map(([a, v]) => `${a} ${v}`)
9
+ .join(", ")})`, "");
10
+ lines.push(`**High ${count("high")} | Medium ${count("medium")} | Low ${count("low")} | Pass ${count("pass")}**`, "");
11
+ if (r.lighthouse.length) {
12
+ lines.push("## Lighthouse", "");
13
+ lines.push("| Page | Device | Perf | A11y | Best pr. | SEO | LCP ms | TBT ms | CLS | JS KB | Total KB | Report |");
14
+ lines.push("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |");
15
+ for (const l of r.lighthouse) {
16
+ const s = l.scores;
17
+ const m = l.metrics;
18
+ lines.push(`| ${new URL(l.url).pathname} | ${l.formFactor} | ${s.performance ?? "-"} | ${s.accessibility ?? "-"} | ${s["best-practices"] ?? "-"} | ${s.seo ?? "-"} | ${Math.round(m.lcpMs ?? 0)} | ${Math.round(m.tbtMs ?? 0)} | ${(m.cls ?? 0).toFixed(3)} | ${Math.round((l.scriptBytes ?? 0) / 1024)} | ${Math.round((l.totalBytes ?? 0) / 1024)} | [html](${l.reportFile}) |`);
19
+ }
20
+ lines.push("");
21
+ }
22
+ const real = r.crux?.home ?? r.crux?.origin;
23
+ if (real) {
24
+ lines.push("## Real visitors (Chrome UX Report, phones, p75)", "");
25
+ lines.push(`${real.scope} ${real.key}, ${real.period}: LCP ${real.lcpMs ?? "-"} ms, INP ${real.inpMs ?? "-"} ms, CLS ${real.cls ?? "-"}, TTFB ${real.ttfbMs ?? "-"} ms`, "");
26
+ }
27
+ if (r.reviews?.length) {
28
+ lines.push("## Google reviews", "");
29
+ lines.push("| Listing | Rating | Reviews | Last 3 months | Last 12 months | Answered |");
30
+ lines.push("| --- | --- | --- | --- | --- | --- |");
31
+ for (const v of r.reviews)
32
+ lines.push(`| ${v.name} | ${v.rating} | ${v.count} | ${v.last3Months} | ${v.last12Months} | ${v.replied ?? "?"} |`);
33
+ lines.push("");
34
+ }
35
+ lines.push("## Findings", "");
36
+ for (const sev of ORDER) {
37
+ const items = r.findings.filter((f) => f.severity === sev);
38
+ if (!items.length)
39
+ continue;
40
+ lines.push(`### ${sev.toUpperCase()}`, "");
41
+ for (const f of items) {
42
+ lines.push(`- **[${f.area}] ${f.title}**: ${f.evidence}`);
43
+ if (f.pages?.length && f.pages.length <= 5)
44
+ for (const p of f.pages)
45
+ lines.push(` - ${p}`);
46
+ }
47
+ lines.push("");
48
+ }
49
+ lines.push("## Site", "");
50
+ lines.push(`- HTTPS redirect: ${r.site.https ? "yes" : "no"}`);
51
+ lines.push(`- robots.txt: ${r.site.robotsTxt === null ? "missing" : "present"}`);
52
+ for (const s of r.site.sitemaps)
53
+ lines.push(`- Sitemap ${s.url}: ${s.urls} URLs, newest lastmod ${s.newestLastmod ?? "none"}`);
54
+ lines.push(`- AI crawlers: ${Object.entries(r.site.aiBots)
55
+ .map(([b, v]) => `${b} ${v}`)
56
+ .join(", ")}`);
57
+ lines.push("");
58
+ return lines.join("\n");
59
+ }