diff --git a/PRODUCT.md b/PRODUCT.md index e781e02..72cda2d 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -41,7 +41,7 @@ Chrome 116+, side panel next to the page, DevTools open on the side, localhost / ## Evidence on Hand - Real screenshots of the extension on Wikipedia and on a local test page (JSON-LD analyzer, headers grade, AI answer, popup palette, options). -- Verified runs: 298 unit tests, 124 end-to-end checks in Chromium, a real Anthropic analysis of Wikipedia's JSON-LD (≈4k tokens in, 4.5k out, $0.053). +- Verified runs: 859 unit tests, 322 end-to-end checks in Chromium, a real Anthropic analysis of Wikipedia's JSON-LD (≈4k tokens in, 4.5k out, $0.053). - No users, testimonials, download counts or store ratings exist: never invent them. ## Product Principles diff --git a/README.md b/README.md index db6dc58..4c607c4 100644 --- a/README.md +++ b/README.md @@ -42,16 +42,21 @@ Chrome 116 or later. | Tab | Tools | |---|---| -| Cache | **Storage usage**: how much the site keeps on the device (quota, usage by kind, persistent or best-effort), IndexedDB databases with their stores and record counts, Cache Storage caches with entries and sizes, OPFS files, the largest localStorage keys, cookies, service workers, a Markdown report · Hard reload · clear this site's cache · fresh start (all site data + reload) · clear cookies · clear local/session storage · unregister service workers · no-cache mode per tab · site data checklist · cookie editor (edit, import/export JSON, flag audit: Secure, HttpOnly on session cookies, SameSite, expiry, size) · Web Storage editor | -| Inspect | Tech stack (frameworks, CMS, analytics, CDN, server) and DOM stats · SEO & meta (checks, social card preview, headings summary, meta, head links) · **Headings outline**: every h1–h6 and `role="heading"` as a tree, with what a screen reader gets (visually hidden, `aria-hidden`, hidden) and the problems (no h1 or several, headings before the h1, skipped levels shown as gaps, empty or overlong headings, `role="heading"` without `aria-level`, duplicates, empty sections), click a heading to find it in the page, level badges drawn on the page, a page map of where the headings fall and how many words each section holds, a table of contents to copy as Markdown or HTML (ids proposed where missing), Copy for agent and AI help (review the outline, rewrite the headings, check them against their sections, find missing sections, or ask about one heading) · **Structured data**: every JSON-LD block parsed and checked against schema.org and Google rich results (required / recommended properties, ISO dates, absolute URLs, prices, currencies, `@id` references, breadcrumb positions, JSON syntax errors with line and column), tree and source views, snippet validator, Rich Results Test / Schema validator links · a **page report** at the top of Overview (security grade, SEO, headings, JSON-LD, errors, accessibility, Web Vitals, each opening its panel) · Performance (Web Vitals on their good / poor scales, navigation timeline, bytes by type, request waterfall, long tasks) · **Responsiveness** (why it is slow): record while you use the page, then the slowest interactions split into input delay / handlers / paint against INP's thresholds, the scripts that ran in each (Long Animation Frames: function, file, character offset turned into line:column, invoker, forced layout), script time per file, suggestions labeled as heuristics and a copy as Markdown for a coding agent; back/forward cache test with Chrome's not-restored reasons explained; speculation rules (inline and `Speculation-Rules` header) and whether the page was prerendered or prefetched · Console errors (captured from the first script on every page, count on the toolbar badge) · Link checker · Fonts & colors (eyedropper, palette, contrast) · **Accessibility audit** with [axe-core](https://github.com/dequelabs/axe-core) (WCAG 2.0/2.1/2.2 A and AA, optional best practices and AAA, whole page or one region): violations by impact, needs-review items, each failing element outlined in the page on click, WCAG criteria and Deque's fix guide, Copy for agent / Ask AI · robots.txt tester, sitemap browser, PWA manifest checks · Open in PageSpeed, W3C validator, SSL Labs, securityheaders, Wayback… | -| Security | Headers & security (grade, CSP/HSTS/framing/…, caching, raw headers) · **Secrets scanner**: API keys, tokens and private keys shipped to the browser (inline scripts and JSON blobs, this origin's scripts, HTML comments, meta tags, config globals, Web Storage, readable cookies), masked until revealed, with where each was found; public-by-design keys (Stripe publishable, Firebase config, Supabase anon) shown as such · **Source maps & exposed files**: reachable source maps, and an opt-in probe for `.git`, `.env`, `.DS_Store`, `phpinfo.php`, `security.txt`… checked by content against a random-path baseline · **Third parties & SRI**: requests and bytes per site, cross-origin scripts and stylesheets without `integrity`, `crossorigin` mismatches, mixed content, iframes without `sandbox` · **Vulnerable libraries**: jQuery, jQuery UI, AngularJS, Angular, Bootstrap, Vue, React, Lodash, Moment, Handlebars, DOMPurify… found by their version globals, script URLs and file names (CDN paths included) and the banners of the site's own scripts, matched against a bundled [Retire.js](https://github.com/RetireJS/retire.js) database: advisories with severity, CVE / GHSA links and fixed-in version, the first clean release to upgrade to, end-of-life notes (AngularJS 1.x, Vue 2, jQuery 1–2, Bootstrap 3), Copy for agent; detection by version only · **CSP analyzer**: directive by directive (unsafe-inline, unsafe-eval, wildcards, `strict-dynamic`, missing `object-src`/`base-uri`/`frame-ancestors`, report-only) and a starter policy from the origins the page used | +| Cache | **Storage usage**: how much the site keeps on the device (quota, usage by kind, persistent or best-effort), IndexedDB databases with their stores and record counts, Cache Storage caches with entries and sizes, OPFS files, the largest localStorage keys, cookies, service workers, a Markdown report · Hard reload · clear this site's cache · fresh start (all site data + reload) · clear cookies · clear local/session storage · unregister service workers · no-cache mode per tab · site data checklist · cookie editor (edit, add, delete, flag audit: Secure, HttpOnly on session cookies, SameSite, expiry, size) · **cookies.txt export** like "Get cookies.txt LOCALLY": this site's cookies as Netscape cookies.txt for curl, wget and yt-dlp (`#HttpOnly_` lines, session cookies at expiry 0), JSON or a `Cookie` header string, to copy, download or save where you pick; export all cookies of every site (asks for all-sites access, since Chrome only lists cookies of sites devkit can reach); a table view of the cookies.txt fields with a nowrap toggle; partitioned (CHIPS) cookies included and marked; import JSON or cookies.txt; "Copy cookies.txt" in the palette · Web Storage editor · **IndexedDB**: databases, object stores (key path, autoIncrement, indexes with unique / multiEntry, record counts) and records page by page, through the primary key or an index, filtered by an exact key or a text prefix; a record as a tree, edited as JSON with Date, Map, Set, BigInt, Blob, typed arrays… kept as `$type` tags and written back as they were, add, delete, clear a store, delete a database (confirmed in the panel), export a store as JSON · **Cache Storage**: service worker caches and their requests with status, content type and size, an entry's headers and body (JSON as a tree, text, image preview; opaque responses marked), delete an entry or a cache, export a cache as JSON | +| Inspect | Tech stack (frameworks, CMS, analytics, CDN, server) and DOM stats · **SEO & meta**: a counters strip (issues, words, headings, images with missing alt, internal · external links), the issues (share of images without alt, title and description too short or long with their length, Open Graph tags still worth adding, hreflang problems), PageSpeed / W3C links, Copy report and Copy for agent; meta lengths against their limits (title 60, description 160, og:title 88, og:description 200); the Open Graph / Twitter checklist (essential and recommended tags, Twitter tags covered by Open Graph shown as fallbacks) and its mistakes (og:url not the canonical, relative or http:// og:image, `name="og:…"` instead of `property=`, unknown `twitter:card`); share previews for Facebook, LinkedIn, X, WhatsApp and Slack with each network's layout, image ratio and approximate truncation, the image requested only after **Load preview image**, then checked on the measured file (below 1200×630, below 200 px, odd ratio, `og:image:width` / `height` that do not match); an hreflang table with BCP-47 checks (`de_AT`, `en-UK`, a country code used as a language), self-reference, x-default, duplicates, conflicting targets and relative URLs; images and links (total, missing alt, without title, internal, external, unique, nofollow); indexability (meta robots and `X-Robots-Tag`, robots.txt for Googlebot, HTTP status); a searchable headings list and the meta and head links · **Headings & landmarks**: every h1–h6 and `role="heading"` as a tree, with what a screen reader gets (visually hidden, `aria-hidden`, hidden) and the problems (no h1 or several, headings before the h1, skipped levels shown as gaps, empty or overlong headings, `role="heading"` without `aria-level`, duplicates, empty sections); a **Landmarks** view of the ARIA landmarks as browsers map the HTML (banner, navigation, main, region, complementary, contentinfo, search, form), listed HeadingsMap-style as `Breadcrumbs [navigation]`, with their problems (no main or several, several top-level banners or contentinfos, same-role landmarks without distinct names, hidden landmarks, redundant `role`, headings outside every landmark), and an All view with each landmark's headings nested under it, Expand all / Collapse all; click a heading or landmark to find it in the page, level or landmark badges drawn on the page, a page map of where the headings fall and how many words each section holds, a table of contents to copy as Markdown or HTML (ids proposed where missing), Copy for agent and AI help (review the outline, rewrite the headings, check them against their sections, find missing sections, or ask about one heading) · **Structured data**: page URL, canonical, robots meta and `X-Robots-Tag` at a glance; every JSON-LD block (`@graph`, arrays, nested nodes) parsed and validated in two modes, Rich Results (Google's required / recommended properties) or Schema.org (the vocabulary, checked locally: unknown types and properties with "Did you mean…?", properties on the wrong type, nested values of the wrong type, invalid enumeration values such as `InStok`, superseded terms such as `serviceArea` → `areaServed`), plus value formats in both (ISO 8601 dates and durations with the fix, prices with a comma or currency sign, `priceCurrency` not ISO 4217, relative URLs or URLs with spaces, `@id` references, breadcrumb positions, JSON syntax errors with line and column); a Valid / Warning / Error badge per block (Experimental for pending Schema.org terms, Not supported for types Google dropped from rich results), identical findings grouped as ×N, search with highlighted matches, code or tree view (blocks open on the one you pick, findings folded below), Copy JSON, Copy ` + + diff --git a/src/entrypoints/print/main.tsx b/src/entrypoints/print/main.tsx new file mode 100644 index 0000000..9d27af9 --- /dev/null +++ b/src/entrypoints/print/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import "../../ui/styles.css"; +import { PrintApp } from "../../ui/Print"; + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/src/entrypoints/redirect-probe.content.ts b/src/entrypoints/redirect-probe.content.ts new file mode 100644 index 0000000..9a244d8 --- /dev/null +++ b/src/entrypoints/redirect-probe.content.ts @@ -0,0 +1,46 @@ +import { browser } from "wxt/browser"; +import { META_REFRESH_SEEN } from "../lib/redirects"; + +/** + * Tells the background whether the page has a ``, so the Redirect path panel can name a + * client redirect (meta refresh or JavaScript). Registered at runtime by the background once the user grants + * webRequest, webNavigation and site access; read-only. It runs at document_start and reports the tag as soon as + * the parser inserts it: a refresh with no delay can replace the page before an injected script would run. + */ +export default defineContentScript({ + matches: [""], + runAt: "document_start", + registration: "runtime", + main() { + let sent = false; + const send = (content: string | null) => { + if (sent) return; + sent = true; + observer.disconnect(); + browser.runtime.sendMessage({ type: META_REFRESH_SEEN, content }).catch(() => undefined); + }; + const check = (el: Element) => { + if (el.tagName !== "META" || (el.getAttribute("http-equiv") ?? "").trim().toLowerCase() !== "refresh") return; + const content = el.getAttribute("content"); + if (content !== null && !el.closest("noscript")) send(content); + }; + // Only the nodes the parser adds, and only until starts: the tag belongs in . + const observer = new MutationObserver((records) => { + for (const r of records) + for (const node of Array.from(r.addedNodes)) { + if (!(node instanceof Element)) continue; + if (node.tagName === "BODY") observer.disconnect(); + check(node); + } + }); + observer.observe(document, { childList: true, subtree: true }); + document.addEventListener( + "DOMContentLoaded", + () => { + for (const el of Array.from(document.querySelectorAll("meta[http-equiv]"))) check(el); + send(null); + }, + { once: true }, + ); + }, +}); diff --git a/src/entrypoints/repo-deps.content.ts b/src/entrypoints/repo-deps.content.ts new file mode 100644 index 0000000..4c1f245 --- /dev/null +++ b/src/entrypoints/repo-deps.content.ts @@ -0,0 +1,78 @@ +import { browser } from "wxt/browser"; +import { fetchRepoFiles, readRepoPage } from "../lib/page/repo-files"; +import { loadRepoDeps, type PackageInfo } from "../lib/repo-deps"; +import type { PackageInfoMessage } from "../lib/repo-deps-info"; +import { BOX_TAG, boxAnchor, fillDepsBox, renderDepsBox } from "../lib/repo-deps-view"; + +/** + * The opt-in Dependencies box on github.com and gitlab.com, registered at runtime from Options or the Repo + * dependencies panel once the user grants access to those two sites. Both sites navigate in-app, so it follows URL + * changes, and puts its box back when the page re-renders over it. + */ +export default defineContentScript({ + matches: ["https://github.com/*", "https://gitlab.com/*"], + registration: "runtime", + runAt: "document_idle", + main() { + let shown: { key: string; box: HTMLElement | null } | null = null; + let loading: string | null = null; + + const place = (box: HTMLElement, host: "github" | "gitlab") => { + const anchor = boxAnchor(host); + if (!anchor) return false; + if (anchor.nextElementSibling !== box) anchor.after(box); + return true; + }; + + const update = async () => { + const url = location.href.split("#")[0]!; + // Folder pages only: a file page shows that file. + const isFolder = !/\/(?:-\/)?blob\//.test(location.pathname); + if (shown?.key !== url) { + for (const old of document.querySelectorAll(BOX_TAG)) old.remove(); + shown = null; + } + if (!isFolder) return; + if (shown) { + // Same page, re-rendered: put the box back if the page dropped it, or below the README once it shows up. + if (shown.box) place(shown.box, shown.box.dataset.host === "gitlab" ? "gitlab" : "github"); + return; + } + if (loading === url) return; + loading = url; + try { + const result = await loadRepoDeps(url, readRepoPage(), fetchRepoFiles); + if (location.href.split("#")[0] !== url) return; + const useful = result?.manifests.some((m) => m.deps.length || m.workspaces.length); + if (!result || !useful) { + shown = { key: url, box: null }; + return; + } + const box = renderDepsBox(result); + box.dataset.host = result.loc.host; + shown = { key: url, box }; + place(box, result.loc.host); + const deps = result.manifests.flatMap((m) => m.deps).map(({ name, ecosystem, source }) => ({ name, ecosystem, source })); + const message: PackageInfoMessage = { type: "devkit:package-info", deps }; + const info = (await browser.runtime.sendMessage(message).catch(() => null)) as Record | null; + if (info) fillDepsBox(box, info); + } finally { + if (loading === url) loading = null; + } + }; + + let timer: number | null = null; + const schedule = () => { + if (timer !== null) return; + timer = window.setTimeout(() => { + timer = null; + update(); + }, 300); + }; + // The root, not the body: Turbo swaps the whole body on navigation. + new MutationObserver(schedule).observe(document.documentElement, { childList: true, subtree: true }); + document.addEventListener("turbo:load", schedule); + window.addEventListener("popstate", schedule); + update(); + }, +}); diff --git a/src/lib/actions.ts b/src/lib/actions.ts index ba69c3d..d6131ee 100644 --- a/src/lib/actions.ts +++ b/src/lib/actions.ts @@ -1,6 +1,11 @@ import { browser } from "wxt/browser"; import { quickReport } from "./bug-report-gather"; +import { readCookies } from "./cookie-jar"; +import { toNetscape } from "./cookies-export"; import { runInTab } from "./inject"; +import { DATA_VIEWER_FILE, dataViewerMessage } from "./data-viewer"; +import { JSON_VIEWER_HOST_ID } from "./json-viewer"; +import { forceJsonViewer, jsonViewerState } from "./page/json-viewer"; import { PENDING_ROUTE_KEY } from "./panels"; import { clearWebStorage, toggleCss, toggleDesignMode, toggleOutline, unregisterServiceWorkers } from "./page/toggles"; import { ALL_SITES, type PermissionNeed } from "./permissions"; @@ -46,7 +51,8 @@ export interface ActionDef { run: (ctx: ActionContext) => Promise; } -const ALL_DATA = { +/** Every kind of site data "Fresh start" removes (the Consent check clears the same). */ +export const ALL_DATA = { cache: true, cacheStorage: true, cookies: true, @@ -123,6 +129,25 @@ export const ACTIONS: ActionDef[] = [ return { message: `Cookies cleared for ${origin}.` }; }, }, + { + id: "copy-cookies-txt", + title: "Copy cookies.txt", + description: "This site's cookies in Netscape format, for curl, wget or yt-dlp", + category: "cache", + keywords: "cookies.txt netscape curl yt-dlp wget export cookie jar", + needsPage: true, + // Chrome only lists the cookies of hosts devkit can access: ask for this site like the cookie editor. + scripts: true, + needs: () => ({ permissions: ["cookies"] }), + run: async ({ url }) => { + const cookies = await readCookies({ url }); + if (!cookies.length) return { message: "No cookie for this page." }; + return { + message: `cookies.txt copied (${cookies.length} cookie${cookies.length > 1 ? "s" : ""}). It holds session tokens: keep it private.`, + copy: toNetscape(cookies), + }; + }, + }, { id: "clear-storage", title: "Clear local & session storage", @@ -270,6 +295,24 @@ export const ACTIONS: ActionDef[] = [ return { message: "Hover the page to measure (Esc exits)." }; }, }, + { + id: "format-json", + // The id keeps its JSON name: the action now formats every data format. + title: "Format this data page", + description: + "JSON, XML / RSS / Atom, CSV / TSV, YAML or JSON Lines in this tab: collapsible tree or sortable table, filter, copy and download", + category: "utils", + keywords: + "json formatter pretty viewer beautify api response tree xml rss atom feed csv tsv table yaml yml jsonl ndjson json lines data", + needsPage: true, + // No `scripts`: the palette's activeTab grant is enough, no site access is asked. + run: async ({ tabId }) => { + await runInTab(tabId, forceJsonViewer); + await browser.scripting.executeScript({ target: { tabId }, files: [`/${DATA_VIEWER_FILE}` as const] }); + const { state, format, contentType } = await runInTab(tabId, jsonViewerState, [JSON_VIEWER_HOST_ID]); + return { message: dataViewerMessage(state, format, contentType) }; + }, + }, { id: "copy-markdown-link", title: "Copy as Markdown link", diff --git a/src/lib/agent-files.ts b/src/lib/agent-files.ts new file mode 100644 index 0000000..33b632f --- /dev/null +++ b/src/lib/agent-files.ts @@ -0,0 +1,62 @@ +// The agent and crawler files of a page's origin (robots.txt, llms.txt, llms-full.txt, ai.txt, the sitemap), read +// for the Agent readiness panel, the AI context and the Overview. Plain fetches from the extension, no cookies. +import { type AiTxt, type CrawlerAccess, crawlerAccess, type LlmsTxt, parseAiTxt, parseLlmsTxt } from "./readiness"; +import { parseRobots, type Robots } from "./site-files"; + +export interface AgentFiles { + robotsStatus: number; + robots: Robots | null; + crawlers: CrawlerAccess[]; + /** The page's path, the one the crawler rules are checked against. */ + path: string; + llms: LlmsTxt; + llmsFull: LlmsTxt; + aiTxt: AiTxt; + sitemap: { url: string; found: boolean }; +} + +async function fetchText(url: string): Promise<{ status: number; text: string; type: string }> { + try { + const res = await fetch(url, { credentials: "omit", cache: "no-store" }); + return { status: res.status, text: await res.text(), type: res.headers.get("content-type") ?? "" }; + } catch { + return { status: 0, text: "", type: "" }; + } +} + +/** /llms.txt alone: the only agent file the readiness score counts (the others only add recommendations). */ +export async function fetchLlmsTxt(origin: string): Promise { + const r = await fetchText(`${origin}/llms.txt`); + return parseLlmsTxt(`${origin}/llms.txt`, r.status, r.type, r.text); +} + +/** robots.txt, llms.txt, llms-full.txt, ai.txt and the sitemap of `origin`; crawler rules checked for `url`'s path. */ +export async function fetchAgentFiles(origin: string, url: string): Promise { + const [robots, llms, llmsFull, ai] = await Promise.all( + ["/robots.txt", "/llms.txt", "/llms-full.txt", "/ai.txt"].map((p) => fetchText(`${origin}${p}`)), + ); + const parsedRobots = robots!.status > 0 && robots!.status < 400 && !/text\/html/i.test(robots!.type) ? parseRobots(robots!.text) : null; + let path = "/"; + try { + path = new URL(url).pathname || "/"; + } catch { + /* keep / */ + } + const listed = parsedRobots?.sitemaps[0]; + let sitemap: { url: string; found: boolean }; + if (listed) sitemap = { url: listed, found: true }; + else { + const s = await fetchText(`${origin}/sitemap.xml`); + sitemap = { url: `${origin}/sitemap.xml`, found: s.status > 0 && s.status < 400 && /<(urlset|sitemapindex)\b/.test(s.text) }; + } + return { + robotsStatus: robots!.status, + robots: parsedRobots, + crawlers: crawlerAccess(parsedRobots, path), + path, + llms: parseLlmsTxt(`${origin}/llms.txt`, llms!.status, llms!.type, llms!.text), + llmsFull: parseLlmsTxt(`${origin}/llms-full.txt`, llmsFull!.status, llmsFull!.type, llmsFull!.text), + aiTxt: parseAiTxt(`${origin}/ai.txt`, ai!.status, ai!.type, ai!.text), + sitemap, + }; +} diff --git a/src/lib/agent/agents.ts b/src/lib/agent/agents.ts new file mode 100644 index 0000000..a8467e6 --- /dev/null +++ b/src/lib/agent/agents.ts @@ -0,0 +1,122 @@ +// "Copy for agent" and "Copy report" Markdown of the Agent tools (WebMCP) and Agent readiness panels. Pure: each +// takes what its panel computed, in the shared shape of agent-md.ts. +import { agentDoc, code, findingList, plural } from "../agent-md"; +import type { WebMcpSnapshot } from "../page/webmcp"; +import { type CrawlerAccess, IMPACT_TEXT, type Impact, PURPOSE_TEXT, type Readiness, type ReadinessInputs } from "../readiness"; +import { RISK_TEXT, type ToolAnalysis } from "../webmcp"; + +export interface AgentsCtx { + url: string; + heading?: "##" | "###"; +} + +const DISCLAIMER = "This score is a technical orientation and not a guarantee of compatibility with any specific AI agent."; + +/** Agent tools panel: every WebMCP tool with its risk and the problems of its name, description, schema and annotations. */ +export function agentToolsMarkdown(snap: WebMcpSnapshot, tools: ToolAnalysis[], ctx: AgentsCtx): string { + const apis = [ + snap.apis.document.present ? "document.modelContext" : "", + snap.apis.navigator.present ? "navigator.modelContext" : "", + snap.apis.testing.present ? "navigator.modelContextTesting" : "", + ].filter(Boolean); + const problems = tools.flatMap((t) => t.findings.filter((f) => f.level === "bad").map((f) => ({ t, f }))); + const warnings = tools.flatMap((t) => t.findings.filter((f) => f.level === "warn").map((f) => ({ t, f }))); + const result = !tools.length + ? "No WebMCP tool found on this page." + : `${plural(tools.length, "tool")}; ${problems.length || warnings.length ? [problems.length ? plural(problems.length, "problem") : "", warnings.length ? plural(warnings.length, "warning") : ""].filter(Boolean).join(", ") : "no problem found"}.`; + const inventory = tools.map( + (t) => + `- ${code(t.tool.name || "(unnamed)")}: ${RISK_TEXT[t.risk]} risk (${t.riskReasons.join("; ")}). Source: ${t.tool.sources.join(", ")}${t.tool.form ? `, form ${code(t.tool.form.selector)}` : ""}.`, + ); + const item = ({ t, f }: { t: ToolAnalysis; f: { area: string; message: string } }) => ({ + text: `${code(t.tool.name || "(unnamed)")} (${f.area}): ${f.message}`, + details: [t.tool.form ? `Where: the form ${code(t.tool.form.selector)}` : "Where: the registerTool() call that defines it"], + }); + return agentDoc({ + title: "Agent tools (devkit panel: Inspect › Agent tools)", + url: ctx.url, + result, + context: [ + `WebMCP APIs on the page: ${apis.length ? apis.join(", ") : "none (experimental: Chrome origin trial or chrome://flags/#enable-webmcp-testing)"}.`, + "Risk classes come from the tool names, descriptions and annotations: a heuristic.", + ], + heading: ctx.heading, + sections: [ + { title: "Tools", body: inventory }, + { title: "To fix", body: findingList(problems.map(item)) }, + { title: "Worth checking", body: findingList(warnings.map(item)) }, + ], + verify: "Reload the page and refresh devkit's Agent tools panel.", + }); +} + +const crawlerLine = (c: CrawlerAccess) => + `- ${c.agent} (${c.operator}, ${PURPOSE_TEXT[c.purpose]}): ${c.root.allowed ? "allowed" : "blocked"} on /${c.root.rule ? ` by ${code(c.root.rule)}` : ""}${c.page.allowed !== c.root.allowed ? `, ${c.page.allowed ? "allowed" : "blocked"} on this page` : ""}`; + +/** One line per agent file checked (llms.txt, llms-full.txt, ai.txt, sitemap); files not checked are left out. */ +export function filesLines(inputs: ReadinessInputs): string[] { + const out: string[] = []; + const llms = inputs.llms; + if (llms !== undefined) + out.push( + llms?.present + ? `- llms.txt: present (${llms.bytes} bytes${llms.title ? `, "${llms.title}"` : ""}, ${plural(llms.links, "link")})` + : "- llms.txt: none", + ); + if (inputs.llmsFull !== undefined) + out.push(`- llms-full.txt: ${inputs.llmsFull?.present ? `present (${inputs.llmsFull.bytes} bytes)` : "none"}`); + if (inputs.aiTxt !== undefined) + out.push( + `- ai.txt: ${inputs.aiTxt?.present ? (inputs.aiTxt.optOutAll ? "opts the whole site out of AI training" : inputs.aiTxt.optOutPartial ? "opts some files out of AI training" : "present, allows AI training") : "none"}`, + ); + if (inputs.sitemap !== undefined) out.push(`- Sitemap: ${inputs.sitemap?.found ? inputs.sitemap.url : "not found"}`); + return out; +} + +/** "Copy report": the score, the breakdown, the files and crawlers, the recommendations. */ +export function readinessReport(r: Readiness, inputs: ReadinessInputs, ctx: AgentsCtx): string { + const crawlers = inputs.crawlers ?? []; + const blocked = crawlers.filter((c) => !c.root.allowed); + const byImpact = (impact: Impact) => r.recommendations.filter((x) => x.impact === impact).map((x) => `- ${x.text}`); + return [ + `# Agent readiness: ${r.total}/100`, + `Page: ${ctx.url}`, + DISCLAIMER, + "", + "## Breakdown", + ...r.areas.map((a) => `- ${a.label}: ${a.score}/${a.max}`), + "", + "## Agent files", + ...filesLines(inputs), + ...(crawlers.length + ? [ + "", + `## AI crawlers (robots.txt): ${crawlers.length - blocked.length} allowed · ${blocked.length} blocked`, + ...crawlers.map(crawlerLine), + ] + : []), + ...(["high", "medium", "low"] as Impact[]).flatMap((i) => { + const lines = byImpact(i); + return lines.length ? ["", `## ${IMPACT_TEXT[i]}`, ...lines] : []; + }), + ].join("\n"); +} + +/** "Copy for agent": what to change in the site to raise the score, most impact first. */ +export function readinessMarkdown(r: Readiness, inputs: ReadinessInputs, ctx: AgentsCtx): string { + const fixes = r.recommendations.filter((x) => x.impact !== "low" && !/may be intentional/.test(x.text)); + const later = r.recommendations.filter((x) => x.impact === "low" || /may be intentional/.test(x.text)); + return agentDoc({ + title: "Agent readiness (devkit panel: Inspect › Agent readiness)", + url: ctx.url, + result: `${r.total}/100 (${r.areas.map((a) => `${a.label} ${a.score}/${a.max}`).join(", ")}).`, + context: [DISCLAIMER, "The score is a heuristic computed locally by devkit; every rule is listed in the panel."], + heading: ctx.heading, + sections: [ + { title: "To fix", body: findingList(fixes.map((x) => ({ text: `${IMPACT_TEXT[x.impact]}: ${x.text}` }))) }, + { title: "Worth checking", body: findingList(later.map((x) => ({ text: x.text }))) }, + { title: "Agent files", body: filesLines(inputs) }, + ], + verify: "Deploy, reload the page and refresh devkit's Agent readiness panel.", + }); +} diff --git a/src/lib/agent/consent.ts b/src/lib/agent/consent.ts new file mode 100644 index 0000000..3fffa10 --- /dev/null +++ b/src/lib/agent/consent.ts @@ -0,0 +1,188 @@ +// "Copy for agent" and JSON export of the Consent check. Names only: cookie and storage values are never +// captured, request URLs keep their host, path and a few known parameters (gcs, tid…), not identifiers. +import { agentDoc, bySeverity, code, plural } from "../agent-md"; +import { + CATEGORY_LABEL, + CHOICE_LABEL, + type ConsentAnalysis, + type ConsentComparison, + type ConsentFinding, + isTracking, + trackingHits, +} from "../consent"; + +const FIX: Record = { + "ads-cookies": "Load the tag that sets them only after Accept (CMP blocking, or GTM triggers on the consent event).", + "analytics-cookies": + "Hold the analytics tag until consent, or run it cookieless (Consent Mode with analytics_storage denied, or an exempt configuration).", + "tracking-storage": "Write these keys only after consent; the tag that writes them should wait for the CMP.", + "ads-requests": "Block these tags until the visitor accepts: they must not load before the CMP's answer.", + "analytics-requests": "Delay them until consent, or make sure they run without identifiers while consent is denied.", + "consent-mode-missing": + "Before the GTM / gtag snippet: `gtag('consent', 'default', { ad_storage: 'denied', analytics_storage: 'denied', ad_user_data: 'denied', ad_personalization: 'denied', wait_for_update: 500 })`.", + "consent-default-granted": "Set these signals to 'denied' in the default; the CMP sends 'granted' in an update after Accept.", + "consent-update-before": "Make the CMP send gtag('consent', 'update', …) only from the visitor's choice (or a stored earlier choice).", + "no-cmp": "Add a consent banner (CMP) if the site sets non-essential cookies, or confirm the custom banner blocks them.", + "tcf-tracking-before-string": + "Make the ad tags wait for the TC string (`__tcfapi('addEventListener', 2, …)` with tcloaded / useractioncomplete).", + "reject-tracking-storage": "After Reject, the tags that set these must not run: check the CMP's blocking rules.", + "reject-tracking-requests": "Map these tags to their consent purpose so Reject blocks them.", + "reject-granted": "Send `gtag('consent', 'update', { …: 'denied' })` on Reject.", + "accept-no-update": "On Accept, send `gtag('consent', 'update', { ad_storage: 'granted', … })` for the purposes accepted.", +}; + +const findingItem = (f: ConsentFinding): string => + [ + `- **${f.label}**: ${f.detail}`, + ...(f.items ?? []).slice(0, 25).map((i) => ` - ${code(i)}`), + (f.items?.length ?? 0) > 25 ? ` - … and ${f.items!.length - 25} more` : "", + FIX[f.id] ? ` - Fix: ${FIX[f.id]}` : "", + ] + .filter(Boolean) + .join("\n"); + +const PHASE_TEXT = { + before: "after devkit cleared the site's cookies and storage and reloaded, before any interaction", + current: "current state, without clearing (may already include an earlier choice)", + after: "after a choice in the banner", +} as const; + +function trackerLines(a: ConsentAnalysis): string[] { + const cookies = a.cookies + .filter((c) => !c.preexisting && c.category !== "unknown") + .map( + (c) => + `- cookie ${code(c.name)}: ${CATEGORY_LABEL[c.category]}${c.vendor ? `, ${c.vendor}` : ""}, ${c.firstParty ? "first party" : `third party (${c.domain.replace(/^\./, "")})`}${c.partitioned ? ", partitioned" : ""}`, + ); + const unknownCookies = a.cookies.filter((c) => !c.preexisting && c.category === "unknown"); + const keys = a.storage + .filter((k) => k.category !== "unknown") + .map((k) => `- ${k.area}Storage ${code(k.key)}: ${CATEGORY_LABEL[k.category]}${k.vendor ? `, ${k.vendor}` : ""}`); + const requests = a.requests + .filter((g) => !g.firstParty || g.category !== "unknown") + .slice(0, 40) + .map( + (g) => + `- ${code(g.host)}: ${CATEGORY_LABEL[g.category]}${g.vendor ? `, ${g.vendor}` : ""}, ${plural(g.count, "request")}${g.deniedPings ? ` (${g.deniedPings} with consent denied)` : ""}${g.loader ? ", tag loader" : ""}`, + ); + return [ + ...cookies, + unknownCookies.length ? `- other cookies: ${unknownCookies.map((c) => code(c.name)).join(", ")}` : "", + ...keys, + ...requests, + ]; +} + +function consentModeLines(a: ConsentAnalysis): string[] { + const cm = a.consentMode; + if (!cm.present) return [a.googleTags ? "- No gtag('consent', …) command in the dataLayer." : ""]; + return cm.signals + .filter((s) => s.default !== undefined || s.update !== undefined) + .map((s) => `- ${code(s.signal)}: default ${s.default ?? "not set"}${s.update ? `, update ${s.update}` : ""}`); +} + +function comparisonLines(c: ConsentComparison): string[] { + return [ + `Capture ${CHOICE_LABEL[c.choice]} (${new Date(c.after.capture.at).toISOString()}):`, + ...bySeverity(c.findings).map(findingItem), + c.cookiesAdded.length ? `- Cookies added: ${c.cookiesAdded.map((k) => code(k.name)).join(", ")}` : "- No cookie added.", + c.storageAdded.length ? `- Storage keys added: ${c.storageAdded.map((k) => code(k.key)).join(", ")}` : "", + c.requestsAdded.length ? `- Hosts added: ${c.requestsAdded.map((g) => code(g.host)).join(", ")}` : "", + ...c.signals.map((s) => `- Consent Mode ${code(s.signal)}: ${s.before} → ${s.after}`), + ]; +} + +/** Markdown for a coding agent: the findings first, then what was seen, then the before / after comparisons. */ +export function consentMarkdown(a: ConsentAnalysis, comparisons: ConsentComparison[] = [], ctx: { heading?: "##" | "###" } = {}): string { + const findings = bySeverity(a.findings); + const bad = findings.filter((f) => f.level === "bad"); + const warn = findings.filter((f) => f.level === "warn"); + const notes = findings.filter((f) => f.level === "info" || f.level === "good"); + const result = bad.length + ? `${plural(bad.length, "problem")}${warn.length ? ` and ${plural(warn.length, "warning")}` : ""} with consent.` + : warn.length + ? `${plural(warn.length, "warning")} with consent.` + : "No problem found (heuristic)."; + return agentDoc({ + title: "Consent check (GDPR / ePrivacy)", + url: a.capture.url, + heading: ctx.heading, + result, + context: [ + `Captured ${PHASE_TEXT[a.capture.phase]}.`, + `Heuristic: cookies, storage keys and hosts are matched against devkit's list of common trackers by name and domain. Cookie and storage values are never read into the report.`, + a.cmps.length ? `Consent banner: ${a.cmps.map((c) => c.name).join(", ")}.` : "", + ], + sections: [ + { title: "To fix", body: bad.map(findingItem) }, + { title: "Worth checking", body: warn.map(findingItem) }, + { title: "Notes", body: notes.map(findingItem) }, + { title: "Consent Mode", body: consentModeLines(a) }, + { title: "Seen on the page", body: trackerLines(a) }, + ...comparisons.map((c, i) => ({ title: `Comparison ${i + 1}: ${CHOICE_LABEL[c.choice]}`, body: comparisonLines(c) })), + ], + verify: + bad.length || warn.length + ? "Run Inspect › Consent check › Check before consent again in devkit, then accept or reject in the banner and press Capture now." + : undefined, + }); +} + +/** JSON export: every capture as recorded (names, stripped URLs), its classification and findings. */ +export function consentJson(analyses: ConsentAnalysis[], comparisons: ConsentComparison[]): string { + return JSON.stringify( + { + tool: "devkit consent check", + note: "Heuristic classification by name and domain. Cookie and storage values are never captured.", + captures: analyses.map((a) => ({ + ...a.capture, + findings: a.findings, + consentMode: a.consentMode, + cmps: a.cmps, + cookies: a.cookies.map(({ name, domain, path, partitioned, httpOnly, session, preexisting, category, vendor, firstParty }) => ({ + name, + domain, + path, + partitioned, + httpOnly, + session, + preexisting, + category, + vendor, + firstParty, + })), + storage: a.storage.map(({ area, key, category, vendor }) => ({ area, key, category, vendor })), + requests: a.requests.map(({ host, firstParty, category, vendor, count, deniedPings, types, paths, gcs, loader }) => ({ + host, + firstParty, + category, + vendor, + count, + trackingHits: isTracking({ category, vendor, loader }) ? count - deniedPings : 0, + deniedPings, + types, + paths, + gcs, + })), + })), + comparisons: comparisons.map((c) => ({ + choice: c.choice, + before: c.before.capture.id, + after: c.after.capture.id, + cookiesAdded: c.cookiesAdded.map((k) => ({ name: k.name, domain: k.domain, category: k.category, vendor: k.vendor })), + cookiesRemoved: c.cookiesRemoved.map((k) => ({ name: k.name, domain: k.domain })), + storageAdded: c.storageAdded.map((k) => ({ area: k.area, key: k.key, category: k.category })), + requestsAdded: c.requestsAdded.map((g) => ({ + host: g.host, + category: g.category, + vendor: g.vendor, + trackingHits: trackingHits(g), + })), + signals: c.signals, + findings: c.findings, + })), + }, + null, + 2, + ); +} diff --git a/src/lib/agent/crawl.ts b/src/lib/agent/crawl.ts new file mode 100644 index 0000000..41a6319 --- /dev/null +++ b/src/lib/agent/crawl.ts @@ -0,0 +1,79 @@ +// "Copy for agent" report of the Site crawl panel: the findings across the crawled pages, each with the pages +// concerned (paths on the crawled site), the fix, and how to check it. Pure: takes what the panel crawled. +import { agentDoc, clip, code, findingList, plural } from "../agent-md"; +import { type CrawlFinding, type CrawlPage, crawlFindings, crawlSummary, type SitemapRead, type SkippedUrl } from "../crawl"; +import type { ValidateMode } from "../jsonld"; +import { NO_PROBLEM } from "./inspect"; + +export interface CrawlReportData { + origin: string; + pages: CrawlPage[]; + skipped: SkippedUrl[]; + /** Planned URLs not fetched yet (the crawl was stopped). */ + pending: string[]; + mode: ValidateMode; + sitemaps: SitemapRead[]; +} + +/** A URL of the crawled site as its path, others in full. */ +const where = (url: string, origin: string) => code(url.startsWith(`${origin}/`) ? url.slice(origin.length) || "/" : url); + +function urlsLine(urls: string[], origin: string, max = 8): string { + const shown = urls.slice(0, max).map((u) => where(u, origin)); + return `${shown.join(", ")}${urls.length > max ? ` and ${plural(urls.length - max, "more page")}` : ""}`; +} + +const QUOTED = new Set(["duplicate-title", "duplicate-description", "duplicate-h1"]); + +function item(f: CrawlFinding, origin: string) { + const details = f.groups?.length + ? f.groups.slice(0, 8).map((g) => { + const value = QUOTED.has(f.id) + ? `"${clip(g.value, 120)}"` + : f.id === "canonical-elsewhere" || f.id === "redirected" + ? where(g.value, origin) + : g.value; + return `${value}${f.id === "canonical-elsewhere" ? " ← " : f.id === "redirected" ? " ← " : ": "}${urlsLine(g.urls, origin, 6)}`; + }) + : [urlsLine(f.urls, origin)]; + if (f.groups && f.groups.length > 8) details.push(`… and ${plural(f.groups.length - 8, "more group")}`); + return { text: `${f.title}: ${plural(f.urls.length, "page")}.`, details: [...details, `Fix: ${f.fix}`] }; +} + +export function crawlMarkdown(data: CrawlReportData, ctx: { heading?: "##" | "###" } = {}): string { + const findings = crawlFindings(data.pages, { mode: data.mode, skipped: data.skipped }); + const bad = findings.filter((f) => f.level === "bad"); + const warn = findings.filter((f) => f.level === "warn"); + const info = findings.filter((f) => f.level === "info"); + const s = crawlSummary(data.pages); + const sitemaps = data.sitemaps.filter((m) => m.kind === "urlset" || m.kind === "sitemapindex"); + const result = + bad.length || warn.length + ? [bad.length ? plural(bad.length, "problem") : "", warn.length ? plural(warn.length, "warning") : ""].filter(Boolean).join(", ") + + ` across ${plural(s.pages, "page")}.` + : `${NO_PROBLEM} (${plural(s.pages, "page")} crawled)`; + return agentDoc({ + title: "Site crawl", + url: data.origin, + heading: ctx.heading, + result, + context: [ + `Crawled ${plural(s.pages, "page")}: ${s.ok} answered 2xx, ${s.errors} an error, ${s.redirects} redirected, ${s.noindex} noindex, ${s.withJsonLd} with JSON-LD.`, + sitemaps.length + ? `From ${plural(sitemaps.length, "sitemap")}: ${sitemaps + .slice(0, 5) + .map((m) => code(m.url)) + .join(", ")}.` + : "", + data.pending.length ? `Stopped early: ${plural(data.pending.length, "planned URL")} not fetched.` : "", + `devkit read the served HTML of each page (no JavaScript ran), so tags a script adds after load are not seen. JSON-LD checked with the ${data.mode === "rich" ? "Rich Results" : "Schema.org"} rules.`, + ], + sections: [ + { title: "To fix", body: findingList(bad.map((f) => item(f, data.origin))) }, + { title: "Worth checking", body: findingList(warn.map((f) => item(f, data.origin))) }, + { title: "Notes", body: info.map((f) => `- ${f.title}: ${urlsLine(f.urls, data.origin, 5)}.`) }, + ], + verify: + "Deploy the fixes, then run devkit's Site crawl again (Inspect › Site crawl) and open a page in the SEO or Structured data panel for its details.", + }); +} diff --git a/src/lib/agent/crux.ts b/src/lib/agent/crux.ts new file mode 100644 index 0000000..91c293b --- /dev/null +++ b/src/lib/agent/crux.ts @@ -0,0 +1,27 @@ +// "Field data (CrUX)" lines of the Performance "Copy for agent" report, from what the CrUX section loaded. +import { type CruxResult, FORM_FACTOR_TEXT, formatPeriod } from "../crux"; +import { formatVital, msLabel, RATING_TEXT, VITALS } from "../viz"; + +const share = (f: number) => `${Math.round(f * 100)}%`; + +/** Markdown body (no heading): scope, period, then one line per vital with its p75, rating and distribution. */ +export function cruxMarkdown(result: CruxResult): string { + const { record, fellBack } = result; + const what = record.scope === "url" ? `URL ${record.target}` : `origin ${record.target}`; + const lines = [ + `75th percentile of real Chrome visits over 28 days (${FORM_FACTOR_TEXT[record.formFactor].toLowerCase()}), for the ${what}${record.period ? `, ${formatPeriod(record.period)}` : ""}.`, + ]; + if (fellBack) lines.push("The URL itself has no field data: these are the origin's."); + lines.push(""); + for (const m of record.metrics) { + const t = VITALS[m.name]; + const d = m.distribution; + lines.push( + `- ${t.label} p75 ${formatVital(m.name, m.p75)}${m.rating ? ` (${RATING_TEXT[m.rating].toLowerCase()})` : ""}${ + d ? `: ${share(d.good)} good, ${share(d.ni)} needs improvement, ${share(d.poor)} poor` : "" + }`, + ); + } + if (record.rtt !== null) lines.push(`- Round trip time p75 ${msLabel(record.rtt)}`); + return lines.join("\n"); +} diff --git a/src/lib/agent/inspect.ts b/src/lib/agent/inspect.ts index bfc3c87..574a896 100644 --- a/src/lib/agent/inspect.ts +++ b/src/lib/agent/inspect.ts @@ -4,11 +4,14 @@ import { agentDoc, clip, code, fence, plural } from "../agent-md"; import { createRedactor, type ReportError } from "../bug-report"; import { sourcePath } from "../element"; +import type { DataLayerAnalysis, DataLayerIssue } from "../datalayer"; import { cachingReport, type Check, type HeaderFetch, securityReport } from "../headers"; import { type HeadingIssue, headingIssues, headingText, isExposed, levelCounts, outlineLines } from "../headings"; import { type Finding, type JsonLdBlock, type JsonLdReport, richResultsTestUrl } from "../jsonld"; import type { FontsColors, MetaSnapshot, PerfSnapshot } from "../page/collect"; +import { isLandmarkExposed, type LandmarkIssue, landmarkFix, landmarkIssues, landmarksOutline } from "../landmarks"; import type { HeadingsSnapshot, RawHeading } from "../page/headings"; +import type { LandmarksSnapshot } from "../page/landmarks"; import { jsonLdVerdict } from "../report"; import { linkHref, metaValue, seoReport } from "../seo"; import { EXTERNAL_TOOLS, isAllowed, manifestChecks, type Robots, type Sitemap } from "../site-files"; @@ -143,12 +146,35 @@ function seoFix(c: Check, snap: MetaSnapshot): { where: string; fix: string } | } case "favicon": return { where: "``", fix: `Add ${code('')} (or a 32×32 PNG).` }; - case "hreflang": + case "hreflang-x-default": return { where: '`` in ``', fix: `Add ${code(``)} for visitors whose language matches no alternate.`, }; + case "hreflang-self": + return { + where: '`` in ``', + fix: `Add ${code(``)}: every language version lists itself too.`, + }; + case "og-name": + return { where: "``", fix: 'Write Open Graph tags as `` (property=, not name=).' }; + case "og-url-canonical": + return { where: '``', fix: `Set og:url to the canonical URL: ${code(linkHref(snap, "canonical") ?? page)}.` }; + case "images-alt": + return { + where: "the page's `` elements", + fix: 'Give each content image an `alt` describing it, and `alt=""` to decorative ones (Page › Assets lists them).', + }; default: + if (c.id.startsWith("og:image") || c.id.startsWith("twitter:image")) + return { where: "``", fix: "Use an absolute `https://` URL for the share image." }; + if (c.id === "twitter-card") + return { where: '``', fix: "Use one of `summary`, `summary_large_image`, `app` or `player`." }; + if (c.id.startsWith("hreflang")) + return { + where: '`` in ``', + fix: "Use ISO 639-1 language codes with an optional ISO 3166-1 region joined by a hyphen (`de-AT`, `en-GB`), absolute URLs, and one URL per language.", + }; return null; } } @@ -217,9 +243,54 @@ function headingFix(issue: HeadingIssue, snap: HeadingsSnapshot): string { const headingWhere = (h: RawHeading) => `${code(h.selector)}: ${code(clip(h.html, 160))}`; -/** Headings panel: the problems of `headingIssues` and the outline they sit in. */ -export function headingsMarkdown(snap: HeadingsSnapshot, ctx: AgentCtx): string { +function landmarkItem(i: LandmarkIssue, landmarks: LandmarksSnapshot | undefined): Item { + const at = i.at.map((n) => landmarks?.landmarks[n]).filter((l) => l !== undefined); + return { + text: `${i.label}: ${clip(i.detail, 240)}`, + details: [ + ...at.slice(0, 6).map((l) => `Where: ${code(l.selector)} (\`<${l.tag}>\`)`), + at.length > 6 ? `… and ${at.length - 6} more` : "", + `Fix: ${landmarkFix(i)}`, + ], + }; +} + +/** The landmarks alone (the Overview's row; the Headings panel reports them with the outline): issues and tree. */ +export function landmarksMarkdown(snap: LandmarksSnapshot, ctx: AgentCtx, headings?: RawHeading[]): string { + const issues = landmarkIssues(snap, headings); + const bad = issues.filter((i) => i.level === "bad").map((i) => landmarkItem(i, snap)); + const warn = issues.filter((i) => i.level === "warn").map((i) => landmarkItem(i, snap)); + const notes = issues.filter((i) => i.level === "info"); + const exposed = snap.landmarks.filter(isLandmarkExposed).length; + return agentDoc({ + title: "Landmarks", + url: ctx.url, + heading: ctx.heading, + result: counted(bad.length, warn.length), + context: [ + `${plural(snap.landmarks.length, "ARIA landmark")}${snap.capped ? " (capped)" : ""}, ${exposed} announced by screen readers, as browsers map them (HTML-AAM).`, + ], + sections: [ + { title: "To fix", body: list(bad) }, + { title: "Worth checking", body: list(warn) }, + { + title: "Notes", + body: list( + notes.map((i) => ({ text: `${i.label}: ${clip(i.detail, 200)}` })), + 10, + ), + }, + { title: "Tree", body: snap.landmarks.length ? fence(landmarksOutline(snap, { hidden: true, selectors: true })) : "" }, + ], + verify: + bad.length || warn.length ? "Reload the page and refresh devkit's Headings panel, Landmarks view (Inspect › Headings)." : undefined, + }); +} + +/** Headings panel: the problems of `headingIssues` (and `landmarkIssues` when given) and the outline they sit in. */ +export function headingsMarkdown(snap: HeadingsSnapshot, ctx: AgentCtx, landmarks?: LandmarksSnapshot): string { const issues = headingIssues(snap); + const lmIssues = landmarks ? landmarkIssues(landmarks, snap.headings) : []; const item = (i: HeadingIssue): Item => { const at = i.at.map((n) => snap.headings[n]).filter((h): h is RawHeading => Boolean(h)); return { @@ -231,9 +302,14 @@ export function headingsMarkdown(snap: HeadingsSnapshot, ctx: AgentCtx): string ], }; }; - const bad = issues.filter((i) => i.level === "bad"); - const warn = issues.filter((i) => i.level === "warn"); - const notes = issues.filter((i) => i.level === "info"); + const lmItem = (i: LandmarkIssue) => landmarkItem(i, landmarks); + const by = (level: HeadingIssue["level"]) => [ + ...issues.filter((i) => i.level === level).map(item), + ...lmIssues.filter((i) => i.level === level).map(lmItem), + ]; + const bad = by("bad"); + const warn = by("warn"); + const notes = [...issues, ...lmIssues].filter((i) => i.level === "info"); const exposed = snap.headings.filter(isExposed); const counts = levelCounts(exposed) .map((n, l) => (n ? `h${l + 1} ×${n}` : "")) @@ -248,10 +324,13 @@ export function headingsMarkdown(snap: HeadingsSnapshot, ctx: AgentCtx): string context: [ `${plural(snap.headings.length, "heading")}${snap.capped ? " (capped)" : ""}, ${exposed.length} announced by screen readers${counts ? ` (${counts})` : ""}.`, noId ? `${plural(noId, "visible heading")} without an \`id\`: no link can point to ${noId === 1 ? "it" : "them"}.` : "", + landmarks + ? `${plural(landmarks.landmarks.length, "ARIA landmark")}${landmarks.capped ? " (capped)" : ""}, as browsers map them (HTML-AAM).` + : "", ], sections: [ - { title: "To fix", body: list(bad.map(item)) }, - { title: "Worth checking", body: list(warn.map(item)) }, + { title: "To fix", body: list(bad) }, + { title: "Worth checking", body: list(warn) }, { title: "Notes", body: list( @@ -260,6 +339,10 @@ export function headingsMarkdown(snap: HeadingsSnapshot, ctx: AgentCtx): string ), }, { title: "Outline", body: outlineLines(snap, issues, { max: 80 }) }, + { + title: "Landmarks", + body: landmarks?.landmarks.length ? fence(landmarksOutline(landmarks, { hidden: true, selectors: true })) : "", + }, ], verify: bad.length || warn.length ? "Reload the page and refresh devkit's Headings panel (Inspect › Headings)." : undefined, }); @@ -290,8 +373,12 @@ function jsonSnippet(raw: string, error: string | undefined): string { return fence(out.join("\n")); } -function jsonLdItem(block: JsonLdBlock, f: Finding, types: string[]): Item { - const where = `Block #${block.index + 1}${types.length ? ` (${types.join(", ")})` : ""}, ${code(f.path)}`; +function jsonLdItem(block: JsonLdBlock, f: Finding, types: string[], paths: string[] = [f.path]): Item { + const more = + paths.length > 1 + ? ` and ${plural(paths.length - 1, "other node")} (×${paths.length}: ${paths.slice(1, 6).map(code).join(", ")}${paths.length > 6 ? ", …" : ""})` + : ""; + const where = `Block #${block.index + 1}${types.length ? ` (${types.join(", ")})` : ""}, ${code(f.path)}${more}`; const details: string[] = []; let snippet: string | undefined; if (!block.ok && block.error && block.error !== "Empty script") { @@ -303,6 +390,9 @@ function jsonLdItem(block: JsonLdBlock, f: Finding, types: string[]): Item { else if (/missing required/.test(f.message)) details.push("Fix: add the property to this node with the value the page shows; without it the node is not eligible for rich results."); else if (/missing recommended/.test(f.message)) details.push("Fix: add it if the page shows that information."); + else if (f.rule === "vocab.domain") + details.push("Fix: move the property to a node of a type that has it, or change the node's @type; search engines may ignore it here."); + else if (f.rule === "vocab.range") details.push("Fix: give it a node of one of the expected types (or plain text where Text is listed)."); return { text: `${where}: ${f.message}`, details, block: snippet }; } @@ -316,10 +406,18 @@ export function jsonLdMarkdown(report: JsonLdReport, ctx: AgentCtx): string { ...b.findings.map((f) => ({ f, types: b.nodes[0]?.types ?? [] })), ...b.nodes.flatMap((n) => n.findings.map((f) => ({ f, types: n.types }))), ]; + // Identical findings on several nodes of the block (four offers with the same bad price) are one item. + const groups = new Map(); for (const { f, types } of entries) { - if (f.severity === "error") errors.push(jsonLdItem(b, f, types)); - else if (f.severity === "warn") warnings.push(jsonLdItem(b, f, types)); - else notes.set(f.message, [...(notes.get(f.message) ?? []), f.path]); + const key = `${f.severity}\u0000${f.rule}\u0000${f.message}`; + const g = groups.get(key); + if (g) g.paths.push(f.path); + else groups.set(key, { f, types, paths: [f.path] }); + } + for (const { f, types, paths } of groups.values()) { + if (f.severity === "error") errors.push(jsonLdItem(b, f, types, paths)); + else if (f.severity === "warn") warnings.push(jsonLdItem(b, f, types, paths)); + else notes.set(f.message, [...(notes.get(f.message) ?? []), ...paths]); } } const { error, warn } = report.counts; @@ -337,6 +435,9 @@ export function jsonLdMarkdown(report: JsonLdReport, ctx: AgentCtx): string { ? [ report.types.length ? `Types: ${report.types.map((t) => `${t.type} ×${t.count}`).join(", ")}` : "", 'Blocks are numbered in document order of the page\'s ``; +} + +/** `product-1.jsonld` (the block's first type and number); `.txt` for a block that is not valid JSON. */ +export function blockFileName(block: JsonLdBlock): string { + const type = (block.nodes[0]?.types[0] ?? "jsonld").replace(/[^\w-]+/g, "-").toLowerCase(); + return `${type}-${block.index + 1}.${block.ok ? "jsonld" : "txt"}`; +} + +/** Canonical, robots meta and X-Robots-Tag at a glance; null where the page sets none. */ +export function indexingSignals( + snap: { meta: { key: string; value: string }[]; links: { rel: string; href: string }[] }, + headers?: Record, +): { canonical: string | null; robots: string | null; xRobotsTag: string | null } { + const canonical = snap.links.find((l) => l.rel.toLowerCase().split(/\s+/).includes("canonical"))?.href ?? null; + const robots = snap.meta + .filter((m) => /^(robots|googlebot)$/i.test(m.key)) + .map((m) => (m.key.toLowerCase() === "robots" ? m.value : `${m.key}: ${m.value}`)) + .join(" · "); + const header = headers ? Object.entries(headers).find(([k]) => k.toLowerCase() === "x-robots-tag")?.[1] : undefined; + return { canonical, robots: robots || null, xRobotsTag: header ?? null }; +} + export const richResultsTestUrl = (url: string) => `https://search.google.com/test/rich-results?url=${encodeURIComponent(url)}`; export const schemaValidatorUrl = (url: string) => `https://validator.schema.org/#url=${encodeURIComponent(url)}`; diff --git a/src/lib/landmarks.ts b/src/lib/landmarks.ts new file mode 100644 index 0000000..60baffa --- /dev/null +++ b/src/lib/landmarks.ts @@ -0,0 +1,305 @@ +// The page's ARIA landmarks: tree, problems and text outline. Pure: the collector is in page/landmarks.ts. +import type { Level } from "./headers"; +import { buildOutline, headingText, isExposed, type OutlineNode } from "./headings"; +import type { RawHeading } from "./page/headings"; +import type { LandmarksSnapshot, RawLandmark } from "./page/landmarks"; + +export type LandmarkIssueId = + | "no-main" + | "multiple-main" + | "multiple-banner" + | "multiple-contentinfo" + | "not-top-level" + | "not-unique" + | "aria-hidden" + | "hidden" + | "redundant-role" + | "outside"; + +export interface LandmarkIssue { + id: LandmarkIssueId; + level: Level; + label: string; + detail: string; + /** The landmarks it is about (indexes in the snapshot), first one first. */ + at: number[]; + /** For "outside": the headings left out of every landmark. */ + headings?: number[]; +} + +/** Announced by screen readers and reachable by landmark navigation. */ +export const isLandmarkExposed = (l: Pick) => l.visibility === "visible"; + +/** HeadingsMap style: "Breadcrumbs [navigation]", or "main [main]" when it has no name. */ +export const landmarkLabel = (l: Pick) => `${l.name || l.role} [${l.role}]`; + +/** What the markup says: the tag when it gives the role ("nav"), else the role ("navigation" on a div). */ +export const landmarkTag = (l: Pick) => + l.explicitRole && !["header", "footer", "nav", "main", "aside", "form", "section", "search"].includes(l.tag) ? l.role : l.tag; + +const quoted = (l: RawLandmark) => (l.name ? `"${l.name.slice(0, 60)}"` : "unnamed"); +const norm = (s: string | undefined) => (s ?? "").toLowerCase().replace(/\s+/g, " ").trim(); + +export function landmarkIssues(snap: Pick, headings?: RawHeading[]): LandmarkIssue[] { + const out: LandmarkIssue[] = []; + const all = snap.landmarks; + const exposed = all.filter(isLandmarkExposed); + const of = (role: RawLandmark["role"]) => exposed.filter((l) => l.role === role); + + const mains = of("main"); + if (!mains.length) + out.push({ + id: "no-main", + level: "warn", + label: "No main landmark", + detail: all.some((l) => l.role === "main") + ? "The only
is hidden from screen readers: they cannot jump to the content." + : "No
nor role=main: screen reader users cannot jump past the header to the content.", + at: all.filter((l) => l.role === "main").map((l) => l.index), + }); + else if (mains.length > 1) + out.push({ + id: "multiple-main", + level: "warn", + label: `${mains.length} main landmarks`, + detail: "A page has one main landmark; hide the others (hidden attribute) when they are not the current view.", + at: mains.map((l) => l.index), + }); + for (const [role, id, tag] of [ + ["banner", "multiple-banner", "header"], + ["contentinfo", "multiple-contentinfo", "footer"], + ] as const) { + const top = of(role).filter((l) => l.parent < 0); + if (top.length > 1) + out.push({ + id, + level: "warn", + label: `${top.length} top-level ${role} landmarks`, + detail: `A page has one ${role} (its site-wide <${tag}>); ${top.map(quoted).join(", ")}.`, + at: top.map((l) => l.index), + }); + } + for (const l of exposed) + if (l.parent >= 0 && (l.role === "main" || l.role === "banner" || l.role === "contentinfo")) { + const p = all[l.parent]; + out.push({ + id: "not-top-level", + level: "warn", + label: `${l.role} inside another landmark`, + detail: `<${l.tag}> ${landmarkLabel(l)} sits inside ${p ? landmarkLabel(p) : "another landmark"}: ${l.role} belongs at the top of the page.`, + at: [l.index], + }); + } + // Same role, same name (or no name): a screen reader's landmarks list cannot tell them apart. main, banner and + // contentinfo have their own checks above. + const groups = new Map(); + for (const l of exposed) { + if (l.role === "main" || l.role === "banner" || l.role === "contentinfo") continue; + const key = `${l.role}:${norm(l.name)}`; + groups.set(key, [...(groups.get(key) ?? []), l]); + } + for (const g of groups.values()) + if (g.length > 1) { + const first = g[0]!; + out.push({ + id: "not-unique", + level: "warn", + label: first.name ? `${g.length} ${first.role} named "${first.name.slice(0, 40)}"` : `${g.length} unnamed ${first.role}`, + detail: `Give each ${first.role} landmark a distinct aria-label (or aria-labelledby), e.g. "Main menu" and "Footer links".`, + at: g.map((l) => l.index), + }); + } + for (const l of all) + if (l.visibility === "aria-hidden") + out.push({ + id: "aria-hidden", + level: "warn", + label: `Visible ${l.role} hidden from screen readers`, + detail: `${landmarkLabel(l)} is on screen but under aria-hidden="true".`, + at: [l.index], + }); + const hidden = all.filter((l) => l.visibility === "hidden"); + if (hidden.length) + out.push({ + id: "hidden", + level: "info", + label: `${hidden.length} hidden landmark${hidden.length === 1 ? "" : "s"}`, + detail: `${hidden + .slice(0, 4) + .map((l) => landmarkLabel(l)) + .join(", ")}${hidden.length > 4 ? ", …" : ""}: not announced; fine for a closed menu or dialog.`, + at: hidden.map((l) => l.index), + }); + for (const l of all) + if (l.redundantRole) + out.push({ + id: "redundant-role", + level: "info", + label: `Redundant role="${l.role}"`, + detail: `<${l.tag} role="${l.role}"> ${landmarkLabel(l)}: the tag already gives that role.`, + at: [l.index], + }); + const outside = headings ? snap.headingsOutside.filter((i) => headings[i] && isExposed(headings[i]!)) : snap.headingsOutside; + if (outside.length && all.length) { + const named = headings + ? outside + .slice(0, 3) + .map((i) => `h${headings[i]!.level} "${headingText(headings[i]!).slice(0, 50)}"`) + .join(", ") + : ""; + out.push({ + id: "outside", + level: "info", + label: `${outside.length} heading${outside.length === 1 ? "" : "s"} outside landmarks`, + detail: `${named ? `${named}${outside.length > 3 ? ", …" : ""}: ` : ""}landmark navigation skips ${outside.length === 1 ? "it" : "them"}; put the content in
or another landmark.`, + at: [], + headings: outside, + }); + } + const rank: Record = { bad: 0, warn: 1, info: 2, good: 3 }; + return out.sort((x, y) => rank[x.level] - rank[y.level]); +} + +/** Issues by landmark index, worst first. */ +export function issuesByLandmark(issues: LandmarkIssue[]): Map { + const m = new Map(); + for (const issue of issues) for (const i of issue.at) m.set(i, [...(m.get(i) ?? []), issue]); + return m; +} + +export interface LandmarkNode { + landmark: RawLandmark; + children: LandmarkNode[]; +} + +/** The nearest ancestor kept by `keep`, -1 when none. */ +function keptParent(all: RawLandmark[], l: RawLandmark, keep: (l: RawLandmark) => boolean): number { + for (let p = l.parent; p >= 0; p = all[p]?.parent ?? -1) if (all[p] && keep(all[p]!)) return p; + return -1; +} + +/** Nests landmarks under their nearest landmark ancestor; the ones `keep` drops are skipped and their children lifted. */ +export function buildLandmarkTree( + snap: Pick, + keep: (l: RawLandmark) => boolean = () => true, +): LandmarkNode[] { + const all = snap.landmarks; + const nodes = new Map(); + const roots: LandmarkNode[] = []; + for (const l of all) { + if (!keep(l)) continue; + const node: LandmarkNode = { landmark: l, children: [] }; + nodes.set(l.index, node); + const p = keptParent(all, l, keep); + (p >= 0 ? nodes.get(p)!.children : roots).push(node); + } + return roots; +} + +export type CombinedNode = + | { kind: "landmark"; landmark: RawLandmark; children: CombinedNode[] } + | { kind: "heading"; node: OutlineNode } + | { kind: "outside"; children: CombinedNode[] }; + +/** + * Landmarks with their headings nested under them, in document order: each run of headings between two child + * landmarks is an outline of its own. Headings in no kept landmark go under an "outside" node at the end. + */ +export function buildCombinedTree( + snap: Pick, + headings: RawHeading[], + keep: (l: RawLandmark) => boolean = () => true, +): CombinedNode[] { + const all = snap.landmarks; + const shown = new Map(headings.map((h) => [h.index, h] as const)); + const owner = new Map(); + for (const l of all) + for (const i of l.headingIndexes) { + if (!shown.has(i)) continue; + owner.set(i, keep(l) ? l.index : keptParent(all, l, keep)); + } + const direct = new Map(); + const outside: number[] = []; + for (const h of headings) { + const o = owner.get(h.index) ?? -1; + if (o < 0) outside.push(h.index); + else direct.set(o, [...(direct.get(o) ?? []), h.index]); + } + const kids = new Map(); + const roots: RawLandmark[] = []; + for (const l of all) { + if (!keep(l)) continue; + const p = keptParent(all, l, keep); + if (p < 0) roots.push(l); + else kids.set(p, [...(kids.get(p) ?? []), l]); + } + const outline = (idx: number[]): CombinedNode[] => buildOutline(idx.map((i) => shown.get(i)!)).map((node) => ({ kind: "heading", node })); + const content = (landmarks: RawLandmark[], own: number[]): CombinedNode[] => { + // A heading comes before a landmark when its index is below the landmark's first following heading. + type Item = { key: number; landmark?: RawLandmark; heading?: number }; + const items: Item[] = [ + ...landmarks.map((l) => ({ key: l.headingStart - 0.5, landmark: l })), + ...own.map((i) => ({ key: i, heading: i })), + ].sort((a, b) => a.key - b.key); + const out: CombinedNode[] = []; + let run: number[] = []; + const flush = () => { + if (run.length) out.push(...outline(run)); + run = []; + }; + for (const it of items) { + if (it.heading !== undefined) run.push(it.heading); + else { + flush(); + const l = it.landmark!; + out.push({ kind: "landmark", landmark: l, children: content(kids.get(l.index) ?? [], direct.get(l.index) ?? []) }); + } + } + flush(); + return out; + }; + const tree = content(roots, []); + if (outside.length) tree.push({ kind: "outside", children: outline(outside) }); + return tree; +} + +/** The landmarks as text, 4 spaces per level: "main [main]", " Breadcrumbs [navigation]". Hidden ones only when asked. */ +export function landmarksOutline(snap: Pick, opts: { hidden?: boolean; selectors?: boolean } = {}): string { + const tree = buildLandmarkTree(snap, (l) => Boolean(opts.hidden) || isLandmarkExposed(l)); + const lines: string[] = []; + const walk = (nodes: LandmarkNode[], depth: number) => { + for (const n of nodes) { + const l = n.landmark; + const flags = [l.visibility !== "visible" ? l.visibility : "", opts.selectors ? l.selector : ""].filter(Boolean); + lines.push(`${" ".repeat(depth)}${landmarkLabel(l)}${flags.length ? ` (${flags.join("; ")})` : ""}`); + walk(n.children, depth + 1); + } + }; + walk(tree, 0); + return lines.join("\n"); +} + +export function landmarkFix(issue: LandmarkIssue): string { + switch (issue.id) { + case "no-main": + return "Wrap the page's main content in one `
`."; + case "multiple-main": + return "Keep one `
`; turn the others into `
` or hide the inactive ones with `hidden`."; + case "multiple-banner": + return "Keep the site-wide `
` at the top; move the others inside `
` / `
` (where they are not banners) or use a `
`."; + case "multiple-contentinfo": + return "Keep the site-wide `