pagegraph 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -4
- package/dist/audit.d.ts +5 -0
- package/dist/audit.js +3 -0
- package/dist/audit.js.map +1 -1
- package/dist/{graph-BlLoEOw2.d.ts → checks-BfsQtKga.d.ts} +43 -2
- package/dist/cli.js +11388 -2897
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +7 -1
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts +131 -14
- package/dist/index.js +172 -4
- package/dist/index.js.map +1 -1
- package/dist/links-sGbLkl-7.js +184 -0
- package/dist/links-sGbLkl-7.js.map +1 -0
- package/package.json +13 -8
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/core/graph.ts","../src/core/projections.ts","../src/core/checks.ts","../src/core/inspect-html.ts","../src/core/resolve-route-link.ts"],"sourcesContent":["/**\n * SEO graph — the derived model that projections (sitemap, robots), the CLI, and\n * the check engine all read from. Built from route declarations (`staticData.seo`)\n * plus consumer-supplied content collections. This module is pure: no React, no\n * env, no knowledge of where instances come from. Origins and env-derived values\n * are injected by the callers of the projections, never read here.\n *\n * A node is one of:\n * - a structural route (`source: \"route\"`), keyed by its normalized full path,\n * merging a layout route's declaration (crumb) with its index child's (kind,\n * sitemap policy) when both resolve to the same URL;\n * - a content instance (`source` = the collection's label), keyed by the page URL\n * and carrying page-level metadata.\n *\n * Edges: `crumb-parent` (breadcrumb ancestry), `related` (deliberate cross-links),\n * `collection-member` (membership in a curated set), and `redirect` (route aliases).\n * The route walk emits crumb/related/redirect edges from declarations; a collection\n * may declare any additional edges its instances need.\n */\n\nimport type { AnyRoute } from \"@tanstack/react-router\";\n\nimport type { PublicPath, RouteSeo, SeoKind } from \"./declare\";\n\n/**\n * Where a node came from: `\"route\"` for a structural route declaration, or the\n * `source` label of the collection that produced the instance (e.g. \"blog\").\n */\nexport type SeoSource = string;\n\nexport interface SeoNode {\n /** Canonical path, no origin (e.g. \"/pricing\", \"/blog/my-post\"). */\n path: string;\n kind: SeoKind;\n source: SeoSource;\n /** Route-declared policy, or synthesized (kind + inherited sitemap) for instances. */\n policy: RouteSeo;\n instance?:\n | {\n title: string;\n description?: string | undefined;\n publishedAt?: string | undefined;\n modifiedAt?: string | undefined;\n }\n | undefined;\n}\n\nexport type SeoEdgeType = \"crumb-parent\" | \"related\" | \"redirect\" | \"collection-member\";\n\nexport interface SeoEdge {\n from: string;\n to: string;\n type: SeoEdgeType;\n}\n\nexport interface SeoGraph {\n nodes: Map<string, SeoNode>;\n edges: Array<SeoEdge>;\n /** Exact-path ownership conflicts encountered while assembling graph sources. */\n collisions?: ReadonlyArray<{ path: string; sources: ReadonlyArray<SeoSource> }> | undefined;\n}\n\n/** One concrete page produced by a collection. */\nexport interface SeoInstance {\n /** Canonical path of the page (e.g. \"/blog/my-post\"). */\n readonly path: string;\n readonly title: string;\n readonly description?: string | undefined;\n readonly publishedAt?: string | undefined;\n readonly modifiedAt?: string | undefined;\n}\n\nexport interface SeoCollection {\n /**\n * The param route these instances render through (e.g. \"/blog/$slug\"). Instances\n * inherit this route's declared policy (kind + sitemap) — the graph reads it from\n * the structural node, so declarations stay the single source of truth.\n */\n readonly route: PublicPath;\n /** The `source` stamped on every node this collection produces (e.g. \"blog\"). */\n readonly source: SeoSource;\n readonly instances: ReadonlyArray<SeoInstance>;\n /** Edges the collection declares between its instances and the rest of the graph. */\n readonly edges?: ReadonlyArray<SeoEdge> | undefined;\n}\n\nexport interface BuildSeoGraphInput {\n readonly routeTree: AnyRoute;\n readonly collections?: ReadonlyArray<SeoCollection> | undefined;\n}\n\n/** Kind for instances whose collection route carries no declaration to inherit. */\nconst FALLBACK_KIND: SeoKind = \"page\";\n\n/** Structural view of a route we walk — the fields present before router init(). */\ninterface WalkableRoute {\n readonly options: {\n readonly path?: string | undefined;\n readonly staticData?: { readonly seo?: RouteSeo | undefined } | undefined;\n };\n readonly children?: ReadonlyArray<WalkableRoute> | undefined;\n}\n\n/**\n * Join a child's local path onto its parent's computed full path with the same\n * semantics as TanStack's route init (relative segments, index \"/\" inherits the\n * parent, pathless/group routes are transparent), then normalize trailing slashes.\n */\nfunction joinPath(parent: string, seg: string | undefined): string {\n if (seg === undefined) return parent; // pathless layout / route group\n if (seg === \"/\") return parent; // index route resolves to its parent's URL\n const trimmed = seg.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n const joined = `${parent === \"/\" ? \"\" : parent}/${trimmed}`;\n return joined.replace(/\\/{2,}/g, \"/\");\n}\n\n/** Merge a route's declaration into an existing same-path node (deeper route wins). */\nfunction mergeSeo(base: RouteSeo, override: RouteSeo): RouteSeo {\n return {\n kind: override.kind,\n crumb: override.crumb ?? base.crumb,\n sitemap: override.sitemap ?? base.sitemap,\n robots: override.robots ?? base.robots,\n related: override.related ?? base.related,\n link: override.link ?? base.link,\n redirectTo: override.redirectTo ?? base.redirectTo,\n };\n}\n\n/**\n * Walk the route tree building structural nodes and crumb-parent edges. `crumbStack`\n * holds the paths of crumb-declaring ancestors so each crumb node links to its nearest\n * crumb ancestor down the real route-parent chain (matching render-time breadcrumbs).\n */\nfunction walkRoutes(\n route: WalkableRoute,\n parentPath: string,\n isRoot: boolean,\n nodes: Map<string, SeoNode>,\n edges: Array<SeoEdge>,\n crumbStack: Array<string>,\n): void {\n const path = isRoot ? \"/\" : joinPath(parentPath, route.options.path);\n const seo = route.options.staticData?.seo;\n\n if (seo) {\n const existing = nodes.get(path);\n if (existing) {\n existing.policy = mergeSeo(existing.policy, seo);\n existing.kind = existing.policy.kind;\n } else {\n nodes.set(path, { path, kind: seo.kind, source: \"route\", policy: { ...seo } });\n }\n\n const nearestCrumbAncestor = crumbStack[crumbStack.length - 1];\n if (seo.crumb !== undefined && nearestCrumbAncestor !== undefined) {\n edges.push({ from: path, to: nearestCrumbAncestor, type: \"crumb-parent\" });\n }\n }\n\n const pushedCrumb = seo?.crumb !== undefined;\n if (pushedCrumb) crumbStack.push(path);\n for (const child of route.children ?? []) {\n walkRoutes(child, path, false, nodes, edges, crumbStack);\n }\n if (pushedCrumb) crumbStack.pop();\n}\n\n/**\n * Add one collection's instance nodes, inheriting kind + sitemap policy from the\n * collection route's declaration, then append the edges it declares. A path already\n * owned by another node is a collision: the first owner keeps the path and the\n * conflict is reported (the `path-owner-collision` check turns it into a violation).\n */\nfunction addCollection(\n nodes: Map<string, SeoNode>,\n edges: Array<SeoEdge>,\n collisions: Array<{ path: string; sources: ReadonlyArray<SeoSource> }>,\n collection: SeoCollection,\n): void {\n const collectionNode = nodes.get(collection.route);\n const kind = collectionNode?.kind ?? FALLBACK_KIND;\n const sitemap = collectionNode?.policy.sitemap;\n\n /**\n * Paths this collection lost to an earlier owner. Their instances never enter\n * the graph, so any edge declared out of them would dangle — and the dead-edge\n * check only validates an edge's `to`, so nothing downstream would catch it.\n */\n const rejected = new Set<string>();\n\n for (const instance of collection.instances) {\n const existing = nodes.get(instance.path);\n if (existing) {\n collisions.push({ path: instance.path, sources: [existing.source, collection.source] });\n rejected.add(instance.path);\n continue;\n }\n nodes.set(instance.path, {\n path: instance.path,\n kind,\n source: collection.source,\n policy: { kind, sitemap },\n instance: {\n title: instance.title,\n description: instance.description,\n publishedAt: instance.publishedAt,\n modifiedAt: instance.modifiedAt,\n },\n });\n }\n\n for (const edge of collection.edges ?? []) {\n if (rejected.has(edge.from)) continue;\n edges.push(edge);\n }\n}\n\n/**\n * Build the SEO graph from route declarations and content collections.\n *\n * Synchronous: the caller materializes its collections before calling, so there is\n * no async work here. Callers own the origin.\n */\nexport function buildSeoGraph(input: BuildSeoGraphInput): SeoGraph {\n const nodes = new Map<string, SeoNode>();\n const edges: Array<SeoEdge> = [];\n const collisions: Array<{ path: string; sources: ReadonlyArray<SeoSource> }> = [];\n\n walkRoutes(input.routeTree as unknown as WalkableRoute, \"/\", true, nodes, edges, []);\n\n for (const collection of input.collections ?? []) {\n addCollection(nodes, edges, collisions, collection);\n }\n\n for (const node of nodes.values()) {\n if (node.source !== \"route\") continue;\n for (const to of node.policy.related ?? []) {\n edges.push({ from: node.path, to, type: \"related\" });\n }\n if (node.policy.redirectTo !== undefined) {\n edges.push({ from: node.path, to: node.policy.redirectTo, type: \"redirect\" });\n }\n }\n\n return { nodes, edges, collisions };\n}\n","/**\n * Projections of the SEO graph: sitemap.xml, robots.txt, and single-node\n * inspection. Pure functions — the origin, the host's indexability, and the\n * robots disallow list are injected by the caller, never read from the\n * environment or a generated file.\n */\n\nimport type { SeoEdge, SeoGraph, SeoNode } from \"./graph\";\n\nexport interface ProjectionConfig {\n origin: string;\n indexable: boolean;\n}\n\nexport interface RobotsConfig extends ProjectionConfig {\n /** Path prefixes to disallow on an indexable host (e.g. the app-only groups). */\n disallow: ReadonlyArray<string>;\n /**\n * Origin-wide Content-Signal preferences\n * (https://contentsignals.org/), emitted as `Content-Signal: <value>` under\n * `User-agent: *` on an indexable host. Omit for none. The plugin never\n * invents a default — pass the policy you want, e.g.\n * `\"search=yes, ai-input=yes, ai-train=yes\"`.\n */\n contentSignal?: string | undefined;\n /**\n * Extra full lines in the indexable `User-agent: *` group, after\n * Content-Signal (if any) and before Allow/Disallow. Use for directives the\n * plugin does not model, or to compose {@link contentSignal} yourself.\n */\n directives?: ReadonlyArray<string> | undefined;\n /**\n * Last-mile override: receives the rendered robots.txt and returns the file\n * to emit. Runs for indexable and preview hosts. Use when you need to wrap\n * or replace the default body rather than add group lines.\n */\n transform?: ((robots: string) => string) | undefined;\n}\n\nexport interface NodeReport {\n node: SeoNode;\n inSitemap: boolean;\n incoming: Array<SeoEdge>;\n outgoing: Array<SeoEdge>;\n}\n\nconst escapeXml = (value: string): string =>\n value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n\n/**\n * A node belongs in the sitemap when it declares a positive sitemap policy, is not\n * a redirect, is not robots-noindexed, and is not a param template (a route whose\n * path still contains a `$` segment — those exist only so their instances inherit).\n */\nfunction isSitemapEligible(node: SeoNode): boolean {\n if (node.policy.redirectTo !== undefined) return false;\n if (node.policy.robots?.includes(\"noindex\")) return false;\n if (!node.policy.sitemap) return false; // false or absent\n if (node.path.includes(\"$\")) return false;\n return true;\n}\n\n/** Canonical absolute URL for a node under the given origin. */\nfunction urlForNode(origin: string, node: SeoNode): string {\n return node.path === \"/\" ? origin : `${origin}${node.path}`;\n}\n\n/**\n * Instance lastmod: the most recent date the page's frontmatter carries. A\n * collection whose instances carry no dates (docs, a manifest-driven gallery)\n * emits no `<lastmod>` at all.\n */\nfunction instanceLastmod(node: SeoNode): string | undefined {\n const instance = node.instance;\n if (!instance) return undefined;\n const date = instance.modifiedAt ?? instance.publishedAt;\n return date ? new Date(date).toISOString() : undefined;\n}\n\nfunction renderUrlEntry(url: string, lastmod: string | undefined, node: SeoNode): string {\n const sitemap = node.policy.sitemap;\n // isSitemapEligible guarantees a positive policy before this runs.\n const { changeFrequency, priority } = sitemap as { changeFrequency: string; priority: number };\n const lines = [` <url>`, ` <loc>${escapeXml(url)}</loc>`];\n if (lastmod) lines.push(` <lastmod>${lastmod}</lastmod>`);\n lines.push(\n ` <changefreq>${changeFrequency}</changefreq>`,\n ` <priority>${priority.toFixed(1)}</priority>`,\n ` </url>`,\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Render sitemap.xml from the graph. Structural route entries emit no `<lastmod>`\n * (a route has no publish date); content instances emit it from their frontmatter.\n * Route entries are sorted by path, then instances follow in collection order.\n * `indexable` is intentionally unused — the sitemap body is host-independent;\n * robots.txt is what gates crawling.\n */\nexport function renderSitemap(graph: SeoGraph, cfg: ProjectionConfig): string {\n const nodes = [...graph.nodes.values()];\n const staticNodes = nodes\n .filter((node) => node.source === \"route\" && isSitemapEligible(node))\n .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n const instanceNodes = nodes.filter((node) => node.source !== \"route\" && isSitemapEligible(node));\n\n const seen = new Set<string>();\n const entries: Array<string> = [];\n for (const node of [...staticNodes, ...instanceNodes]) {\n const url = urlForNode(cfg.origin, node);\n const key = url.toLowerCase().replace(/\\/$/, \"\");\n if (seen.has(key)) continue;\n seen.add(key);\n entries.push(renderUrlEntry(url, instanceLastmod(node), node));\n }\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\\n${entries.join(\n \"\\n\",\n )}\\n</urlset>\\n`;\n}\n\n/** Format a Content-Signal robots.txt directive from the preference list. */\nexport function contentSignal(value: string): string {\n return `Content-Signal: ${value}`;\n}\n\nconst groupLines = (cfg: RobotsConfig): Array<string> => {\n const lines: Array<string> = [];\n if (cfg.contentSignal !== undefined && cfg.contentSignal !== \"\") {\n lines.push(contentSignal(cfg.contentSignal));\n }\n for (const directive of cfg.directives ?? []) {\n if (directive !== \"\") lines.push(directive);\n }\n return lines;\n};\n\n/**\n * Render robots.txt. A non-indexable host (previews) gets a disallow-all\n * with no Sitemap line; an indexable host disallows exactly the prefixes the caller\n * passes. Pages that declare `robots: noindex` are intentionally NOT added as\n * Disallow entries — a Disallow would stop crawlers reaching the page to read its\n * `noindex, follow` meta, so the graph's per-node robots policy never feeds this\n * list. `graph` is unused — kept for signature parity with the other projections,\n * which callers load the graph once for and pass to each.\n *\n * Origin-wide group directives (`contentSignal`, `directives`) are indexable-host\n * only. {@link RobotsConfig.transform} always runs last so a consumer can override\n * the whole file.\n */\nexport function renderRobots(_graph: SeoGraph, cfg: RobotsConfig): string {\n const rendered = cfg.indexable\n ? [\n \"User-agent: *\",\n ...groupLines(cfg),\n \"Allow: /\",\n ...cfg.disallow.map((path) => `Disallow: ${path}`),\n \"\",\n `Sitemap: ${cfg.origin}/sitemap.xml`,\n `Host: ${cfg.origin}`,\n \"\",\n ].join(\"\\n\")\n : [\"User-agent: *\", \"Disallow: /\", \"\"].join(\"\\n\");\n return cfg.transform === undefined ? rendered : cfg.transform(rendered);\n}\n\n/** Inspect a single node: its declaration, sitemap eligibility, and edges. */\nexport function inspectNode(graph: SeoGraph, path: string): NodeReport | undefined {\n const node = graph.nodes.get(path);\n if (!node) return undefined;\n return {\n node,\n inSitemap: isSitemapEligible(node),\n incoming: graph.edges.filter((edge) => edge.to === path),\n outgoing: graph.edges.filter((edge) => edge.from === path),\n };\n}\n","/**\n * The SEO check engine: a set of rules run against the derived {@link SeoGraph}.\n * Pure — no I/O, no `clientEnv`, no React. The CLI's `pagegraph check` command and the\n * vitest suite both call {@link checkGraph}; nothing else derives correctness.\n *\n * Two severities, mapped to the CLI's exit contract:\n * - `structural` — a declaration is internally broken (a link points nowhere, a\n * card would render empty, a page contradicts its own robots/sitemap intent).\n * Any structural violation fails `pagegraph check` (exit 1); these must not ship.\n * - `editorial` — a quality smell (duplicate or mis-sized titles/descriptions).\n * Reported as warnings; `pagegraph check` still exits 0 when only these are present.\n *\n * The graph only knows what declarations and frontmatter carry, so the rules are\n * scoped to that: per-node title/description live only on collection *instances*,\n * never on structural route nodes (whose head tags are composed at render time and\n * are not in the graph). Rules are data-driven and listed once in\n * {@link CHECK_RULES}.\n */\n\nimport type { SitemapPolicy } from \"./declare\";\nimport type { SeoGraph, SeoNode } from \"./graph\";\n\nexport type Severity = \"structural\" | \"editorial\";\n\nexport interface Violation {\n severity: Severity;\n rule: string;\n path?: string | undefined;\n message: string;\n fix?: string | undefined;\n}\n\n/** A single finding before its rule's `severity`/`rule` name are attached. */\ninterface RawViolation {\n path?: string | undefined;\n message: string;\n fix?: string | undefined;\n}\n\ninterface CheckRule {\n readonly name: string;\n readonly severity: Severity;\n readonly evaluate: (graph: SeoGraph) => ReadonlyArray<RawViolation>;\n}\n\n/** A positive sitemap policy — the author asked for this page to be indexed. */\nconst hasPositiveSitemap = (sitemap: SitemapPolicy | false | undefined): sitemap is SitemapPolicy =>\n sitemap !== undefined && sitemap !== false;\n\n/** Content and manifest instances carry page-level title/description. */\nconst isInstance = (node: SeoNode): boolean => node.source !== \"route\";\n\n/** Group instance nodes by a present, non-empty string field for duplicate detection. */\nconst groupInstancesBy = (\n graph: SeoGraph,\n field: (node: SeoNode) => string | undefined,\n): Map<string, Array<SeoNode>> => {\n const groups = new Map<string, Array<SeoNode>>();\n for (const node of graph.nodes.values()) {\n if (!isInstance(node)) continue;\n const value = field(node)?.trim();\n if (!value) continue;\n const bucket = groups.get(value);\n if (bucket) bucket.push(node);\n else groups.set(value, [node]);\n }\n return groups;\n};\n\nconst DESCRIPTION_MAX = 160;\nconst DESCRIPTION_MIN = 50;\n\n/**\n * Every check, in one place. `checkGraph` runs them in order and stamps each\n * finding with its rule name and severity, so the output is grouped by rule and\n * deterministic (nodes iterate in graph insertion order, edges in array order).\n */\nconst CHECK_RULES: ReadonlyArray<CheckRule> = [\n {\n name: \"path-owner-collision\",\n severity: \"structural\",\n evaluate: (graph) =>\n (graph.collisions ?? []).map((collision) => ({\n path: collision.path,\n message: `Canonical path \"${collision.path}\" is owned by multiple sources: ${collision.sources.join(\", \")}.`,\n fix: \"Give every concrete page one canonical path and one graph owner.\",\n })),\n },\n {\n name: \"canonical-path-collision\",\n severity: \"structural\",\n evaluate: (graph) => {\n const groups = new Map<string, Array<string>>();\n for (const path of graph.nodes.keys()) {\n const canonical = path.toLowerCase().replace(/\\/$/, \"\") || \"/\";\n const paths = groups.get(canonical);\n if (paths) paths.push(path);\n else groups.set(canonical, [path]);\n }\n return [...groups.values()]\n .filter((paths) => paths.length > 1)\n .flatMap((paths) =>\n paths.map((path) => ({\n path,\n message: `Canonical path collides with ${paths.filter((candidate) => candidate !== path).join(\", \")}.`,\n fix: \"Use one lowercase, trailing-slash-normalized canonical path.\",\n })),\n );\n },\n },\n {\n name: \"self-edge\",\n severity: \"structural\",\n evaluate: (graph) =>\n graph.edges\n .filter((edge) => edge.from === edge.to)\n .map((edge) => ({\n path: edge.from,\n message: `${edge.type} edge points back to its own source node.`,\n fix: \"Remove the self-reference from the canonical manifest or route declaration.\",\n })),\n },\n {\n name: \"duplicate-edge\",\n severity: \"structural\",\n evaluate: (graph) => {\n const seen = new Set<string>();\n const duplicates: Array<RawViolation> = [];\n for (const edge of graph.edges) {\n const key = `${edge.from}\\u0000${edge.to}\\u0000${edge.type}`;\n if (seen.has(key)) {\n duplicates.push({\n path: edge.from,\n message: `Duplicate ${edge.type} edge from \"${edge.from}\" to \"${edge.to}\".`,\n fix: \"Declare each graph relationship exactly once.\",\n });\n } else {\n seen.add(key);\n }\n }\n return duplicates;\n },\n },\n {\n // A `related` or `redirect` edge points at a path with no node — the target\n // route/page was renamed or deleted and the declaration wasn't updated.\n name: \"dead-edge\",\n severity: \"structural\",\n evaluate: (graph) =>\n graph.edges\n .filter((edge) => edge.type !== \"crumb-parent\" && !graph.nodes.has(edge.to))\n .map((edge) => ({\n path: edge.from,\n message: `${edge.type} edge from \"${edge.from}\" points at \"${edge.to}\", which is not a node in the graph.`,\n fix: `Update the ${edge.type === \"redirect\" ? \"redirectTo\" : \"related\"} target on the \"${edge.from}\" route, or restore \"${edge.to}\".`,\n })),\n },\n {\n // A content instance with no usable title can't render a legible <title> or card.\n name: \"instance-missing-title\",\n severity: \"structural\",\n evaluate: (graph) =>\n [...graph.nodes.values()]\n .filter((node) => isInstance(node) && !node.instance?.title.trim())\n .map((node) => ({\n path: node.path,\n message: `Content page \"${node.path}\" has no title.`,\n fix: \"Add a `title` to the page frontmatter.\",\n })),\n },\n {\n // The declaration asks for the page to be in the sitemap yet also marks it\n // noindex — contradictory intent. The projection resolves it (noindex wins,\n // excluded), but the declaration should say one thing.\n name: \"sitemap-noindex-contradiction\",\n severity: \"structural\",\n evaluate: (graph) =>\n [...graph.nodes.values()]\n .filter(\n (node) =>\n hasPositiveSitemap(node.policy.sitemap) &&\n node.policy.robots?.toLowerCase().includes(\"noindex\"),\n )\n .map((node) => ({\n path: node.path,\n message: `\"${node.path}\" declares a sitemap policy but its robots value is \"${node.policy.robots}\".`,\n fix: \"Drop the sitemap policy (or set `sitemap: false`) on a noindex page, or remove the noindex robots value.\",\n })),\n },\n {\n // Robots declarations are house-convention lowercase: the sitemap projection\n // matches `includes(\"noindex\")` literally, so a miscased value (\"Noindex\")\n // would silently stay sitemap-eligible. This gate makes that unrepresentable.\n name: \"robots-not-lowercase\",\n severity: \"structural\",\n evaluate: (graph) =>\n [...graph.nodes.values()]\n .filter(\n (node) =>\n node.policy.robots !== undefined &&\n node.policy.robots !== node.policy.robots.toLowerCase(),\n )\n .map((node) => ({\n path: node.path,\n message: `\"${node.path}\" declares robots \"${node.policy.robots}\" — robots values must be lowercase.`,\n fix: 'Lowercase the robots declaration (e.g. \"noindex, follow\").',\n })),\n },\n {\n // A `related` card for a route target renders from that route's `link`\n // metadata; without it the card has no title/description and renders empty.\n // (Content-instance targets render from their frontmatter, so they're exempt.)\n name: \"related-target-missing-link\",\n severity: \"structural\",\n evaluate: (graph) => {\n const linklessTargets = new Set<string>();\n for (const edge of graph.edges) {\n if (edge.type !== \"related\") continue;\n const target = graph.nodes.get(edge.to);\n if (target && target.source === \"route\" && target.policy.link === undefined) {\n linklessTargets.add(edge.to);\n }\n }\n return [...linklessTargets].map((path) => ({\n path,\n message: `Route \"${path}\" is a related-link target but declares no link metadata; its card would render empty.`,\n fix: `Add \\`link: { title, description }\\` to the \"${path}\" route's staticData.seo.`,\n }));\n },\n },\n {\n // A redirect/alias node should never advertise itself in the sitemap.\n name: \"redirect-in-sitemap\",\n severity: \"structural\",\n evaluate: (graph) =>\n [...graph.nodes.values()]\n .filter(\n (node) => node.policy.redirectTo !== undefined && hasPositiveSitemap(node.policy.sitemap),\n )\n .map((node) => ({\n path: node.path,\n message: `Redirect \"${node.path}\" (→ \"${node.policy.redirectTo}\") also declares a sitemap policy.`,\n fix: \"Remove the sitemap policy from the redirect route; only its target belongs in the sitemap.\",\n })),\n },\n {\n name: \"duplicate-title\",\n severity: \"editorial\",\n evaluate: (graph) =>\n [...groupInstancesBy(graph, (node) => node.instance?.title).entries()]\n .filter(([, nodes]) => nodes.length > 1)\n .flatMap(([title, nodes]) =>\n nodes.map((node) => ({\n path: node.path,\n message: `Title \"${title}\" is shared by ${nodes.length} pages.`,\n fix: \"Give each page a distinct title.\",\n })),\n ),\n },\n {\n name: \"duplicate-description\",\n severity: \"editorial\",\n evaluate: (graph) =>\n [...groupInstancesBy(graph, (node) => node.instance?.description).entries()]\n .filter(([, nodes]) => nodes.length > 1)\n .flatMap(([, nodes]) =>\n nodes.map((node) => ({\n path: node.path,\n message: `Description is shared by ${nodes.length} pages.`,\n fix: \"Write a distinct meta description for each page.\",\n })),\n ),\n },\n {\n // Meta descriptions outside ~50–160 chars either get truncated in SERPs or\n // read as too thin.\n name: \"description-length\",\n severity: \"editorial\",\n evaluate: (graph) =>\n [...graph.nodes.values()].flatMap((node) => {\n if (!isInstance(node)) return [];\n const description = node.instance?.description?.trim();\n if (!description) return [];\n if (description.length > DESCRIPTION_MAX) {\n return [\n {\n path: node.path,\n message: `Description is ${description.length} chars (max ${DESCRIPTION_MAX}); it will be truncated in results.`,\n fix: `Trim the description to ${DESCRIPTION_MAX} characters or fewer.`,\n },\n ];\n }\n if (description.length < DESCRIPTION_MIN) {\n return [\n {\n path: node.path,\n message: `Description is ${description.length} chars (min ${DESCRIPTION_MIN}); it reads as thin.`,\n fix: `Expand the description to at least ${DESCRIPTION_MIN} characters.`,\n },\n ];\n }\n return [];\n }),\n },\n];\n\n/** Run every rule against the graph and return the flat list of violations. */\nexport function checkGraph(graph: SeoGraph): Array<Violation> {\n return CHECK_RULES.flatMap((rule) =>\n rule.evaluate(graph).map((raw) => ({\n severity: rule.severity,\n rule: rule.name,\n path: raw.path,\n message: raw.message,\n fix: raw.fix,\n })),\n );\n}\n\n/** Structural violations fail `pagegraph check`; editorial-only stays green. */\nexport const hasStructuralViolations = (violations: ReadonlyArray<Violation>): boolean =>\n violations.some((violation) => violation.severity === \"structural\");\n","/**\n * Read a rendered `<head>` and validate it: title, meta\n * (description/robots/og/twitter), canonical link, and `application/ld+json`\n * blocks, with a minimal per-type JSON-LD check.\n *\n * This is the pure half of `pagegraph inspect --live` — the half worth having on its\n * own. The CLI fetches a URL and hands the body here; a test suite can render a\n * page and hand *that* here, asserting the head it actually ships. Both get the\n * same verdict, because it is the same function.\n *\n * No HTML-parsing dependency, by design: a `<head>` is small and well-formed, so\n * string/regex scanning is enough, and the package's core stays zero-dependency\n * (which is also why the object guard below is hand-rolled — `effect/Predicate`\n * is not reachable from this entry). It is honest about its limits: it does not\n * build a DOM, so exotic markup (commented-out tags, CDATA, attributes spanning\n * constructs) is out of scope. This validates *rendered output*, not arbitrary\n * HTML.\n *\n * `issues` are blocking: a non-empty list makes `pagegraph inspect --live` exit 1.\n * Required tags are `<title>`, `meta[name=description]`, and\n * `link[rel=canonical]`; any JSON-LD that fails to parse or fails its minimal\n * schema is also blocking.\n */\n\nexport interface JsonLdReport {\n type: string;\n valid: boolean;\n errors: Array<string>;\n}\n\nexport interface LiveHeadReport {\n url: string;\n status: number;\n title?: string | undefined;\n description?: string | undefined;\n canonical?: string | undefined;\n robots?: string | undefined;\n og: Record<string, string>;\n twitter: Record<string, string>;\n jsonLd: Array<JsonLdReport>;\n issues: Array<string>;\n}\n\nconst ENTITIES: Record<string, string> = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n \""\": '\"',\n \"'\": \"'\",\n \"'\": \"'\",\n};\n\nconst decodeEntities = (value: string): string =>\n value.replace(/&(?:amp|lt|gt|quot|#39|apos);/g, (match) => ENTITIES[match] ?? match);\n\n/** Pull double/single-quoted attributes off a single tag string. */\nconst parseAttrs = (tag: string): Record<string, string> => {\n const attrs: Record<string, string> = {};\n const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(tag)) !== null) {\n attrs[match[1]!.toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? \"\");\n }\n return attrs;\n};\n\n/** Normalize a JSON-LD `@type` (string or array) to a single readable label. */\nconst typeName = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value))\n return value.filter((v) => typeof v === \"string\").join(\", \") || \"unknown\";\n return \"unknown\";\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n // NOTE: This zero-dependency core entry cannot import Effect; JSON-LD validation happens immediately after this shallow narrowing.\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** Flatten a parsed JSON-LD payload (single object, array, or `@graph`) to items. */\nconst collectItems = (parsed: unknown): Array<Record<string, unknown>> => {\n if (Array.isArray(parsed)) return parsed.filter(isObject);\n if (isObject(parsed)) {\n if (Array.isArray(parsed[\"@graph\"])) return parsed[\"@graph\"].filter(isObject);\n return [parsed];\n }\n return [];\n};\n\nconst countQuestions = (mainEntity: unknown): number => {\n if (!Array.isArray(mainEntity)) return 0;\n return mainEntity.filter((entry) => isObject(entry) && typeName(entry[\"@type\"]) === \"Question\")\n .length;\n};\n\nconst validateItemListElements = (value: unknown): Array<string> => {\n if (!Array.isArray(value) || value.length < 1) {\n return [\"ItemList needs at least one `itemListElement` entry.\"];\n }\n const errors: Array<string> = [];\n value.forEach((entry, index) => {\n if (!isObject(entry) || typeName(entry[\"@type\"]) !== \"ListItem\") {\n errors.push(`ItemList entry ${index + 1} is not a ListItem.`);\n return;\n }\n if (entry[\"position\"] !== index + 1) {\n errors.push(`ItemList entry ${index + 1} has an invalid position.`);\n }\n if (!entry[\"name\"] || !entry[\"url\"]) {\n errors.push(`ItemList entry ${index + 1} needs a name and URL.`);\n }\n });\n return errors;\n};\n\n/** Minimal per-type validation — enough to catch an empty or malformed block. */\nconst validateItem = (item: Record<string, unknown>): JsonLdReport => {\n const type = typeName(item[\"@type\"]);\n const errors: Array<string> = [];\n\n if (type === \"Article\" || type === \"NewsArticle\" || type === \"BlogPosting\") {\n if (!item[\"headline\"]) errors.push(\"Article is missing `headline`.\");\n if (!item[\"datePublished\"]) errors.push(\"Article is missing `datePublished`.\");\n } else if (type === \"FAQPage\") {\n if (countQuestions(item[\"mainEntity\"]) < 1) {\n errors.push(\"FAQPage needs at least one Question in `mainEntity`.\");\n }\n } else if (type === \"BreadcrumbList\") {\n const items = item[\"itemListElement\"];\n if (!Array.isArray(items) || items.length < 2) {\n errors.push(\"BreadcrumbList needs at least two `itemListElement` entries.\");\n }\n } else if (type === \"ItemList\") {\n errors.push(...validateItemListElements(item[\"itemListElement\"]));\n const items = item[\"itemListElement\"];\n if (Array.isArray(items) && item[\"numberOfItems\"] !== items.length) {\n errors.push(\"ItemList `numberOfItems` does not match its entries.\");\n }\n }\n\n return { type, valid: errors.length === 0, errors };\n};\n\nconst validateLdJson = (raw: string): Array<JsonLdReport> => {\n let parsed: unknown;\n // NOTE: JSON.parse boundary: converts the native parse throw into an unparseable JsonLdReport value in a pure sync validator\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n return [\n {\n type: \"unparseable\",\n valid: false,\n errors: [`JSON parse error: ${cause instanceof Error ? cause.message : String(cause)}`],\n },\n ];\n }\n const items = collectItems(parsed);\n if (items.length === 0) {\n return [{ type: \"unknown\", valid: false, errors: [\"No JSON-LD object found in block.\"] }];\n }\n return items.map(validateItem);\n};\n\n/** Parse a rendered HTML document's `<head>` into a report. Pure. */\nexport const inspectHtml = (url: string, status: number, html: string): LiveHeadReport => {\n const headMatch = html.match(/<head[^>]*>([\\s\\S]*?)<\\/head>/i);\n const head = headMatch ? headMatch[1]! : html;\n\n const titleMatch = head.match(/<title[^>]*>([\\s\\S]*?)<\\/title>/i);\n const title = titleMatch ? decodeEntities(titleMatch[1]!.trim()) : undefined;\n\n const og: Record<string, string> = {};\n const twitter: Record<string, string> = {};\n let description: string | undefined;\n let robots: string | undefined;\n\n for (const tag of head.match(/<meta\\b[^>]*>/gi) ?? []) {\n const attrs = parseAttrs(tag);\n const content = attrs[\"content\"];\n if (content === undefined) continue;\n const property = attrs[\"property\"];\n const name = attrs[\"name\"];\n if (property?.startsWith(\"og:\")) og[property] = content;\n else if (name?.startsWith(\"twitter:\")) twitter[name] = content;\n else if (name === \"description\") description = content;\n else if (name === \"robots\") robots = content;\n }\n\n let canonical: string | undefined;\n for (const tag of head.match(/<link\\b[^>]*>/gi) ?? []) {\n const attrs = parseAttrs(tag);\n if (attrs[\"rel\"] === \"canonical\") canonical = attrs[\"href\"];\n }\n\n const jsonLd: Array<JsonLdReport> = [];\n const scriptRe = /<script\\b[^>]*type=[\"']application\\/ld\\+json[\"'][^>]*>([\\s\\S]*?)<\\/script>/gi;\n let scriptMatch: RegExpExecArray | null;\n while ((scriptMatch = scriptRe.exec(head)) !== null) {\n jsonLd.push(...validateLdJson(scriptMatch[1]!.trim()));\n }\n\n const issues: Array<string> = [];\n if (status >= 400) issues.push(`Fetch returned HTTP ${status}.`);\n if (!title) issues.push(\"Missing <title>.\");\n if (!description) issues.push(\"Missing meta description.\");\n if (!canonical) issues.push(\"Missing canonical link.\");\n for (const block of jsonLd) {\n if (!block.valid)\n issues.push(...block.errors.map((error) => `JSON-LD (${block.type}): ${error}`));\n }\n\n return { url, status, title, description, canonical, robots, og, twitter, jsonLd, issues };\n};\n\n/** A non-empty `issues` list fails `pagegraph inspect --live` (exit 1). */\nexport const hasBlockingIssues = (report: LiveHeadReport): boolean => report.issues.length > 0;\n","import type { AnyRoute, AnyRouter } from \"@tanstack/react-router\";\n\nimport type { RouteSeo } from \"./declare\";\n\ninterface RouteMaps {\n routesByPath: Record<string, AnyRoute | undefined>;\n routesById: Record<string, AnyRoute>;\n}\n\n/**\n * Resolve a route's declared `seo.link` card (title + description) by its full\n * path.\n *\n * `useRouter()` returns a Router typed to this app's exact route tree, so\n * `routesByPath` is keyed by the literal `FileRouteTypes[\"fullPaths\"]` union —\n * but callers here (declared `related` targets) hold arbitrary runtime path\n * strings, not that literal type. `routesByPath` and `routesById` are plain\n * Records on every Router instance regardless of which route tree it's\n * parameterized over, so this narrows to that structural shape once, at this\n * boundary, instead of threading an `AnyRoute` cast through every call site.\n */\nexport function resolveRouteLink(router: AnyRouter, path: string): RouteSeo[\"link\"] {\n const { routesByPath, routesById } = router as unknown as RouteMaps;\n\n const direct = routesByPath[path];\n if (direct) return direct.options.staticData?.seo?.link;\n\n const byFullPath = Object.values(routesById).find((route) => route.fullPath === path);\n return byFullPath?.options.staticData?.seo?.link;\n}\n"],"mappings":";;AA4FA,MAAM,gBAAyB;;;;;;AAgB/B,SAAS,SAAS,QAAgB,KAAiC;CACjE,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,IAAI,QAAQ,KAAK,OAAO;CACxB,MAAM,UAAU,IAAI,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAE1D,OAAO,GADW,WAAW,MAAM,KAAK,OAAO,GAAG,UACpC,QAAQ,WAAW,GAAG;AACtC;;AAGA,SAAS,SAAS,MAAgB,UAA8B;CAC9D,OAAO;EACL,MAAM,SAAS;EACf,OAAO,SAAS,SAAS,KAAK;EAC9B,SAAS,SAAS,WAAW,KAAK;EAClC,QAAQ,SAAS,UAAU,KAAK;EAChC,SAAS,SAAS,WAAW,KAAK;EAClC,MAAM,SAAS,QAAQ,KAAK;EAC5B,YAAY,SAAS,cAAc,KAAK;CAC1C;AACF;;;;;;AAOA,SAAS,WACP,OACA,YACA,QACA,OACA,OACA,YACM;CACN,MAAM,OAAO,SAAS,MAAM,SAAS,YAAY,MAAM,QAAQ,IAAI;CACnE,MAAM,MAAM,MAAM,QAAQ,YAAY;CAEtC,IAAI,KAAK;EACP,MAAM,WAAW,MAAM,IAAI,IAAI;EAC/B,IAAI,UAAU;GACZ,SAAS,SAAS,SAAS,SAAS,QAAQ,GAAG;GAC/C,SAAS,OAAO,SAAS,OAAO;EAClC,OACE,MAAM,IAAI,MAAM;GAAE;GAAM,MAAM,IAAI;GAAM,QAAQ;GAAS,QAAQ,EAAE,GAAG,IAAI;EAAE,CAAC;EAG/E,MAAM,uBAAuB,WAAW,WAAW,SAAS;EAC5D,IAAI,IAAI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,IAAI,CAAC,OAAO,OAAO,KAAK,kBAAkB;CAC1C,IAAI,CAAC,aAAa,OAAO,KAAK,2BAA2B;CACzD,IAAI,CAAC,WAAW,OAAO,KAAK,yBAAyB;CACrD,KAAK,MAAM,SAAS,QAClB,IAAI,CAAC,MAAM,OACT,OAAO,KAAK,GAAG,MAAM,OAAO,KAAK,UAAU,YAAY,MAAM,KAAK,KAAK,OAAO,CAAC;CAGnF,OAAO;EAAE;EAAK;EAAQ;EAAO;EAAa;EAAW;EAAQ;EAAI;EAAS;EAAQ;CAAO;AAC3F;;AAGA,MAAa,qBAAqB,WAAoC,OAAO,OAAO,SAAS;;;;;;;;;;;;;;;AClM7F,SAAgB,iBAAiB,QAAmB,MAAgC;CAClF,MAAM,EAAE,cAAc,eAAe;CAErC,MAAM,SAAS,aAAa;CAC5B,IAAI,QAAQ,OAAO,OAAO,QAAQ,YAAY,KAAK;CAGnD,OADmB,OAAO,OAAO,UAAU,CAAC,CAAC,MAAM,UAAU,MAAM,aAAa,IAChE,CAAC,EAAE,QAAQ,YAAY,KAAK;AAC9C"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/core/graph.ts","../src/core/projections.ts","../src/core/checks.ts","../src/core/link-candidates.ts","../src/core/inspect-html.ts","../src/core/resolve-route-link.ts"],"sourcesContent":["/**\n * SEO graph — the derived model that projections (sitemap, robots), the CLI, and\n * the check engine all read from. Built from route declarations (`staticData.seo`)\n * plus consumer-supplied content collections. This module is pure: no React, no\n * env, no knowledge of where instances come from. Origins and env-derived values\n * are injected by the callers of the projections, never read here.\n *\n * A node is one of:\n * - a structural route (`source: \"route\"`), keyed by its normalized full path,\n * merging a layout route's declaration (crumb) with its index child's (kind,\n * sitemap policy) when both resolve to the same URL;\n * - a content instance (`source` = the collection's label), keyed by the page URL\n * and carrying page-level metadata.\n *\n * Edges: `crumb-parent` (breadcrumb ancestry), `related` (deliberate cross-links),\n * `collection-member` (membership in a curated set), and `redirect` (route aliases).\n * The route walk emits crumb/related/redirect edges from declarations; a collection\n * may declare any additional edges its instances need.\n */\n\nimport type { AnyRoute } from \"@tanstack/react-router\";\n\nimport type { PublicPath, RouteSeo, SeoKind } from \"./declare\";\n\n/**\n * Where a node came from: `\"route\"` for a structural route declaration, or the\n * `source` label of the collection that produced the instance (e.g. \"blog\").\n */\nexport type SeoSource = string;\n\nexport interface SeoNode {\n /** Canonical path, no origin (e.g. \"/pricing\", \"/blog/my-post\"). */\n path: string;\n kind: SeoKind;\n source: SeoSource;\n /** Route-declared policy, or synthesized (kind + inherited sitemap) for instances. */\n policy: RouteSeo;\n instance?:\n | {\n title: string;\n description?: string | undefined;\n publishedAt?: string | undefined;\n modifiedAt?: string | undefined;\n }\n | undefined;\n}\n\nexport type SeoEdgeType = \"crumb-parent\" | \"related\" | \"redirect\" | \"collection-member\";\n\nexport interface SeoEdge {\n from: string;\n to: string;\n type: SeoEdgeType;\n}\n\nexport interface SeoGraph {\n nodes: Map<string, SeoNode>;\n edges: Array<SeoEdge>;\n /** Exact-path ownership conflicts encountered while assembling graph sources. */\n collisions?: ReadonlyArray<{ path: string; sources: ReadonlyArray<SeoSource> }> | undefined;\n}\n\n/** One concrete page produced by a collection. */\nexport interface SeoInstance {\n /** Canonical path of the page (e.g. \"/blog/my-post\"). */\n readonly path: string;\n readonly title: string;\n readonly description?: string | undefined;\n readonly publishedAt?: string | undefined;\n readonly modifiedAt?: string | undefined;\n}\n\nexport interface SeoCollection {\n /**\n * The param route these instances render through (e.g. \"/blog/$slug\"). Instances\n * inherit this route's declared policy (kind + sitemap) — the graph reads it from\n * the structural node, so declarations stay the single source of truth.\n */\n readonly route: PublicPath;\n /** The `source` stamped on every node this collection produces (e.g. \"blog\"). */\n readonly source: SeoSource;\n readonly instances: ReadonlyArray<SeoInstance>;\n /** Edges the collection declares between its instances and the rest of the graph. */\n readonly edges?: ReadonlyArray<SeoEdge> | undefined;\n}\n\nexport interface BuildSeoGraphInput {\n readonly routeTree: AnyRoute;\n readonly collections?: ReadonlyArray<SeoCollection> | undefined;\n}\n\n/** Kind for instances whose collection route carries no declaration to inherit. */\nconst FALLBACK_KIND: SeoKind = \"page\";\n\n/** Structural view of a route we walk — the fields present before router init(). */\ninterface WalkableRoute {\n readonly options: {\n readonly path?: string | undefined;\n readonly staticData?: { readonly seo?: RouteSeo | undefined } | undefined;\n };\n readonly children?: ReadonlyArray<WalkableRoute> | undefined;\n}\n\n/**\n * Join a child's local path onto its parent's computed full path with the same\n * semantics as TanStack's route init (relative segments, index \"/\" inherits the\n * parent, pathless/group routes are transparent), then normalize trailing slashes.\n */\nfunction joinPath(parent: string, seg: string | undefined): string {\n if (seg === undefined) return parent; // pathless layout / route group\n if (seg === \"/\") return parent; // index route resolves to its parent's URL\n const trimmed = seg.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n const joined = `${parent === \"/\" ? \"\" : parent}/${trimmed}`;\n return joined.replace(/\\/{2,}/g, \"/\");\n}\n\n/** Merge a route's declaration into an existing same-path node (deeper route wins). */\nfunction mergeSeo(base: RouteSeo, override: RouteSeo): RouteSeo {\n return {\n kind: override.kind,\n crumb: override.crumb ?? base.crumb,\n sitemap: override.sitemap ?? base.sitemap,\n robots: override.robots ?? base.robots,\n related: override.related ?? base.related,\n link: override.link ?? base.link,\n redirectTo: override.redirectTo ?? base.redirectTo,\n };\n}\n\n/**\n * Walk the route tree building structural nodes and crumb-parent edges. `crumbStack`\n * holds the paths of crumb-declaring ancestors so each crumb node links to its nearest\n * crumb ancestor down the real route-parent chain (matching render-time breadcrumbs).\n */\nfunction walkRoutes(\n route: WalkableRoute,\n parentPath: string,\n isRoot: boolean,\n nodes: Map<string, SeoNode>,\n edges: Array<SeoEdge>,\n crumbStack: Array<string>,\n): void {\n const path = isRoot ? \"/\" : joinPath(parentPath, route.options.path);\n const seo = route.options.staticData?.seo;\n\n if (seo) {\n const existing = nodes.get(path);\n if (existing) {\n existing.policy = mergeSeo(existing.policy, seo);\n existing.kind = existing.policy.kind;\n } else {\n nodes.set(path, { path, kind: seo.kind, source: \"route\", policy: { ...seo } });\n }\n\n const nearestCrumbAncestor = crumbStack[crumbStack.length - 1];\n if (seo.crumb !== undefined && nearestCrumbAncestor !== undefined) {\n edges.push({ from: path, to: nearestCrumbAncestor, type: \"crumb-parent\" });\n }\n }\n\n const pushedCrumb = seo?.crumb !== undefined;\n if (pushedCrumb) crumbStack.push(path);\n for (const child of route.children ?? []) {\n walkRoutes(child, path, false, nodes, edges, crumbStack);\n }\n if (pushedCrumb) crumbStack.pop();\n}\n\n/**\n * Add one collection's instance nodes, inheriting kind + sitemap policy from the\n * collection route's declaration, then append the edges it declares. A path already\n * owned by another node is a collision: the first owner keeps the path and the\n * conflict is reported (the `path-owner-collision` check turns it into a violation).\n */\nfunction addCollection(\n nodes: Map<string, SeoNode>,\n edges: Array<SeoEdge>,\n collisions: Array<{ path: string; sources: ReadonlyArray<SeoSource> }>,\n collection: SeoCollection,\n): void {\n const collectionNode = nodes.get(collection.route);\n const kind = collectionNode?.kind ?? FALLBACK_KIND;\n const sitemap = collectionNode?.policy.sitemap;\n\n /**\n * Paths this collection lost to an earlier owner. Their instances never enter\n * the graph, so any edge declared out of them would dangle — and the dead-edge\n * check only validates an edge's `to`, so nothing downstream would catch it.\n */\n const rejected = new Set<string>();\n\n for (const instance of collection.instances) {\n const existing = nodes.get(instance.path);\n if (existing) {\n collisions.push({ path: instance.path, sources: [existing.source, collection.source] });\n rejected.add(instance.path);\n continue;\n }\n nodes.set(instance.path, {\n path: instance.path,\n kind,\n source: collection.source,\n policy: { kind, sitemap },\n instance: {\n title: instance.title,\n description: instance.description,\n publishedAt: instance.publishedAt,\n modifiedAt: instance.modifiedAt,\n },\n });\n }\n\n for (const edge of collection.edges ?? []) {\n if (rejected.has(edge.from)) continue;\n edges.push(edge);\n }\n}\n\n/**\n * Build the SEO graph from route declarations and content collections.\n *\n * Synchronous: the caller materializes its collections before calling, so there is\n * no async work here. Callers own the origin.\n */\nexport function buildSeoGraph(input: BuildSeoGraphInput): SeoGraph {\n const nodes = new Map<string, SeoNode>();\n const edges: Array<SeoEdge> = [];\n const collisions: Array<{ path: string; sources: ReadonlyArray<SeoSource> }> = [];\n\n walkRoutes(input.routeTree as unknown as WalkableRoute, \"/\", true, nodes, edges, []);\n\n for (const collection of input.collections ?? []) {\n addCollection(nodes, edges, collisions, collection);\n }\n\n for (const node of nodes.values()) {\n if (node.source !== \"route\") continue;\n for (const to of node.policy.related ?? []) {\n edges.push({ from: node.path, to, type: \"related\" });\n }\n if (node.policy.redirectTo !== undefined) {\n edges.push({ from: node.path, to: node.policy.redirectTo, type: \"redirect\" });\n }\n }\n\n return { nodes, edges, collisions };\n}\n","/**\n * Projections of the SEO graph: sitemap.xml, robots.txt, and single-node\n * inspection. Pure functions — the origin, the host's indexability, and the\n * robots disallow list are injected by the caller, never read from the\n * environment or a generated file.\n */\n\nimport type { SeoEdge, SeoGraph, SeoNode } from \"./graph\";\n\nexport interface ProjectionConfig {\n origin: string;\n indexable: boolean;\n}\n\nexport interface RobotsConfig extends ProjectionConfig {\n /** Path prefixes to disallow on an indexable host (e.g. the app-only groups). */\n disallow: ReadonlyArray<string>;\n /**\n * Origin-wide Content-Signal preferences\n * (https://contentsignals.org/), emitted as `Content-Signal: <value>` under\n * `User-agent: *` on an indexable host. Omit for none. The plugin never\n * invents a default — pass the policy you want, e.g.\n * `\"search=yes, ai-input=yes, ai-train=yes\"`.\n */\n contentSignal?: string | undefined;\n /**\n * Extra full lines in the indexable `User-agent: *` group, after\n * Content-Signal (if any) and before Allow/Disallow. Use for directives the\n * plugin does not model, or to compose {@link contentSignal} yourself.\n */\n directives?: ReadonlyArray<string> | undefined;\n /**\n * Last-mile override: receives the rendered robots.txt and returns the file\n * to emit. Runs for indexable and preview hosts. Use when you need to wrap\n * or replace the default body rather than add group lines.\n */\n transform?: ((robots: string) => string) | undefined;\n}\n\nexport interface NodeReport {\n node: SeoNode;\n inSitemap: boolean;\n incoming: Array<SeoEdge>;\n outgoing: Array<SeoEdge>;\n}\n\nconst escapeXml = (value: string): string =>\n value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n\n/**\n * A node belongs in the sitemap when it declares a positive sitemap policy, is not\n * a redirect, is not robots-noindexed, and is not a param template (a route whose\n * path still contains a `$` segment — those exist only so their instances inherit).\n */\nexport function isSitemapEligible(node: SeoNode): boolean {\n if (node.policy.redirectTo !== undefined) return false;\n if (node.policy.robots?.includes(\"noindex\")) return false;\n if (!node.policy.sitemap) return false; // false or absent\n if (node.path.includes(\"$\")) return false;\n return true;\n}\n\n/** Canonical absolute URL for a node under the given origin. */\nfunction urlForNode(origin: string, node: SeoNode): string {\n return node.path === \"/\" ? origin : `${origin}${node.path}`;\n}\n\n/**\n * Instance lastmod: the most recent date the page's frontmatter carries. A\n * collection whose instances carry no dates (docs, a manifest-driven gallery)\n * emits no `<lastmod>` at all.\n */\nfunction instanceLastmod(node: SeoNode): string | undefined {\n const instance = node.instance;\n if (!instance) return undefined;\n const date = instance.modifiedAt ?? instance.publishedAt;\n return date ? new Date(date).toISOString() : undefined;\n}\n\nfunction renderUrlEntry(url: string, lastmod: string | undefined, node: SeoNode): string {\n const sitemap = node.policy.sitemap;\n // isSitemapEligible guarantees a positive policy before this runs.\n const { changeFrequency, priority } = sitemap as { changeFrequency: string; priority: number };\n const lines = [` <url>`, ` <loc>${escapeXml(url)}</loc>`];\n if (lastmod) lines.push(` <lastmod>${lastmod}</lastmod>`);\n lines.push(\n ` <changefreq>${changeFrequency}</changefreq>`,\n ` <priority>${priority.toFixed(1)}</priority>`,\n ` </url>`,\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Render sitemap.xml from the graph. Structural route entries emit no `<lastmod>`\n * (a route has no publish date); content instances emit it from their frontmatter.\n * Route entries are sorted by path, then instances follow in collection order.\n * `indexable` is intentionally unused — the sitemap body is host-independent;\n * robots.txt is what gates crawling.\n */\nexport function renderSitemap(graph: SeoGraph, cfg: ProjectionConfig): string {\n const nodes = [...graph.nodes.values()];\n const staticNodes = nodes\n .filter((node) => node.source === \"route\" && isSitemapEligible(node))\n .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n const instanceNodes = nodes.filter((node) => node.source !== \"route\" && isSitemapEligible(node));\n\n const seen = new Set<string>();\n const entries: Array<string> = [];\n for (const node of [...staticNodes, ...instanceNodes]) {\n const url = urlForNode(cfg.origin, node);\n const key = url.toLowerCase().replace(/\\/$/, \"\");\n if (seen.has(key)) continue;\n seen.add(key);\n entries.push(renderUrlEntry(url, instanceLastmod(node), node));\n }\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\\n${entries.join(\n \"\\n\",\n )}\\n</urlset>\\n`;\n}\n\n/** Format a Content-Signal robots.txt directive from the preference list. */\nexport function contentSignal(value: string): string {\n return `Content-Signal: ${value}`;\n}\n\nconst groupLines = (cfg: RobotsConfig): Array<string> => {\n const lines: Array<string> = [];\n if (cfg.contentSignal !== undefined && cfg.contentSignal !== \"\") {\n lines.push(contentSignal(cfg.contentSignal));\n }\n for (const directive of cfg.directives ?? []) {\n if (directive !== \"\") lines.push(directive);\n }\n return lines;\n};\n\n/**\n * Render robots.txt. A non-indexable host (previews) gets a disallow-all\n * with no Sitemap line; an indexable host disallows exactly the prefixes the caller\n * passes. Pages that declare `robots: noindex` are intentionally NOT added as\n * Disallow entries — a Disallow would stop crawlers reaching the page to read its\n * `noindex, follow` meta, so the graph's per-node robots policy never feeds this\n * list. `graph` is unused — kept for signature parity with the other projections,\n * which callers load the graph once for and pass to each.\n *\n * Origin-wide group directives (`contentSignal`, `directives`) are indexable-host\n * only. {@link RobotsConfig.transform} always runs last so a consumer can override\n * the whole file.\n */\nexport function renderRobots(_graph: SeoGraph, cfg: RobotsConfig): string {\n const rendered = cfg.indexable\n ? [\n \"User-agent: *\",\n ...groupLines(cfg),\n \"Allow: /\",\n ...cfg.disallow.map((path) => `Disallow: ${path}`),\n \"\",\n `Sitemap: ${cfg.origin}/sitemap.xml`,\n `Host: ${cfg.origin}`,\n \"\",\n ].join(\"\\n\")\n : [\"User-agent: *\", \"Disallow: /\", \"\"].join(\"\\n\");\n return cfg.transform === undefined ? rendered : cfg.transform(rendered);\n}\n\n/** Inspect a single node: its declaration, sitemap eligibility, and edges. */\nexport function inspectNode(graph: SeoGraph, path: string): NodeReport | undefined {\n const node = graph.nodes.get(path);\n if (!node) return undefined;\n return {\n node,\n inSitemap: isSitemapEligible(node),\n incoming: graph.edges.filter((edge) => edge.to === path),\n outgoing: graph.edges.filter((edge) => edge.from === path),\n };\n}\n","/**\n * The SEO check engine: a set of rules run against the derived {@link SeoGraph}.\n * Pure — no I/O, no `clientEnv`, no React. The CLI's `pagegraph check` command and the\n * vitest suite both call {@link checkGraph}; nothing else derives correctness.\n *\n * Two severities, mapped to the CLI's exit contract:\n * - `structural` — a declaration is internally broken (a link points nowhere, a\n * card would render empty, a page contradicts its own robots/sitemap intent).\n * Any structural violation fails `pagegraph check` (exit 1); these must not ship.\n * - `editorial` — a quality smell (duplicate or mis-sized titles/descriptions).\n * Reported as warnings; `pagegraph check` still exits 0 when only these are present.\n *\n * The graph only knows what declarations and frontmatter carry, so the rules are\n * scoped to that: per-node title/description live only on collection *instances*,\n * never on structural route nodes (whose head tags are composed at render time and\n * are not in the graph). Rules are data-driven and listed once in\n * {@link CHECK_RULES}.\n */\n\nimport type { SitemapPolicy } from \"./declare\";\nimport type { SeoGraph, SeoNode } from \"./graph\";\nimport { isSitemapEligible } from \"./projections\";\n\nexport type Severity = \"structural\" | \"editorial\";\n\nexport interface Violation {\n severity: Severity;\n rule: string;\n path?: string | undefined;\n message: string;\n fix?: string | undefined;\n}\n\n/**\n * A contextual-link coverage rule: every sitemap-eligible page matching the\n * `path` glob must have at least `minInbound` incoming `related` edges. Unlike\n * the static rules, these come from project policy (a CLI flag or\n * `seo.config.ts`), because \"which pages are money pages\" is app knowledge.\n */\nexport interface CoverageRule {\n /** Path glob: `*` matches within a segment, `**` matches across segments. */\n readonly path: string;\n /** Minimum incoming contextual (`related`) edges the matched page needs. */\n readonly minInbound: number;\n}\n\n/** A single finding before its rule's `severity`/`rule` name are attached. */\ninterface RawViolation {\n path?: string | undefined;\n message: string;\n fix?: string | undefined;\n}\n\ninterface CheckRule {\n readonly name: string;\n readonly severity: Severity;\n readonly evaluate: (graph: SeoGraph) => ReadonlyArray<RawViolation>;\n}\n\n/** A positive sitemap policy — the author asked for this page to be indexed. */\nconst hasPositiveSitemap = (sitemap: SitemapPolicy | false | undefined): sitemap is SitemapPolicy =>\n sitemap !== undefined && sitemap !== false;\n\n/** Content and manifest instances carry page-level title/description. */\nconst isInstance = (node: SeoNode): boolean => node.source !== \"route\";\n\n/** Group instance nodes by a present, non-empty string field for duplicate detection. */\nconst groupInstancesBy = (\n graph: SeoGraph,\n field: (node: SeoNode) => string | undefined,\n): Map<string, Array<SeoNode>> => {\n const groups = new Map<string, Array<SeoNode>>();\n for (const node of graph.nodes.values()) {\n if (!isInstance(node)) continue;\n const value = field(node)?.trim();\n if (!value) continue;\n const bucket = groups.get(value);\n if (bucket) bucket.push(node);\n else groups.set(value, [node]);\n }\n return groups;\n};\n\nconst DESCRIPTION_MAX = 160;\nconst DESCRIPTION_MIN = 50;\n\n/**\n * Every check, in one place. `checkGraph` runs them in order and stamps each\n * finding with its rule name and severity, so the output is grouped by rule and\n * deterministic (nodes iterate in graph insertion order, edges in array order).\n */\nconst CHECK_RULES: ReadonlyArray<CheckRule> = [\n {\n name: \"path-owner-collision\",\n severity: \"structural\",\n evaluate: (graph) =>\n (graph.collisions ?? []).map((collision) => ({\n path: collision.path,\n message: `Canonical path \"${collision.path}\" is owned by multiple sources: ${collision.sources.join(\", \")}.`,\n fix: \"Give every concrete page one canonical path and one graph owner.\",\n })),\n },\n {\n name: \"canonical-path-collision\",\n severity: \"structural\",\n evaluate: (graph) => {\n const groups = new Map<string, Array<string>>();\n for (const path of graph.nodes.keys()) {\n const canonical = path.toLowerCase().replace(/\\/$/, \"\") || \"/\";\n const paths = groups.get(canonical);\n if (paths) paths.push(path);\n else groups.set(canonical, [path]);\n }\n return [...groups.values()]\n .filter((paths) => paths.length > 1)\n .flatMap((paths) =>\n paths.map((path) => ({\n path,\n message: `Canonical path collides with ${paths.filter((candidate) => candidate !== path).join(\", \")}.`,\n fix: \"Use one lowercase, trailing-slash-normalized canonical path.\",\n })),\n );\n },\n },\n {\n name: \"self-edge\",\n severity: \"structural\",\n evaluate: (graph) =>\n graph.edges\n .filter((edge) => edge.from === edge.to)\n .map((edge) => ({\n path: edge.from,\n message: `${edge.type} edge points back to its own source node.`,\n fix: \"Remove the self-reference from the canonical manifest or route declaration.\",\n })),\n },\n {\n name: \"duplicate-edge\",\n severity: \"structural\",\n evaluate: (graph) => {\n const seen = new Set<string>();\n const duplicates: Array<RawViolation> = [];\n for (const edge of graph.edges) {\n const key = `${edge.from}\\u0000${edge.to}\\u0000${edge.type}`;\n if (seen.has(key)) {\n duplicates.push({\n path: edge.from,\n message: `Duplicate ${edge.type} edge from \"${edge.from}\" to \"${edge.to}\".`,\n fix: \"Declare each graph relationship exactly once.\",\n });\n } else {\n seen.add(key);\n }\n }\n return duplicates;\n },\n },\n {\n // A `related` or `redirect` edge points at a path with no node — the target\n // route/page was renamed or deleted and the declaration wasn't updated.\n name: \"dead-edge\",\n severity: \"structural\",\n evaluate: (graph) =>\n graph.edges\n .filter((edge) => edge.type !== \"crumb-parent\" && !graph.nodes.has(edge.to))\n .map((edge) => ({\n path: edge.from,\n message: `${edge.type} edge from \"${edge.from}\" points at \"${edge.to}\", which is not a node in the graph.`,\n fix: `Update the ${edge.type === \"redirect\" ? \"redirectTo\" : \"related\"} target on the \"${edge.from}\" route, or restore \"${edge.to}\".`,\n })),\n },\n {\n // A content instance with no usable title can't render a legible <title> or card.\n name: \"instance-missing-title\",\n severity: \"structural\",\n evaluate: (graph) =>\n [...graph.nodes.values()]\n .filter((node) => isInstance(node) && !node.instance?.title.trim())\n .map((node) => ({\n path: node.path,\n message: `Content page \"${node.path}\" has no title.`,\n fix: \"Add a `title` to the page frontmatter.\",\n })),\n },\n {\n // The declaration asks for the page to be in the sitemap yet also marks it\n // noindex — contradictory intent. The projection resolves it (noindex wins,\n // excluded), but the declaration should say one thing.\n name: \"sitemap-noindex-contradiction\",\n severity: \"structural\",\n evaluate: (graph) =>\n [...graph.nodes.values()]\n .filter(\n (node) =>\n hasPositiveSitemap(node.policy.sitemap) &&\n node.policy.robots?.toLowerCase().includes(\"noindex\"),\n )\n .map((node) => ({\n path: node.path,\n message: `\"${node.path}\" declares a sitemap policy but its robots value is \"${node.policy.robots}\".`,\n fix: \"Drop the sitemap policy (or set `sitemap: false`) on a noindex page, or remove the noindex robots value.\",\n })),\n },\n {\n // Robots declarations are house-convention lowercase: the sitemap projection\n // matches `includes(\"noindex\")` literally, so a miscased value (\"Noindex\")\n // would silently stay sitemap-eligible. This gate makes that unrepresentable.\n name: \"robots-not-lowercase\",\n severity: \"structural\",\n evaluate: (graph) =>\n [...graph.nodes.values()]\n .filter(\n (node) =>\n node.policy.robots !== undefined &&\n node.policy.robots !== node.policy.robots.toLowerCase(),\n )\n .map((node) => ({\n path: node.path,\n message: `\"${node.path}\" declares robots \"${node.policy.robots}\" — robots values must be lowercase.`,\n fix: 'Lowercase the robots declaration (e.g. \"noindex, follow\").',\n })),\n },\n {\n // A `related` card for a route target renders from that route's `link`\n // metadata; without it the card has no title/description and renders empty.\n // (Content-instance targets render from their frontmatter, so they're exempt.)\n name: \"related-target-missing-link\",\n severity: \"structural\",\n evaluate: (graph) => {\n const linklessTargets = new Set<string>();\n for (const edge of graph.edges) {\n if (edge.type !== \"related\") continue;\n const target = graph.nodes.get(edge.to);\n if (target && target.source === \"route\" && target.policy.link === undefined) {\n linklessTargets.add(edge.to);\n }\n }\n return [...linklessTargets].map((path) => ({\n path,\n message: `Route \"${path}\" is a related-link target but declares no link metadata; its card would render empty.`,\n fix: `Add \\`link: { title, description }\\` to the \"${path}\" route's staticData.seo.`,\n }));\n },\n },\n {\n // A redirect/alias node should never advertise itself in the sitemap.\n name: \"redirect-in-sitemap\",\n severity: \"structural\",\n evaluate: (graph) =>\n [...graph.nodes.values()]\n .filter(\n (node) => node.policy.redirectTo !== undefined && hasPositiveSitemap(node.policy.sitemap),\n )\n .map((node) => ({\n path: node.path,\n message: `Redirect \"${node.path}\" (→ \"${node.policy.redirectTo}\") also declares a sitemap policy.`,\n fix: \"Remove the sitemap policy from the redirect route; only its target belongs in the sitemap.\",\n })),\n },\n {\n name: \"duplicate-title\",\n severity: \"editorial\",\n evaluate: (graph) =>\n [...groupInstancesBy(graph, (node) => node.instance?.title).entries()]\n .filter(([, nodes]) => nodes.length > 1)\n .flatMap(([title, nodes]) =>\n nodes.map((node) => ({\n path: node.path,\n message: `Title \"${title}\" is shared by ${nodes.length} pages.`,\n fix: \"Give each page a distinct title.\",\n })),\n ),\n },\n {\n name: \"duplicate-description\",\n severity: \"editorial\",\n evaluate: (graph) =>\n [...groupInstancesBy(graph, (node) => node.instance?.description).entries()]\n .filter(([, nodes]) => nodes.length > 1)\n .flatMap(([, nodes]) =>\n nodes.map((node) => ({\n path: node.path,\n message: `Description is shared by ${nodes.length} pages.`,\n fix: \"Write a distinct meta description for each page.\",\n })),\n ),\n },\n {\n // Meta descriptions outside ~50–160 chars either get truncated in SERPs or\n // read as too thin.\n name: \"description-length\",\n severity: \"editorial\",\n evaluate: (graph) =>\n [...graph.nodes.values()].flatMap((node) => {\n if (!isInstance(node)) return [];\n const description = node.instance?.description?.trim();\n if (!description) return [];\n if (description.length > DESCRIPTION_MAX) {\n return [\n {\n path: node.path,\n message: `Description is ${description.length} chars (max ${DESCRIPTION_MAX}); it will be truncated in results.`,\n fix: `Trim the description to ${DESCRIPTION_MAX} characters or fewer.`,\n },\n ];\n }\n if (description.length < DESCRIPTION_MIN) {\n return [\n {\n path: node.path,\n message: `Description is ${description.length} chars (min ${DESCRIPTION_MIN}); it reads as thin.`,\n fix: `Expand the description to at least ${DESCRIPTION_MIN} characters.`,\n },\n ];\n }\n return [];\n }),\n },\n];\n\n/**\n * Run every static rule against the graph, then any caller-supplied\n * {@link CoverageRule}s, and return the flat list of violations. With no\n * `coverage` option the result is exactly the static rule set.\n */\nexport function checkGraph(\n graph: SeoGraph,\n options: { readonly coverage?: ReadonlyArray<CoverageRule> | undefined } = {},\n): Array<Violation> {\n const violations: Array<Violation> = CHECK_RULES.flatMap((rule) =>\n rule.evaluate(graph).map((raw): Violation => ({\n severity: rule.severity,\n rule: rule.name,\n path: raw.path,\n message: raw.message,\n fix: raw.fix,\n })),\n );\n const coverage = options.coverage;\n if (coverage !== undefined && coverage.length > 0) {\n violations.push(...checkCoverage(graph, coverage));\n }\n return violations;\n}\n\n/** Escape a glob for `RegExp`, then expand `**`, `*`, and `?` to path-aware forms. */\nconst globToRegExp = (glob: string): RegExp => {\n const escaped = glob.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const source = escaped\n .replace(/\\*\\*/g, \"\\u0000\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/\\u0000/g, \".*\");\n return new RegExp(`^${source}$`);\n};\n\n/**\n * Enforce contextual-link coverage rules: a named set of sitemap-eligible\n * \"money\" pages each needs `minInbound` incoming `related` edges. Only\n * `related` edges count — breadcrumb ancestry is navigation, not context.\n *\n * A rule that matches no sitemap-eligible page is itself a violation: a typo or\n * a rule aimed at a noindex page would otherwise pass silently forever.\n */\nexport function checkCoverage(\n graph: SeoGraph,\n rules: ReadonlyArray<CoverageRule>,\n): Array<Violation> {\n const violations: Array<Violation> = [];\n for (const rule of rules) {\n const matcher = globToRegExp(rule.path);\n const matched = [...graph.nodes.values()].filter((node) => matcher.test(node.path));\n const eligible = matched.filter(isSitemapEligible);\n\n if (eligible.length === 0) {\n violations.push({\n severity: \"structural\",\n rule: \"coverage-rule-unmatched\",\n message:\n matched.length === 0\n ? `Coverage rule \"${rule.path}\" matches no page in the graph.`\n : `Coverage rule \"${rule.path}\" matches only pages that are not sitemap-eligible.`,\n fix: \"Point the rule at a sitemap-eligible path, or drop it.\",\n });\n continue;\n }\n\n for (const node of eligible) {\n const inbound = graph.edges.filter(\n (edge) => edge.type === \"related\" && edge.to === node.path,\n ).length;\n if (inbound >= rule.minInbound) continue;\n violations.push({\n severity: \"structural\",\n rule: \"inbound-link-coverage\",\n path: node.path,\n message: `\"${node.path}\" has ${inbound} incoming contextual link(s); the coverage rule requires ${rule.minInbound}.`,\n fix: `Add ${rule.minInbound - inbound} contextual (related) edge(s) pointing at \"${node.path}\".`,\n });\n }\n }\n return violations;\n}\n\n/** Structural violations fail `pagegraph check`; editorial-only stays green. */\nexport const hasStructuralViolations = (violations: ReadonlyArray<Violation>): boolean =>\n violations.some((violation) => violation.severity === \"structural\");\n","/**\n * Pure candidate generation for contextual cross-links.\n *\n * Given the declared graph, enumerate `(source, destination)` pairs that are\n * *plausible* contextual links and *not already connected*. A pair is plausible\n * when the two pages sit in the same cluster: a shared top-level section (e.g.\n * `/blog/a` and `/blog/b` under `/blog`) or, for root-level pages that share no\n * section, the same `kind`. Only sitemap-eligible pages are candidates — a\n * noindex, redirect, or param template is not a link surface.\n *\n * The plan is a proposal, never an application: nothing here writes a\n * declaration. Effect- and framework-free so it runs in the CLI, a Worker, or a\n * test on the same graph.\n */\n\nimport type { SeoGraph, SeoNode } from \"./graph\";\nimport type { SimpleEdge } from \"./links\";\nimport { isSitemapEligible } from \"./projections\";\n\n/** One proposed contextual link, in the direction the link would be authored. */\nexport interface LinkCandidatePair {\n readonly source: string;\n readonly destination: string;\n /** The cluster the pair shares: a top-level section, or `kind:<kind>`. */\n readonly cluster: string;\n /** Why the pair is plausible, e.g. `same top-level section \"/blog\"`. */\n readonly reason: string;\n}\n\nexport interface LinkCandidateOptions {\n /** Maximum candidates to return after ordering (default 50). */\n readonly limit?: number;\n /** Restrict to these clusters; a filter may be a section or a bare kind. */\n readonly clusters?: ReadonlyArray<string>;\n /** Anchors already served in HTML; their pairs are excluded when supplied. */\n readonly renderedEdges?: ReadonlyArray<SimpleEdge>;\n}\n\n/** One cluster and how many candidate pairs it contributes (before `limit`). */\nexport interface LinkClusterSummary {\n readonly key: string;\n readonly candidates: number;\n}\n\nexport interface LinkCandidateResult {\n readonly candidates: ReadonlyArray<LinkCandidatePair>;\n /** Candidate pairs before `limit` was applied (after cluster filters). */\n readonly total: number;\n readonly truncated: boolean;\n readonly clusters: ReadonlyArray<LinkClusterSummary>;\n}\n\n/**\n * Canonical path key: query and hash stripped, trailing slashes removed, \"/\"\n * preserved. This is the same path key the graph and the rendered-link core\n * use, so a served anchor like `/blog/a?ref=nav` still matches the graph pair\n * `/blog/a`.\n */\nconst normalize = (path: string): string => {\n const pathname = path.split(/[?#]/, 1)[0] ?? \"\";\n const trimmed = pathname.replace(/\\/+$/, \"\");\n return trimmed === \"\" ? \"/\" : trimmed;\n};\n\n/** Directionless pair key, so an edge in either direction means \"connected\". */\nexport const undirectedEdgeKey = (from: string, to: string): string => {\n const [a, b] = [normalize(from), normalize(to)].sort();\n return `${a}\\u0000${b}`;\n};\n\n/** First path segment, or undefined for the root page. */\nconst topSegment = (path: string): string | undefined => {\n const segment = path.split(\"/\").filter(Boolean)[0];\n return segment === undefined || segment === \"\" ? undefined : segment;\n};\n\n/** A page with no nested segment (`/`, `/pricing`, `/blog`) is root-level. */\nconst isRootLevel = (path: string): boolean => path.split(\"/\").filter(Boolean).length <= 1;\n\n/**\n * The cluster a pair shares, or undefined when they share none. Section-first:\n * a shared top-level section wins. The kind fallback is local to root-level\n * pages, so it never pairs two nested pages from different sections.\n */\nconst clusterOf = (a: SeoNode, b: SeoNode): { key: string; reason: string } | undefined => {\n const aSegment = topSegment(a.path);\n const bSegment = topSegment(b.path);\n if (aSegment !== undefined && aSegment === bSegment) {\n return { key: aSegment, reason: `same top-level section \"/${aSegment}\"` };\n }\n if (isRootLevel(a.path) && isRootLevel(b.path) && a.kind === b.kind) {\n return { key: `kind:${a.kind}`, reason: `same kind \"${a.kind}\"` };\n }\n return undefined;\n};\n\n/** A `--cluster` filter matches a section by name, or a kind via its bare label. */\nexport const matchesClusterFilter = (cluster: string, filter: string): boolean => {\n const normalized = filter.replace(/^\\/+/, \"\").toLowerCase();\n const key = cluster.toLowerCase();\n return key === normalized || key === `kind:${normalized}`;\n};\n\n/** Human reason string for a candidate's source page, used when handing a plan to Jev. */\nexport const candidateSourceText = (node: SeoNode): string =>\n node.instance?.description?.trim() ||\n node.instance?.title?.trim() ||\n node.policy.link?.description?.trim() ||\n node.policy.link?.title?.trim() ||\n node.path;\n\n/**\n * Enumerate reviewable contextual-link candidates from the declared graph.\n *\n * Excluded: self-pairs, pages that are not sitemap-eligible, pairs already\n * declared as a `related` edge, and — when {@link LinkCandidateOptions.renderedEdges}\n * is supplied — pairs already rendered as an anchor. Queries, hashes, and\n * trailing slashes are normalized so both sides compare by the graph's path key.\n */\nexport const generateLinkCandidates = (\n graph: SeoGraph,\n options: LinkCandidateOptions = {},\n): LinkCandidateResult => {\n const limit = options.limit ?? 50;\n const filters = options.clusters ?? [];\n const rendered = new Set(\n (options.renderedEdges ?? []).map((edge) => undirectedEdgeKey(edge.from, edge.to)),\n );\n const declared = new Set(\n graph.edges\n .filter((edge) => edge.type === \"related\")\n .map((edge) => undirectedEdgeKey(edge.from, edge.to)),\n );\n\n const eligible = [...graph.nodes.values()].filter(isSitemapEligible);\n\n const all: Array<LinkCandidatePair> = [];\n for (let i = 0; i < eligible.length; i++) {\n for (let j = i + 1; j < eligible.length; j++) {\n const a = eligible[i]!;\n const b = eligible[j]!;\n const cluster = clusterOf(a, b);\n if (cluster === undefined) continue;\n if (filters.length > 0 && !filters.some((filter) => matchesClusterFilter(cluster.key, filter))) {\n continue;\n }\n const key = undirectedEdgeKey(a.path, b.path);\n if (declared.has(key) || rendered.has(key)) continue;\n all.push({ source: a.path, destination: b.path, cluster: cluster.key, reason: cluster.reason });\n all.push({ source: b.path, destination: a.path, cluster: cluster.key, reason: cluster.reason });\n }\n }\n\n const compare = (x: LinkCandidatePair, y: LinkCandidatePair): number =>\n x.cluster < y.cluster\n ? -1\n : x.cluster > y.cluster\n ? 1\n : x.source < y.source\n ? -1\n : x.source > y.source\n ? 1\n : x.destination < y.destination\n ? -1\n : x.destination > y.destination\n ? 1\n : 0;\n all.sort(compare);\n\n const counts = new Map<string, number>();\n for (const pair of all) counts.set(pair.cluster, (counts.get(pair.cluster) ?? 0) + 1);\n\n const candidates = all.slice(0, limit);\n return {\n candidates,\n total: all.length,\n truncated: all.length > candidates.length,\n clusters: [...counts.entries()].map(([key, count]) => ({ key, candidates: count })),\n };\n};\n\n/**\n * Decode a rendered-edge dump supplied to the CLI: either a bare array of\n * `{ from, to }` edges, or an object carrying `edges` (or `internalEdges`).\n * Throws on any other shape — this is user input, not a provider payload.\n */\nexport const decodeRenderedEdges = (input: unknown): ReadonlyArray<SimpleEdge> => {\n const array =\n Array.isArray(input)\n ? input\n : input !== null && typeof input === \"object\" && Array.isArray((input as { edges?: unknown }).edges)\n ? (input as { edges: ReadonlyArray<unknown> }).edges\n : input !== null &&\n typeof input === \"object\" &&\n Array.isArray((input as { internalEdges?: unknown }).internalEdges)\n ? (input as { internalEdges: ReadonlyArray<unknown> }).internalEdges\n : undefined;\n\n if (array === undefined) {\n throw new Error(\n \"expected an array of { from, to } edges, or an object with an `edges` array\",\n );\n }\n\n return array.map((item) => {\n if (item === null || typeof item !== \"object\") {\n throw new Error(\"each rendered edge must be an object with string `from` and `to`\");\n }\n const { from, to } = item as { from?: unknown; to?: unknown };\n if (typeof from !== \"string\" || typeof to !== \"string\") {\n throw new Error(\"each rendered edge must have string `from` and `to`\");\n }\n return { from, to };\n });\n};\n","/**\n * Read a rendered `<head>` and validate it: title, meta\n * (description/robots/og/twitter), canonical link, and `application/ld+json`\n * blocks, with a minimal per-type JSON-LD check.\n *\n * This is the pure half of `pagegraph inspect --live` — the half worth having on its\n * own. The CLI fetches a URL and hands the body here; a test suite can render a\n * page and hand *that* here, asserting the head it actually ships. Both get the\n * same verdict, because it is the same function.\n *\n * No HTML-parsing dependency, by design: a `<head>` is small and well-formed, so\n * string/regex scanning is enough, and the package's core stays zero-dependency\n * (which is also why the object guard below is hand-rolled — `effect/Predicate`\n * is not reachable from this entry). It is honest about its limits: it does not\n * build a DOM, so exotic markup (commented-out tags, CDATA, attributes spanning\n * constructs) is out of scope. This validates *rendered output*, not arbitrary\n * HTML.\n *\n * `issues` are blocking: a non-empty list makes `pagegraph inspect --live` exit 1.\n * Required tags are `<title>`, `meta[name=description]`, and\n * `link[rel=canonical]`; any JSON-LD that fails to parse or fails its minimal\n * schema is also blocking.\n */\n\nexport interface JsonLdReport {\n type: string;\n valid: boolean;\n errors: Array<string>;\n}\n\nexport interface LiveHeadReport {\n url: string;\n status: number;\n title?: string | undefined;\n description?: string | undefined;\n canonical?: string | undefined;\n robots?: string | undefined;\n og: Record<string, string>;\n twitter: Record<string, string>;\n jsonLd: Array<JsonLdReport>;\n issues: Array<string>;\n}\n\nconst ENTITIES: Record<string, string> = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n \""\": '\"',\n \"'\": \"'\",\n \"'\": \"'\",\n};\n\nconst decodeEntities = (value: string): string =>\n value.replace(/&(?:amp|lt|gt|quot|#39|apos);/g, (match) => ENTITIES[match] ?? match);\n\n/** Pull double/single-quoted attributes off a single tag string. */\nconst parseAttrs = (tag: string): Record<string, string> => {\n const attrs: Record<string, string> = {};\n const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(tag)) !== null) {\n attrs[match[1]!.toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? \"\");\n }\n return attrs;\n};\n\n/** Normalize a JSON-LD `@type` (string or array) to a single readable label. */\nconst typeName = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value))\n return value.filter((v) => typeof v === \"string\").join(\", \") || \"unknown\";\n return \"unknown\";\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n // NOTE: This zero-dependency core entry cannot import Effect; JSON-LD validation happens immediately after this shallow narrowing.\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** Flatten a parsed JSON-LD payload (single object, array, or `@graph`) to items. */\nconst collectItems = (parsed: unknown): Array<Record<string, unknown>> => {\n if (Array.isArray(parsed)) return parsed.filter(isObject);\n if (isObject(parsed)) {\n if (Array.isArray(parsed[\"@graph\"])) return parsed[\"@graph\"].filter(isObject);\n return [parsed];\n }\n return [];\n};\n\nconst countQuestions = (mainEntity: unknown): number => {\n if (!Array.isArray(mainEntity)) return 0;\n return mainEntity.filter((entry) => isObject(entry) && typeName(entry[\"@type\"]) === \"Question\")\n .length;\n};\n\nconst validateItemListElements = (value: unknown): Array<string> => {\n if (!Array.isArray(value) || value.length < 1) {\n return [\"ItemList needs at least one `itemListElement` entry.\"];\n }\n const errors: Array<string> = [];\n value.forEach((entry, index) => {\n if (!isObject(entry) || typeName(entry[\"@type\"]) !== \"ListItem\") {\n errors.push(`ItemList entry ${index + 1} is not a ListItem.`);\n return;\n }\n if (entry[\"position\"] !== index + 1) {\n errors.push(`ItemList entry ${index + 1} has an invalid position.`);\n }\n if (!entry[\"name\"] || !entry[\"url\"]) {\n errors.push(`ItemList entry ${index + 1} needs a name and URL.`);\n }\n });\n return errors;\n};\n\n/** Minimal per-type validation — enough to catch an empty or malformed block. */\nconst validateItem = (item: Record<string, unknown>): JsonLdReport => {\n const type = typeName(item[\"@type\"]);\n const errors: Array<string> = [];\n\n if (type === \"Article\" || type === \"NewsArticle\" || type === \"BlogPosting\") {\n if (!item[\"headline\"]) errors.push(\"Article is missing `headline`.\");\n if (!item[\"datePublished\"]) errors.push(\"Article is missing `datePublished`.\");\n } else if (type === \"FAQPage\") {\n if (countQuestions(item[\"mainEntity\"]) < 1) {\n errors.push(\"FAQPage needs at least one Question in `mainEntity`.\");\n }\n } else if (type === \"BreadcrumbList\") {\n const items = item[\"itemListElement\"];\n if (!Array.isArray(items) || items.length < 2) {\n errors.push(\"BreadcrumbList needs at least two `itemListElement` entries.\");\n }\n } else if (type === \"ItemList\") {\n errors.push(...validateItemListElements(item[\"itemListElement\"]));\n const items = item[\"itemListElement\"];\n if (Array.isArray(items) && item[\"numberOfItems\"] !== items.length) {\n errors.push(\"ItemList `numberOfItems` does not match its entries.\");\n }\n }\n\n return { type, valid: errors.length === 0, errors };\n};\n\nconst validateLdJson = (raw: string): Array<JsonLdReport> => {\n let parsed: unknown;\n // NOTE: JSON.parse boundary: converts the native parse throw into an unparseable JsonLdReport value in a pure sync validator\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n return [\n {\n type: \"unparseable\",\n valid: false,\n errors: [`JSON parse error: ${cause instanceof Error ? cause.message : String(cause)}`],\n },\n ];\n }\n const items = collectItems(parsed);\n if (items.length === 0) {\n return [{ type: \"unknown\", valid: false, errors: [\"No JSON-LD object found in block.\"] }];\n }\n return items.map(validateItem);\n};\n\n/** Parse a rendered HTML document's `<head>` into a report. Pure. */\nexport const inspectHtml = (url: string, status: number, html: string): LiveHeadReport => {\n const headMatch = html.match(/<head[^>]*>([\\s\\S]*?)<\\/head>/i);\n const head = headMatch ? headMatch[1]! : html;\n\n const titleMatch = head.match(/<title[^>]*>([\\s\\S]*?)<\\/title>/i);\n const title = titleMatch ? decodeEntities(titleMatch[1]!.trim()) : undefined;\n\n const og: Record<string, string> = {};\n const twitter: Record<string, string> = {};\n let description: string | undefined;\n let robots: string | undefined;\n\n for (const tag of head.match(/<meta\\b[^>]*>/gi) ?? []) {\n const attrs = parseAttrs(tag);\n const content = attrs[\"content\"];\n if (content === undefined) continue;\n const property = attrs[\"property\"];\n const name = attrs[\"name\"];\n if (property?.startsWith(\"og:\")) og[property] = content;\n else if (name?.startsWith(\"twitter:\")) twitter[name] = content;\n else if (name === \"description\") description = content;\n else if (name === \"robots\") robots = content;\n }\n\n let canonical: string | undefined;\n for (const tag of head.match(/<link\\b[^>]*>/gi) ?? []) {\n const attrs = parseAttrs(tag);\n if (attrs[\"rel\"] === \"canonical\") canonical = attrs[\"href\"];\n }\n\n const jsonLd: Array<JsonLdReport> = [];\n const scriptRe = /<script\\b[^>]*type=[\"']application\\/ld\\+json[\"'][^>]*>([\\s\\S]*?)<\\/script>/gi;\n let scriptMatch: RegExpExecArray | null;\n while ((scriptMatch = scriptRe.exec(head)) !== null) {\n jsonLd.push(...validateLdJson(scriptMatch[1]!.trim()));\n }\n\n const issues: Array<string> = [];\n if (status >= 400) issues.push(`Fetch returned HTTP ${status}.`);\n if (!title) issues.push(\"Missing <title>.\");\n if (!description) issues.push(\"Missing meta description.\");\n if (!canonical) issues.push(\"Missing canonical link.\");\n for (const block of jsonLd) {\n if (!block.valid)\n issues.push(...block.errors.map((error) => `JSON-LD (${block.type}): ${error}`));\n }\n\n return { url, status, title, description, canonical, robots, og, twitter, jsonLd, issues };\n};\n\n/** A non-empty `issues` list fails `pagegraph inspect --live` (exit 1). */\nexport const hasBlockingIssues = (report: LiveHeadReport): boolean => report.issues.length > 0;\n","import type { AnyRoute, AnyRouter } from \"@tanstack/react-router\";\n\nimport type { RouteSeo } from \"./declare\";\n\ninterface RouteMaps {\n routesByPath: Record<string, AnyRoute | undefined>;\n routesById: Record<string, AnyRoute>;\n}\n\n/**\n * Resolve a route's declared `seo.link` card (title + description) by its full\n * path.\n *\n * `useRouter()` returns a Router typed to this app's exact route tree, so\n * `routesByPath` is keyed by the literal `FileRouteTypes[\"fullPaths\"]` union —\n * but callers here (declared `related` targets) hold arbitrary runtime path\n * strings, not that literal type. `routesByPath` and `routesById` are plain\n * Records on every Router instance regardless of which route tree it's\n * parameterized over, so this narrows to that structural shape once, at this\n * boundary, instead of threading an `AnyRoute` cast through every call site.\n */\nexport function resolveRouteLink(router: AnyRouter, path: string): RouteSeo[\"link\"] {\n const { routesByPath, routesById } = router as unknown as RouteMaps;\n\n const direct = routesByPath[path];\n if (direct) return direct.options.staticData?.seo?.link;\n\n const byFullPath = Object.values(routesById).find((route) => route.fullPath === path);\n return byFullPath?.options.staticData?.seo?.link;\n}\n"],"mappings":";;;AA4FA,MAAM,gBAAyB;;;;;;AAgB/B,SAAS,SAAS,QAAgB,KAAiC;CACjE,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,IAAI,QAAQ,KAAK,OAAO;CACxB,MAAM,UAAU,IAAI,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAE1D,OAAO,GADW,WAAW,MAAM,KAAK,OAAO,GAAG,UACpC,QAAQ,WAAW,GAAG;AACtC;;AAGA,SAAS,SAAS,MAAgB,UAA8B;CAC9D,OAAO;EACL,MAAM,SAAS;EACf,OAAO,SAAS,SAAS,KAAK;EAC9B,SAAS,SAAS,WAAW,KAAK;EAClC,QAAQ,SAAS,UAAU,KAAK;EAChC,SAAS,SAAS,WAAW,KAAK;EAClC,MAAM,SAAS,QAAQ,KAAK;EAC5B,YAAY,SAAS,cAAc,KAAK;CAC1C;AACF;;;;;;AAOA,SAAS,WACP,OACA,YACA,QACA,OACA,OACA,YACM;CACN,MAAM,OAAO,SAAS,MAAM,SAAS,YAAY,MAAM,QAAQ,IAAI;CACnE,MAAM,MAAM,MAAM,QAAQ,YAAY;CAEtC,IAAI,KAAK;EACP,MAAM,WAAW,MAAM,IAAI,IAAI;EAC/B,IAAI,UAAU;GACZ,SAAS,SAAS,SAAS,SAAS,QAAQ,GAAG;GAC/C,SAAS,OAAO,SAAS,OAAO;EAClC,OACE,MAAM,IAAI,MAAM;GAAE;GAAM,MAAM,IAAI;GAAM,QAAQ;GAAS,QAAQ,EAAE,GAAG,IAAI;EAAE,CAAC;EAG/E,MAAM,uBAAuB,WAAW,WAAW,SAAS;EAC5D,IAAI,IAAI,UAAU,KAAA,KAAa,yBAAyB,KAAA,GACtD,MAAM,KAAK;GAAE,MAAM;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AAM,OACT,OAAO,KAAK,GAAG,MAAM,OAAO,KAAK,UAAU,YAAY,MAAM,KAAK,KAAK,OAAO,CAAC;CAGnF,OAAO;EAAE;EAAK;EAAQ;EAAO;EAAa;EAAW;EAAQ;EAAI;EAAS;EAAQ;CAAO;AAC3F;;AAGA,MAAa,qBAAqB,WAAoC,OAAO,OAAO,SAAS;;;;;;;;;;;;;;;AClM7F,SAAgB,iBAAiB,QAAmB,MAAgC;CAClF,MAAM,EAAE,cAAc,eAAe;CAErC,MAAM,SAAS,aAAa;CAC5B,IAAI,QAAQ,OAAO,OAAO,QAAQ,YAAY,KAAK;CAGnD,OADmB,OAAO,OAAO,UAAU,CAAC,CAAC,MAAM,UAAU,MAAM,aAAa,IAChE,CAAC,EAAE,QAAQ,YAAY,KAAK;AAC9C"}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
//#region src/core/links.ts
|
|
2
|
+
const TOKEN = /<(\/?)(nav|footer|header)\b[^>]*>|<a\b([^>]*)>([\s\S]*?)<\/a>/gi;
|
|
3
|
+
const HREF = /(?:^|\s)href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
|
|
4
|
+
const BASE_TAG = /<base\b[^>]*>/gi;
|
|
5
|
+
const NON_NAVIGABLE = /^(?:#|mailto:|tel:|javascript:|data:)/i;
|
|
6
|
+
const stripTags = (value) => value.replace(/<[^>]*>/g, " ");
|
|
7
|
+
const decodeEntities = (value) => value.replace(/ /gi, " ").replace(/&/gi, "&").replace(/</gi, "<").replace(/>/gi, ">").replace(/"/gi, "\"").replace(/'|'/gi, "'");
|
|
8
|
+
const anchorText = (value) => decodeEntities(stripTags(value)).replace(/\s+/g, " ").trim();
|
|
9
|
+
/** Normalize a same-origin URL to the graph's path key (no query/hash; "/" preserved). */
|
|
10
|
+
const normalizePath = (url) => {
|
|
11
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
12
|
+
return path === "" ? "/" : path;
|
|
13
|
+
};
|
|
14
|
+
const hrefValue = (attributes) => {
|
|
15
|
+
const match = HREF.exec(attributes);
|
|
16
|
+
if (match === null) return void 0;
|
|
17
|
+
return match[1] ?? match[2] ?? match[3];
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The document base URL. Browsers use the first `<base>` element that has an
|
|
21
|
+
* `href` attribute and ignore every later one, so a `<base>` carrying only
|
|
22
|
+
* `target` is skipped, but the first `<base href>` wins even when its value is
|
|
23
|
+
* empty (it then resolves to the document URL) or invalid (the base is ignored,
|
|
24
|
+
* resolving to the document URL). With no `<base href>` at all, links resolve
|
|
25
|
+
* against the response URL.
|
|
26
|
+
*/
|
|
27
|
+
const documentBase = (html, responseUrl) => {
|
|
28
|
+
BASE_TAG.lastIndex = 0;
|
|
29
|
+
let tag;
|
|
30
|
+
while ((tag = BASE_TAG.exec(html)) !== null) {
|
|
31
|
+
const href = hrefValue(tag[0]);
|
|
32
|
+
if (href === void 0) continue;
|
|
33
|
+
if (href.length === 0) return responseUrl;
|
|
34
|
+
try {
|
|
35
|
+
return new URL(href, responseUrl);
|
|
36
|
+
} catch {
|
|
37
|
+
return responseUrl;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return responseUrl;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Extract every anchor in document order, tagging each with the region tag it
|
|
44
|
+
* sits inside. Anchor text keeps only its letters and a coarse entity decode;
|
|
45
|
+
* this is a classifier input, not a renderer.
|
|
46
|
+
*/
|
|
47
|
+
const extractAnchors = (html, baseUrl) => {
|
|
48
|
+
const base = new URL(baseUrl);
|
|
49
|
+
const resolutionBase = documentBase(html, base);
|
|
50
|
+
const regions = [];
|
|
51
|
+
const anchors = [];
|
|
52
|
+
TOKEN.lastIndex = 0;
|
|
53
|
+
let match;
|
|
54
|
+
while ((match = TOKEN.exec(html)) !== null) {
|
|
55
|
+
const closing = match[1];
|
|
56
|
+
const regionTag = match[2];
|
|
57
|
+
if (regionTag !== void 0) {
|
|
58
|
+
const region = regionTag.toLowerCase();
|
|
59
|
+
if (closing === "/") {
|
|
60
|
+
const index = regions.lastIndexOf(region);
|
|
61
|
+
if (index !== -1) regions.splice(index, 1);
|
|
62
|
+
} else regions.push(region);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const attributes = match[3];
|
|
66
|
+
const raw = hrefValue(attributes);
|
|
67
|
+
if (raw === void 0 || raw.length === 0 || NON_NAVIGABLE.test(raw)) continue;
|
|
68
|
+
let resolved;
|
|
69
|
+
try {
|
|
70
|
+
resolved = new URL(raw, resolutionBase);
|
|
71
|
+
} catch {
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (resolved.protocol !== "http:" && resolved.protocol !== "https:") continue;
|
|
75
|
+
const region = regions.length === 0 ? "body" : regions[regions.length - 1];
|
|
76
|
+
anchors.push({
|
|
77
|
+
href: resolved.href,
|
|
78
|
+
text: anchorText(match[4] ?? ""),
|
|
79
|
+
region,
|
|
80
|
+
internal: resolved.origin === base.origin
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
return anchors;
|
|
84
|
+
};
|
|
85
|
+
const breadthFirstDepth = (edges, root) => {
|
|
86
|
+
const adjacency = /* @__PURE__ */ new Map();
|
|
87
|
+
for (const edge of edges) {
|
|
88
|
+
const targets = adjacency.get(edge.from) ?? /* @__PURE__ */ new Set();
|
|
89
|
+
targets.add(edge.to);
|
|
90
|
+
adjacency.set(edge.from, targets);
|
|
91
|
+
}
|
|
92
|
+
const depth = /* @__PURE__ */ new Map([[root, 0]]);
|
|
93
|
+
const queue = [root];
|
|
94
|
+
while (queue.length > 0) {
|
|
95
|
+
const current = queue.shift();
|
|
96
|
+
const currentDepth = depth.get(current);
|
|
97
|
+
for (const next of adjacency.get(current) ?? []) {
|
|
98
|
+
if (depth.has(next)) continue;
|
|
99
|
+
depth.set(next, currentDepth + 1);
|
|
100
|
+
queue.push(next);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return depth;
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* Build the rendered graph from crawled pages. `origin` fixes the graph's
|
|
107
|
+
* same-origin boundary — pages and anchors on another origin are dropped, not
|
|
108
|
+
* silently folded in — and `root` is the normalized path the depth BFS starts
|
|
109
|
+
* from (the seed's final path when the homepage redirected). Every page path is
|
|
110
|
+
* keyed the way the declared graph keys its routes.
|
|
111
|
+
*/
|
|
112
|
+
const buildRenderedGraph = (origin, pages, root = "/") => {
|
|
113
|
+
const graphOrigin = new URL(origin).origin;
|
|
114
|
+
const rootKey = root.replace(/\/+$/, "") || "/";
|
|
115
|
+
const edges = [];
|
|
116
|
+
const nodes = /* @__PURE__ */ new Set();
|
|
117
|
+
for (const page of pages) {
|
|
118
|
+
let pageUrl;
|
|
119
|
+
try {
|
|
120
|
+
pageUrl = new URL(page.url);
|
|
121
|
+
} catch {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (pageUrl.origin !== graphOrigin) continue;
|
|
125
|
+
const path = normalizePath(pageUrl);
|
|
126
|
+
nodes.add(path);
|
|
127
|
+
for (const anchor of page.anchors) {
|
|
128
|
+
let targetUrl;
|
|
129
|
+
try {
|
|
130
|
+
targetUrl = new URL(anchor.href);
|
|
131
|
+
} catch {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (targetUrl.origin !== graphOrigin) continue;
|
|
135
|
+
const target = normalizePath(targetUrl);
|
|
136
|
+
if (target === path) continue;
|
|
137
|
+
edges.push({
|
|
138
|
+
from: path,
|
|
139
|
+
to: target,
|
|
140
|
+
region: anchor.region
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const internalEdges = edges;
|
|
145
|
+
const contextualEdges = edges.filter((edge) => edge.region === "body");
|
|
146
|
+
const incoming = new Set(internalEdges.map((edge) => edge.to));
|
|
147
|
+
const orphans = [...nodes].filter((path) => path !== rootKey && !incoming.has(path)).sort();
|
|
148
|
+
const depthByPath = breadthFirstDepth(internalEdges, rootKey);
|
|
149
|
+
let maxDepth = null;
|
|
150
|
+
for (const value of depthByPath.values()) if (maxDepth === null || value > maxDepth) maxDepth = value;
|
|
151
|
+
return {
|
|
152
|
+
edges,
|
|
153
|
+
internalEdges,
|
|
154
|
+
contextualEdges,
|
|
155
|
+
orphans,
|
|
156
|
+
depthByPath,
|
|
157
|
+
maxDepth
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
const edgeKey = (edge) => `${edge.from}\u0000${edge.to}`;
|
|
161
|
+
const normalizeEdge = (edge) => ({
|
|
162
|
+
from: edge.from === "" ? "/" : edge.from.replace(/\/+$/, "") || "/",
|
|
163
|
+
to: edge.to === "" ? "/" : edge.to.replace(/\/+$/, "") || "/"
|
|
164
|
+
});
|
|
165
|
+
/**
|
|
166
|
+
* Diff rendered contextual edges against declared `related`/`crumb` edges. Both
|
|
167
|
+
* sides are path-keyed; the diff is directional and reports each direction
|
|
168
|
+
* separately because they call for different fixes.
|
|
169
|
+
*/
|
|
170
|
+
const diffLinkGraph = (declared, rendered) => {
|
|
171
|
+
const declaredNormalized = declared.map(normalizeEdge);
|
|
172
|
+
const declaredKeys = new Set(declaredNormalized.map(edgeKey));
|
|
173
|
+
const renderedKeys = new Set(rendered.contextualEdges.map(edgeKey));
|
|
174
|
+
return {
|
|
175
|
+
declaredNotRendered: declaredNormalized.filter((edge) => !renderedKeys.has(edgeKey(edge))),
|
|
176
|
+
renderedNotDeclared: rendered.internalEdges.filter((edge) => edge.region === "body").map((edge) => normalizeEdge(edge)).filter((edge) => !declaredKeys.has(edgeKey(edge))),
|
|
177
|
+
declaredCount: declaredNormalized.length,
|
|
178
|
+
renderedContextualCount: rendered.contextualEdges.length
|
|
179
|
+
};
|
|
180
|
+
};
|
|
181
|
+
//#endregion
|
|
182
|
+
export { normalizePath as i, diffLinkGraph as n, extractAnchors as r, buildRenderedGraph as t };
|
|
183
|
+
|
|
184
|
+
//# sourceMappingURL=links-sGbLkl-7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"links-sGbLkl-7.js","names":[],"sources":["../src/core/links.ts"],"sourcesContent":["/**\n * Pure link-graph utilities: read anchors out of rendered HTML, model the\n * rendered graph, compute homepage depth, and diff it against the declared\n * graph. Effect- and framework-free so it runs in the CLI, a Worker, or a test\n * on the same data.\n *\n * This is the \"served HTML\" half of the SEO graph: the declared graph describes\n * intent, this describes what a crawler actually receives.\n */\n\n/** Where an anchor sits in the document, coarsely. */\nexport type AnchorRegion = \"nav\" | \"footer\" | \"header\" | \"body\";\n\nexport interface Anchor {\n readonly href: string;\n readonly text: string;\n readonly region: AnchorRegion;\n /** True when the resolved target shares the page's origin. */\n readonly internal: boolean;\n}\n\nexport interface LinkEdge {\n readonly from: string;\n readonly to: string;\n readonly region: AnchorRegion;\n}\n\nexport interface RenderedGraph {\n readonly edges: ReadonlyArray<LinkEdge>;\n readonly internalEdges: ReadonlyArray<LinkEdge>;\n /** Same-origin body-region edges: the contextual surface. */\n readonly contextualEdges: ReadonlyArray<LinkEdge>;\n /** Same-origin pages with no incoming internal edge (\"reachable only via nav\" is not implied). */\n readonly orphans: ReadonlyArray<string>;\n readonly depthByPath: ReadonlyMap<string, number>;\n readonly maxDepth: number | null;\n}\n\nconst REGION_TAGS = new Set([\"nav\", \"footer\", \"header\"]);\n\nconst TOKEN =\n /<(\\/?)(nav|footer|header)\\b[^>]*>|<a\\b([^>]*)>([\\s\\S]*?)<\\/a>/gi;\n\n// A real `href` attribute is preceded by whitespace (or the tag's start). The\n// boundary keeps `data-href`, `xhref`, and similar attributes from reading as\n// links, and stops a decoy from winning over a genuine `href`.\nconst HREF = /(?:^|\\s)href\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i;\n\nconst BASE_TAG = /<base\\b[^>]*>/gi;\n\nconst NON_NAVIGABLE = /^(?:#|mailto:|tel:|javascript:|data:)/i;\n\nconst stripTags = (value: string): string => value.replace(/<[^>]*>/g, \" \");\n\nconst decodeEntities = (value: string): string =>\n value\n .replace(/ /gi, \" \")\n .replace(/&/gi, \"&\")\n .replace(/</gi, \"<\")\n .replace(/>/gi, \">\")\n .replace(/"/gi, \"\\\"\")\n .replace(/'|'/gi, \"'\");\n\nconst anchorText = (value: string): string =>\n decodeEntities(stripTags(value)).replace(/\\s+/g, \" \").trim();\n\n/** Normalize a same-origin URL to the graph's path key (no query/hash; \"/\" preserved). */\nexport const normalizePath = (url: URL): string => {\n const path = url.pathname.replace(/\\/+$/, \"\");\n return path === \"\" ? \"/\" : path;\n};\n\nconst hrefValue = (attributes: string): string | undefined => {\n const match = HREF.exec(attributes);\n if (match === null) return undefined;\n return match[1] ?? match[2] ?? match[3];\n};\n\n/**\n * The document base URL. Browsers use the first `<base>` element that has an\n * `href` attribute and ignore every later one, so a `<base>` carrying only\n * `target` is skipped, but the first `<base href>` wins even when its value is\n * empty (it then resolves to the document URL) or invalid (the base is ignored,\n * resolving to the document URL). With no `<base href>` at all, links resolve\n * against the response URL.\n */\nconst documentBase = (html: string, responseUrl: URL): URL => {\n BASE_TAG.lastIndex = 0;\n let tag: RegExpExecArray | null;\n while ((tag = BASE_TAG.exec(html)) !== null) {\n const href = hrefValue(tag[0]);\n if (href === undefined) continue;\n if (href.length === 0) return responseUrl;\n try {\n return new URL(href, responseUrl);\n } catch {\n return responseUrl;\n }\n }\n return responseUrl;\n};\n\n/**\n * Extract every anchor in document order, tagging each with the region tag it\n * sits inside. Anchor text keeps only its letters and a coarse entity decode;\n * this is a classifier input, not a renderer.\n */\nexport const extractAnchors = (html: string, baseUrl: string): ReadonlyArray<Anchor> => {\n const base = new URL(baseUrl);\n const resolutionBase = documentBase(html, base);\n const regions: Array<AnchorRegion> = [];\n const anchors: Array<Anchor> = [];\n TOKEN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = TOKEN.exec(html)) !== null) {\n const closing = match[1];\n const regionTag = match[2];\n if (regionTag !== undefined) {\n const region = regionTag.toLowerCase() as AnchorRegion;\n if (closing === \"/\") {\n const index = regions.lastIndexOf(region);\n if (index !== -1) regions.splice(index, 1);\n } else {\n regions.push(region);\n }\n continue;\n }\n const attributes = match[3];\n const raw = hrefValue(attributes);\n if (raw === undefined || raw.length === 0 || NON_NAVIGABLE.test(raw)) continue;\n let resolved: URL;\n try {\n resolved = new URL(raw, resolutionBase);\n } catch {\n continue;\n }\n if (resolved.protocol !== \"http:\" && resolved.protocol !== \"https:\") continue;\n const region = regions.length === 0 ? \"body\" : regions[regions.length - 1]!;\n anchors.push({\n href: resolved.href,\n text: anchorText(match[4] ?? \"\"),\n region,\n internal: resolved.origin === base.origin,\n });\n }\n return anchors;\n};\n\nexport interface RenderedPage {\n readonly url: string;\n readonly anchors: ReadonlyArray<Anchor>;\n}\n\nconst breadthFirstDepth = (\n edges: ReadonlyArray<LinkEdge>,\n root: string,\n): ReadonlyMap<string, number> => {\n const adjacency = new Map<string, Set<string>>();\n for (const edge of edges) {\n const targets = adjacency.get(edge.from) ?? new Set<string>();\n targets.add(edge.to);\n adjacency.set(edge.from, targets);\n }\n const depth = new Map<string, number>([[root, 0]]);\n const queue: Array<string> = [root];\n while (queue.length > 0) {\n const current = queue.shift()!;\n const currentDepth = depth.get(current)!;\n for (const next of adjacency.get(current) ?? []) {\n if (depth.has(next)) continue;\n depth.set(next, currentDepth + 1);\n queue.push(next);\n }\n }\n return depth;\n};\n\n/**\n * Build the rendered graph from crawled pages. `origin` fixes the graph's\n * same-origin boundary — pages and anchors on another origin are dropped, not\n * silently folded in — and `root` is the normalized path the depth BFS starts\n * from (the seed's final path when the homepage redirected). Every page path is\n * keyed the way the declared graph keys its routes.\n */\nexport const buildRenderedGraph = (\n origin: string,\n pages: ReadonlyArray<RenderedPage>,\n root: string = \"/\",\n): RenderedGraph => {\n const originUrl = new URL(origin);\n const graphOrigin = originUrl.origin;\n const rootKey = root.replace(/\\/+$/, \"\") || \"/\";\n const edges: Array<LinkEdge> = [];\n const nodes = new Set<string>();\n for (const page of pages) {\n let pageUrl: URL;\n try {\n pageUrl = new URL(page.url);\n } catch {\n continue;\n }\n if (pageUrl.origin !== graphOrigin) continue;\n const path = normalizePath(pageUrl);\n nodes.add(path);\n for (const anchor of page.anchors) {\n let targetUrl: URL;\n try {\n targetUrl = new URL(anchor.href);\n } catch {\n continue;\n }\n if (targetUrl.origin !== graphOrigin) continue;\n const target = normalizePath(targetUrl);\n if (target === path) continue;\n edges.push({ from: path, to: target, region: anchor.region });\n }\n }\n const internalEdges = edges;\n const contextualEdges = edges.filter((edge) => edge.region === \"body\");\n const incoming = new Set(internalEdges.map((edge) => edge.to));\n const orphans = [...nodes]\n .filter((path) => path !== rootKey && !incoming.has(path))\n .sort();\n const depthByPath = breadthFirstDepth(internalEdges, rootKey);\n let maxDepth: number | null = null;\n for (const value of depthByPath.values()) {\n if (maxDepth === null || value > maxDepth) maxDepth = value;\n }\n return { edges, internalEdges, contextualEdges, orphans, depthByPath, maxDepth };\n};\n\nexport interface SimpleEdge {\n readonly from: string;\n readonly to: string;\n}\n\nexport interface LinkGraphDiff {\n /** Declared internal edges with no matching rendered anchor. */\n readonly declaredNotRendered: ReadonlyArray<SimpleEdge>;\n /** Rendered contextual edges that no declared edge accounts for. */\n readonly renderedNotDeclared: ReadonlyArray<SimpleEdge>;\n readonly declaredCount: number;\n readonly renderedContextualCount: number;\n}\n\nconst edgeKey = (edge: SimpleEdge): string => `${edge.from}\\u0000${edge.to}`;\n\nconst normalizeEdge = (edge: SimpleEdge): SimpleEdge => ({\n from: edge.from === \"\" ? \"/\" : edge.from.replace(/\\/+$/, \"\") || \"/\",\n to: edge.to === \"\" ? \"/\" : edge.to.replace(/\\/+$/, \"\") || \"/\",\n});\n\n/**\n * Diff rendered contextual edges against declared `related`/`crumb` edges. Both\n * sides are path-keyed; the diff is directional and reports each direction\n * separately because they call for different fixes.\n */\nexport const diffLinkGraph = (\n declared: ReadonlyArray<SimpleEdge>,\n rendered: RenderedGraph,\n): LinkGraphDiff => {\n const declaredNormalized = declared.map(normalizeEdge);\n const declaredKeys = new Set(declaredNormalized.map(edgeKey));\n const renderedKeys = new Set(rendered.contextualEdges.map(edgeKey));\n const declaredNotRendered = declaredNormalized.filter(\n (edge) => !renderedKeys.has(edgeKey(edge)),\n );\n const renderedNotDeclared = rendered.internalEdges\n .filter((edge) => edge.region === \"body\")\n .map((edge) => normalizeEdge(edge))\n .filter((edge) => !declaredKeys.has(edgeKey(edge)));\n return {\n declaredNotRendered,\n renderedNotDeclared,\n declaredCount: declaredNormalized.length,\n renderedContextualCount: rendered.contextualEdges.length,\n };\n};\n"],"mappings":";AAwCA,MAAM,QACJ;AAKF,MAAM,OAAO;AAEb,MAAM,WAAW;AAEjB,MAAM,gBAAgB;AAEtB,MAAM,aAAa,UAA0B,MAAM,QAAQ,YAAY,GAAG;AAE1E,MAAM,kBAAkB,UACtB,MACG,QAAQ,YAAY,GAAG,CAAC,CACxB,QAAQ,WAAW,GAAG,CAAC,CACvB,QAAQ,UAAU,GAAG,CAAC,CACtB,QAAQ,UAAU,GAAG,CAAC,CACtB,QAAQ,YAAY,IAAI,CAAC,CACzB,QAAQ,kBAAkB,GAAG;AAElC,MAAM,cAAc,UAClB,eAAe,UAAU,KAAK,CAAC,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;;AAG7D,MAAa,iBAAiB,QAAqB;CACjD,MAAM,OAAO,IAAI,SAAS,QAAQ,QAAQ,EAAE;CAC5C,OAAO,SAAS,KAAK,MAAM;AAC7B;AAEA,MAAM,aAAa,eAA2C;CAC5D,MAAM,QAAQ,KAAK,KAAK,UAAU;CAClC,IAAI,UAAU,MAAM,OAAO,KAAA;CAC3B,OAAO,MAAM,MAAM,MAAM,MAAM,MAAM;AACvC;;;;;;;;;AAUA,MAAM,gBAAgB,MAAc,gBAA0B;CAC5D,SAAS,YAAY;CACrB,IAAI;CACJ,QAAQ,MAAM,SAAS,KAAK,IAAI,OAAO,MAAM;EAC3C,MAAM,OAAO,UAAU,IAAI,EAAE;EAC7B,IAAI,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
1
1
|
{
|
|
2
2
|
"name": "pagegraph",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Route-declared SEO graph and audit toolkit for TanStack Start: sitemap/robots, React head, JSON-LD, Vite coverage gate, live audit, and Jev-backed link decisions.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"seo",
|
|
@@ -79,13 +79,14 @@
|
|
|
79
79
|
"@tanstack/router-generator": "^1.167.21"
|
|
80
80
|
},
|
|
81
81
|
"devDependencies": {
|
|
82
|
-
"@effect/
|
|
83
|
-
"@effect/platform-
|
|
84
|
-
"@effect/
|
|
82
|
+
"@effect/ai-typesafe": "4.0.0-rc.116",
|
|
83
|
+
"@effect/platform-bun": "4.0.0-rc.116",
|
|
84
|
+
"@effect/platform-node-shared": "4.0.0-rc.116",
|
|
85
|
+
"@effect/vitest": "4.0.0-rc.116",
|
|
85
86
|
"@tanstack/react-router": "^1.170.18",
|
|
86
87
|
"@types/node": "^24.0.0",
|
|
87
88
|
"@types/react": "19.2.18",
|
|
88
|
-
"effect": "4.0.0-rc.
|
|
89
|
+
"effect": "4.0.0-rc.116",
|
|
89
90
|
"lighthouse": "13.4.1",
|
|
90
91
|
"react": "19.2.8",
|
|
91
92
|
"schema-dts": "^2.0.0",
|
|
@@ -93,17 +94,21 @@
|
|
|
93
94
|
"tsdown": "^0.22.13",
|
|
94
95
|
"typescript": "^6.0.3",
|
|
95
96
|
"vite": "~8.2.0",
|
|
96
|
-
"vitest": "^
|
|
97
|
+
"vitest": "^5.0.0"
|
|
97
98
|
},
|
|
98
99
|
"peerDependencies": {
|
|
99
|
-
"@effect/
|
|
100
|
+
"@effect/ai-typesafe": "^4.0.0-rc.116",
|
|
101
|
+
"@effect/platform-bun": "^4.0.0-rc.116",
|
|
100
102
|
"@tanstack/react-router": "^1.170.0",
|
|
101
|
-
"effect": "^4.0.0-rc.
|
|
103
|
+
"effect": "^4.0.0-rc.116",
|
|
102
104
|
"lighthouse": ">=13.0.0",
|
|
103
105
|
"react": "^19.0.0",
|
|
104
106
|
"vite": "^8.0.0"
|
|
105
107
|
},
|
|
106
108
|
"peerDependenciesMeta": {
|
|
109
|
+
"@effect/ai-typesafe": {
|
|
110
|
+
"optional": true
|
|
111
|
+
},
|
|
107
112
|
"@effect/platform-bun": {
|
|
108
113
|
"optional": true
|
|
109
114
|
},
|