@hamur/seo 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +26 -2
  3. package/dist/chunks/bun-index-rnjhv41c.js +62 -0
  4. package/dist/chunks/bun-index-xf4srhvn.js +97 -0
  5. package/dist/src/adapters/html.js +40 -0
  6. package/dist/src/adapters/preact.js +36 -0
  7. package/dist/src/adapters/react.js +36 -0
  8. package/dist/src/adapters/solid.js +35 -0
  9. package/dist/src/adapters/svelte.js +35 -0
  10. package/dist/src/adapters/vue.js +43 -0
  11. package/dist/src/index.js +1375 -0
  12. package/dist/src/schema.js +51 -0
  13. package/dist/src/server/index.js +1 -0
  14. package/dist/src/share.js +40 -0
  15. package/dist/types/src/adapters/html.d.ts +6 -0
  16. package/dist/types/src/adapters/preact.d.ts +5 -0
  17. package/dist/types/src/adapters/react.d.ts +5 -0
  18. package/dist/types/src/adapters/solid.d.ts +6 -0
  19. package/dist/types/src/adapters/svelte.d.ts +5 -0
  20. package/dist/types/src/adapters/vue.d.ts +9 -0
  21. package/dist/types/src/build/links.d.ts +4 -0
  22. package/dist/types/src/build/llms.d.ts +6 -0
  23. package/dist/types/src/build/own.d.ts +5 -0
  24. package/dist/types/src/build/robots.d.ts +3 -0
  25. package/dist/types/src/build/schema.d.ts +4 -0
  26. package/dist/types/src/build/sitemap.d.ts +7 -0
  27. package/dist/types/src/index.d.ts +2 -0
  28. package/dist/types/src/links/check.d.ts +7 -0
  29. package/dist/types/src/links/external.d.ts +6 -0
  30. package/dist/types/src/links/options.d.ts +12 -0
  31. package/dist/types/src/links/report.d.ts +4 -0
  32. package/dist/types/src/links/scan.d.ts +24 -0
  33. package/dist/types/src/llms/options.d.ts +9 -0
  34. package/dist/types/src/llms/paths.d.ts +8 -0
  35. package/dist/types/src/llms/text.d.ts +12 -0
  36. package/dist/types/src/module.d.ts +3 -0
  37. package/dist/types/src/robots/ai-bots.d.ts +2 -0
  38. package/dist/types/src/robots/body.d.ts +16 -0
  39. package/dist/types/src/robots/options.d.ts +9 -0
  40. package/dist/types/src/runtime/breadcrumbs.d.ts +37 -0
  41. package/dist/types/src/runtime/markdown.d.ts +15 -0
  42. package/dist/types/src/runtime/schema-plugin.d.ts +2 -0
  43. package/dist/types/src/runtime/schema-store.d.ts +34 -0
  44. package/dist/types/src/schema/graph.d.ts +13 -0
  45. package/dist/types/src/schema/helpers.d.ts +358 -0
  46. package/dist/types/src/schema/options.d.ts +7 -0
  47. package/dist/types/src/schema.d.ts +10 -0
  48. package/dist/types/src/server/agent.d.ts +4 -0
  49. package/dist/types/src/server/door.d.ts +5 -0
  50. package/dist/types/src/server/index.d.ts +1 -0
  51. package/dist/types/src/server/llms.d.ts +2 -0
  52. package/dist/types/src/server/render.d.ts +9 -0
  53. package/dist/types/src/server/robots.d.ts +1 -0
  54. package/dist/types/src/server/sitemap.d.ts +5 -0
  55. package/dist/types/src/share.d.ts +18 -0
  56. package/dist/types/src/sitemap/alternates.d.ts +14 -0
  57. package/dist/types/src/sitemap/answer.d.ts +6 -0
  58. package/dist/types/src/sitemap/entries.d.ts +9 -0
  59. package/dist/types/src/sitemap/options.d.ts +7 -0
  60. package/dist/types/src/sitemap/paths.d.ts +13 -0
  61. package/dist/types/src/sitemap/xml.d.ts +23 -0
  62. package/dist/types/src/types.d.ts +73 -0
  63. package/package.json +136 -4
  64. package/src/adapters/html.ts +43 -0
  65. package/src/adapters/preact.ts +37 -0
  66. package/src/adapters/react.ts +37 -0
  67. package/src/adapters/solid.ts +38 -0
  68. package/src/adapters/svelte.ts +37 -0
  69. package/src/adapters/vue.ts +55 -0
  70. package/src/build/links.ts +13 -0
  71. package/src/build/llms.ts +79 -0
  72. package/src/build/own.ts +46 -0
  73. package/src/build/robots.ts +58 -0
  74. package/src/build/schema.ts +23 -0
  75. package/src/build/sitemap.ts +101 -0
  76. package/src/env.d.ts +44 -0
  77. package/src/index.ts +14 -0
  78. package/src/links/check.ts +233 -0
  79. package/src/links/external.ts +41 -0
  80. package/src/links/options.ts +69 -0
  81. package/src/links/report.ts +49 -0
  82. package/src/links/scan.ts +123 -0
  83. package/src/llms/options.ts +49 -0
  84. package/src/llms/paths.ts +33 -0
  85. package/src/llms/text.ts +26 -0
  86. package/src/module.ts +22 -0
  87. package/src/robots/ai-bots.ts +14 -0
  88. package/src/robots/body.ts +51 -0
  89. package/src/robots/options.ts +75 -0
  90. package/src/runtime/breadcrumbs.ts +84 -0
  91. package/src/runtime/markdown.ts +381 -0
  92. package/src/runtime/schema-plugin.ts +22 -0
  93. package/src/runtime/schema-store.ts +144 -0
  94. package/src/schema/graph.ts +125 -0
  95. package/src/schema/helpers.ts +372 -0
  96. package/src/schema/options.ts +39 -0
  97. package/src/schema.ts +5 -0
  98. package/src/server/agent.ts +45 -0
  99. package/src/server/door.ts +8 -0
  100. package/src/server/index.ts +1 -0
  101. package/src/server/llms.ts +139 -0
  102. package/src/server/render.ts +33 -0
  103. package/src/server/robots.ts +19 -0
  104. package/src/server/sitemap.ts +222 -0
  105. package/src/share.ts +56 -0
  106. package/src/sitemap/alternates.ts +66 -0
  107. package/src/sitemap/answer.ts +42 -0
  108. package/src/sitemap/entries.ts +136 -0
  109. package/src/sitemap/options.ts +47 -0
  110. package/src/sitemap/paths.ts +39 -0
  111. package/src/sitemap/xml.ts +71 -0
  112. package/src/types.ts +89 -0
@@ -0,0 +1,101 @@
1
+ import { DiagnosticError, addTemplate, diagnostic, useLogger, type RouteRecord, type HamurContext } from "hamur/kit"
2
+ import { pageAlternates, readLocales } from "../sitemap/alternates.ts"
3
+ import { clean, sitemapPaths } from "../sitemap/paths.ts"
4
+ import { resolveSitemap, type ResolvedSitemap } from "../sitemap/options.ts"
5
+ import { slashForm } from "hamur/server/internal"
6
+ import { yieldToApp } from "./own.ts"
7
+
8
+ const PATH = "/sitemap.xml"
9
+ export const PART_ROUTE = "/sitemap-:n.xml"
10
+
11
+ const flatten = (routes: RouteRecord[]): RouteRecord[] =>
12
+ routes.flatMap((route) => [...(route.pathless ? [] : [route]), ...flatten(route.children)])
13
+
14
+ /** Under `app.trailingSlash: "always"` a listed page path ends in `/`, by the one rule of the handler and the client. */
15
+ export const slashed = (path: string): string => slashForm(path, "/") ?? path
16
+
17
+ const hash = (text: string): string => {
18
+ let value = 5381
19
+ for (let index = 0; index < text.length; index++) value = ((value * 33) ^ text.charCodeAt(index)) >>> 0
20
+ return value.toString(36)
21
+ }
22
+
23
+ const moduleSource = (values: Record<string, unknown>): string =>
24
+ Object.entries(values)
25
+ .map(([name, value]) => `export const ${name} = ${JSON.stringify(value)};\n`)
26
+ .join("")
27
+
28
+ /** `listed` keeps the URL list in the build for `seo.llms` while `seo.sitemap` serves no file. */
29
+ export function setupSitemap(served: ResolvedSitemap | undefined, hamur: HamurContext, listed = false): void {
30
+ const own = yieldToApp(hamur, PATH, served !== undefined, [PART_ROUTE])
31
+ const sitemap = served ?? (listed ? resolveSitemap(true) : undefined)
32
+ if (!sitemap) {
33
+ addTemplate({
34
+ filename: "seo/sitemap",
35
+ getContents: () =>
36
+ moduleSource({ paths: [], alternates: {}, sources: [], chunkSize: 50_000, baseURL: "/", signature: "" }),
37
+ })
38
+ return
39
+ }
40
+ const { baseURL } = hamur.options.app
41
+ if (served && hamur.options.site.url === undefined && !process.env.HAMUR_SITE_URL)
42
+ useLogger("seo").warn(diagnostic("HAMUR_W6411", `site.url is not set; ${PATH} needs HAMUR_SITE_URL at run time`))
43
+
44
+ hamur.hooks.hook("server:extend", (records) => {
45
+ if (!own.served()) return
46
+ sitemap.sources.forEach((source, index) => {
47
+ if (
48
+ !records.some((record) => record.path === source && (record.method === undefined || record.method === "GET"))
49
+ ) {
50
+ throw new DiagnosticError(
51
+ "HAMUR_E6408",
52
+ `seo.sitemap.sources[${index}] ${JSON.stringify(source)} is not the route of a GET handler`,
53
+ )
54
+ }
55
+ })
56
+ })
57
+
58
+ addTemplate({
59
+ filename: "seo/sitemap",
60
+ getContents: (ctx) => {
61
+ const pages = flatten(ctx.routes)
62
+ const paths = sitemapPaths({
63
+ pages: pages.map((route) => route.path),
64
+ listed: Array.isArray(ctx.options.prerender.routes) ? ctx.options.prerender.routes : [],
65
+ rules: ctx.routeRules,
66
+ exclude: sitemap.exclude,
67
+ })
68
+ const locales = readLocales((ctx.options as unknown as { i18n?: unknown }).i18n)
69
+ const alternates = locales ? pageAlternates(pages, locales, new Set(paths), clean) : {}
70
+ if (hamur.options.app.trailingSlash === "always") {
71
+ return moduleSource({
72
+ paths: paths.map(slashed),
73
+ alternates: Object.fromEntries(
74
+ Object.entries(alternates).map(([path, list]) => [
75
+ slashed(path),
76
+ list.map(([hreflang, other]): [string, string] => [hreflang, slashed(other)]),
77
+ ]),
78
+ ),
79
+ sources: sitemap.sources,
80
+ chunkSize: sitemap.chunkSize,
81
+ baseURL,
82
+ signature: hash(JSON.stringify([paths, alternates, sitemap.sources, "always"])),
83
+ })
84
+ }
85
+ return moduleSource({
86
+ paths,
87
+ alternates,
88
+ sources: sitemap.sources,
89
+ chunkSize: sitemap.chunkSize,
90
+ baseURL,
91
+ signature: hash(JSON.stringify([paths, alternates, sitemap.sources])),
92
+ })
93
+ },
94
+ })
95
+
96
+ if (served && hamur.options.preset === "static") {
97
+ hamur.hooks.hook("prerender:routes", (routes) => {
98
+ if (own.served()) routes.add(PATH)
99
+ })
100
+ }
101
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ declare module "#hamur/seo/robots" {
2
+ /** The `/robots.txt` of an indexable site; the server answers `User-agent: *` / `Disallow: /` when `site.indexable` is false. */
3
+ export const body: string
4
+ /** `<app.baseURL>sitemap.xml` while the module serves a sitemap, else `null`. */
5
+ export const sitemap: string | null
6
+ }
7
+
8
+ declare module "#hamur/seo/sitemap" {
9
+ /** The paths of the sitemap below `app.baseURL`, in order, each once, with the `noindex`, `redirect` and `exclude` paths already left out. */
10
+ export const paths: string[]
11
+ /** `path` → `[hreflang, path]` of each locale of `@hamur/i18n`, then `x-default`; empty without the module. */
12
+ export const alternates: Record<string, Array<[string, string]>>
13
+ /** `seo.sitemap.sources`: the routes of the GET handlers whose answers are listed after the paths. */
14
+ export const sources: string[]
15
+ /** `seo.sitemap.chunkSize`. */
16
+ export const chunkSize: number
17
+ /** `app.baseURL`. */
18
+ export const baseURL: string
19
+ /** Names the build's pages and sources, so a list cached by an earlier build is not read. */
20
+ export const signature: string
21
+ }
22
+
23
+ declare module "#hamur/seo/schema-org" {
24
+ /** `seo.schemaOrg` and the `app` keys the page URL is built with. */
25
+ const schema: import("./runtime/schema-store.ts").SchemaOrgRuntime
26
+ export default schema
27
+ }
28
+
29
+ declare module "#hamur/seo/llms" {
30
+ /** Whether `seo.llms` is on; the middleware and the plugin do nothing while it is not. */
31
+ export const enabled: boolean
32
+ /** `seo.llms.title`, `null` for `site.name`. */
33
+ export const title: string | null
34
+ /** `seo.llms.description`, `null` for `site.description`. */
35
+ export const description: string | null
36
+ /** `seo.llms.exclude`. */
37
+ export const exclude: string[]
38
+ /** `app.baseURL`. */
39
+ export const baseURL: string
40
+ /** `app.trailingSlash`. */
41
+ export const trailingSlash: string
42
+ /** `app.rootId`, the element a page without `<main>` is read from. */
43
+ export const rootId: string
44
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export { default } from "./module.ts"
2
+ export type {
3
+ LinkCheckerConfig,
4
+ LinkRuleId,
5
+ LlmsConfig,
6
+ RobotsConfig,
7
+ RobotsGroup,
8
+ SeoConfig,
9
+ SitemapChangeFrequency,
10
+ SitemapConfig,
11
+ SitemapEntry,
12
+ SitemapPage,
13
+ SitemapVideo,
14
+ } from "./types.ts"
@@ -0,0 +1,233 @@
1
+ import {
2
+ DiagnosticError,
3
+ createRouteRules,
4
+ diagnostic,
5
+ useLogger,
6
+ type HamurContext,
7
+ type PrerenderPage,
8
+ type PrerenderRun,
9
+ type PrerenderedPage,
10
+ } from "hamur/kit"
11
+ import { formatLinkFindings, slashForm, type LinkFinding } from "hamur/server/internal"
12
+ import type { LinkRuleId } from "../types.ts"
13
+ import { probeAll } from "./external.ts"
14
+ import { LINK_RULES, type ResolvedLinkChecker } from "./options.ts"
15
+ import { writeReports } from "./report.ts"
16
+ import { scanPage } from "./scan.ts"
17
+
18
+ const ORIGIN = "http://localhost"
19
+ const REDIRECTS = new Set([301, 302, 303, 307, 308])
20
+ const SCRIPT = /^[\s\u0000-\u001f]*javascript:/i
21
+
22
+ interface Pending {
23
+ at: number
24
+ shown: string
25
+ target: string
26
+ fragment?: string
27
+ }
28
+
29
+ interface Seen {
30
+ path: string
31
+ status: number
32
+ location?: string
33
+ ids?: Set<string>
34
+ pending: Pending[]
35
+ }
36
+
37
+ const trimSlash = (path: string) => path.replace(/(.)\/+$/, "$1")
38
+ const keyOf = (path: string) => trimSlash(path)
39
+
40
+ function stripBase(pathname: string, baseURL: string): string | undefined {
41
+ const base = baseURL.replace(/\/+$/, "")
42
+ if (base === "") return pathname
43
+ if (pathname === base) return "/"
44
+ return pathname.startsWith(`${base}/`) ? pathname.slice(base.length) : undefined
45
+ }
46
+
47
+ const decodeFragment = (hash: string): string | undefined => {
48
+ let value = hash.slice(1)
49
+ try {
50
+ value = decodeURIComponent(value)
51
+ } catch {}
52
+ return value === "" || value === "top" || value.startsWith(":~:") ? undefined : value
53
+ }
54
+
55
+ /** Collects the pages through `prerender:page`, runs the rules that need other pages in `prerender:done`. */
56
+ export function createLinkChecker(hamur: HamurContext, options: ResolvedLinkChecker) {
57
+ const log = useLogger("seo")
58
+ const { baseURL, trailingSlash } = hamur.options.app
59
+ const buildAssets = `/${hamur.options.app.buildAssetsDir.replace(/^\/+|\/+$/g, "")}/`
60
+ const excluded = options.exclude.length
61
+ ? createRouteRules(Object.fromEntries(options.exclude.map((pattern) => [pattern, {}])))
62
+ : undefined
63
+ const routeRules = createRouteRules(hamur.routeRules)
64
+ let pages = new Map<string, Seen>()
65
+ let findings: Array<LinkFinding & { at: number }> = []
66
+ let externals = new Map<string, Set<string>>()
67
+ let scanned = 0
68
+
69
+ const levelOf = (rule: LinkRuleId) => options.rules[rule] ?? LINK_RULES[rule]
70
+ const add = (page: string, rule: LinkRuleId, link: string, message: string, at = Number.MAX_SAFE_INTEGER) => {
71
+ const level = levelOf(rule)
72
+ if (level === false) return
73
+ if (!findings.some((found) => found.page === page && found.rule === rule && found.message === message))
74
+ findings.push({ page, rule, level, link, message, at })
75
+ }
76
+ const siteOrigin = (): string | undefined => {
77
+ try {
78
+ const url = hamur.options.site.url ?? process.env.HAMUR_SITE_URL
79
+ return url === undefined ? undefined : new URL(url).origin
80
+ } catch {
81
+ return undefined
82
+ }
83
+ }
84
+
85
+ function scanLinks(page: PrerenderPage, html: string): Seen {
86
+ const scan = scanPage(html)
87
+ scanned++
88
+ const seen: Seen = { path: page.path, status: page.status, ids: scan.ids, pending: [] }
89
+ const from = `${ORIGIN}${baseURL.replace(/\/+$/, "")}${page.path}`
90
+ const site = siteOrigin()
91
+ for (const [at, { href: raw, named }] of scan.links.entries()) {
92
+ const href = raw.trim()
93
+ if (raw !== href || /\s/.test(href.split(/[?#]/)[0]!))
94
+ add(page.path, "whitespace", raw, `link href ${JSON.stringify(raw)} holds white space`, at)
95
+ if (SCRIPT.test(raw)) {
96
+ add(page.path, "javascript-href", href, `link href ${JSON.stringify(href)} runs script; use a button`, at)
97
+ if (!named) add(page.path, "empty-text", href, `link to ${href} has no text, aria-label or image alt`, at)
98
+ continue
99
+ }
100
+ let url: URL
101
+ try {
102
+ url = new URL(href, from)
103
+ } catch {
104
+ continue
105
+ }
106
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
107
+ if (!named) add(page.path, "empty-text", href, `link to ${href} has no text, aria-label or image alt`, at)
108
+ continue
109
+ }
110
+ const absolute = /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)
111
+ const onSite = absolute && site !== undefined && url.origin === site
112
+ if (url.origin !== ORIGIN && !onSite) {
113
+ if (!named) add(page.path, "empty-text", href, `link to ${href} has no text, aria-label or image alt`, at)
114
+ const key = `${url.origin}${url.pathname}${url.search}`
115
+ if (options.external) externals.set(key, (externals.get(key) ?? new Set()).add(page.path))
116
+ continue
117
+ }
118
+ const appPath = stripBase(url.pathname, baseURL)
119
+ if (appPath === undefined || appPath.startsWith(buildAssets)) continue
120
+ if (excluded?.match(appPath).matches.length) continue
121
+ const own = /^[#?]/.test(href)
122
+ const shown = own ? href : url.pathname
123
+ if (!named) add(page.path, "empty-text", shown, `link to ${shown} has no text, aria-label or image alt`, at)
124
+ if (onSite)
125
+ add(page.path, "absolute-site-url", href, `link to ${href} is absolute on site.url; write ${url.pathname}`, at)
126
+ if (!own) {
127
+ if (url.pathname.includes("//"))
128
+ add(page.path, "double-slash", shown, `link to ${shown} has a double slash in its path`, at)
129
+ if (/[A-Z]/.test(url.pathname.replace(/%[\da-f]{2}/gi, "")))
130
+ add(page.path, "uppercase", shown, `link to ${shown} has upper-case letters in its path`, at)
131
+ const ends = appPath.length > 1 && appPath.endsWith("/")
132
+ if (trailingSlash === "always" ? !ends && slashForm(appPath, "/") !== undefined : ends) {
133
+ const fixed = trailingSlash === "always" ? `${url.pathname}/` : url.pathname.replace(/\/+$/, "")
134
+ add(
135
+ page.path,
136
+ "trailing-slash",
137
+ shown,
138
+ `link to ${shown} does not follow app.trailingSlash ${JSON.stringify(trailingSlash)}; write ${fixed}`,
139
+ at,
140
+ )
141
+ }
142
+ }
143
+ const fragment = decodeFragment(url.hash)
144
+ seen.pending.push({
145
+ at,
146
+ shown: own ? url.hash || href : `${url.pathname}${url.hash}`,
147
+ target: appPath,
148
+ ...(fragment === undefined ? {} : { fragment }),
149
+ })
150
+ }
151
+ return seen
152
+ }
153
+
154
+ function page(current: PrerenderPage): void {
155
+ const html = typeof current.body === "string" && (current.headers.get("content-type") ?? "").startsWith("text/html")
156
+ const ok = current.status >= 200 && current.status <= 299
157
+ const seen =
158
+ html && ok
159
+ ? scanLinks(current, current.body as string)
160
+ : { path: current.path, status: current.status, pending: [] }
161
+ const location = current.headers.get("location")
162
+ pages.set(keyOf(current.path), { ...seen, ...(location ? { location } : {}) })
163
+ }
164
+
165
+ async function done(_pages: PrerenderedPage[], run: PrerenderRun): Promise<void> {
166
+ if (run.checkNext) {
167
+ reset()
168
+ return
169
+ }
170
+ run.linksReported = true
171
+ const failed = new Map(run.failed.map((answer) => [keyOf(answer.path), answer]))
172
+ const known = new Map<string, boolean>()
173
+ const exists = async (path: string) => {
174
+ if (!known.has(path)) known.set(path, await run.exists(path))
175
+ return known.get(path)!
176
+ }
177
+ for (const seen of [...pages.values()].sort((a, b) => (a.path < b.path ? -1 : 1))) {
178
+ for (const { at, shown, target, fragment } of seen.pending) {
179
+ const key = keyOf(target)
180
+ const there = pages.get(key)
181
+ const path = target
182
+ const answer = failed.get(key)
183
+ if (answer) add(seen.path, "broken", shown, `link to ${path} answers ${answer.status}`, at)
184
+ else if (!there && !(await exists(key))) add(seen.path, "broken", shown, `link to ${path} matches no route`, at)
185
+ const redirect = REDIRECTS.has(there?.status ?? 0) ? there?.location : there ? undefined : ruleRedirect(key)
186
+ if (redirect)
187
+ add(seen.path, "redirect", shown, `link to ${path} redirects to ${redirect}; link to ${redirect}`, at)
188
+ if (fragment !== undefined && there?.ids && !there.ids.has(fragment))
189
+ add(
190
+ seen.path,
191
+ "missing-anchor",
192
+ shown,
193
+ `link to ${shown}: ${path} has no element with id ${JSON.stringify(fragment)}`,
194
+ at,
195
+ )
196
+ }
197
+ }
198
+ if (externals.size) {
199
+ const bad = await probeAll(externals.keys())
200
+ for (const [url, message] of bad)
201
+ for (const from of externals.get(url)!) add(from, "external-broken", url, message)
202
+ }
203
+ const ordered = findings
204
+ .toSorted((a, b) => (a.page < b.page ? -1 : a.page > b.page ? 1 : a.at - b.at))
205
+ .map(({ at: _, ...finding }) => finding)
206
+ const errors = ordered.filter((finding) => finding.level === "error").length
207
+ const count = scanned
208
+ reset()
209
+ if (ordered.length) log.warn(diagnostic("HAMUR_W6410", formatLinkFindings(ordered)))
210
+ else if (run.checkOnly) log.info(`link checker: no findings on ${count} page${count === 1 ? "" : "s"}`)
211
+ await writeReports(hamur.options.buildDir, options.report, count, ordered)
212
+ if (options.failOnError && errors)
213
+ throw new DiagnosticError(
214
+ "HAMUR_E6407",
215
+ `[seo] link checker found ${errors} error${errors === 1 ? "" : "s"} (seo.linkChecker.failOnError)`,
216
+ )
217
+ }
218
+
219
+ function ruleRedirect(path: string): string | undefined {
220
+ const { redirect } = routeRules.match(path).rule
221
+ if (redirect === undefined) return undefined
222
+ return typeof redirect === "string" ? redirect : redirect.to
223
+ }
224
+
225
+ function reset(): void {
226
+ pages = new Map()
227
+ findings = []
228
+ externals = new Map()
229
+ scanned = 0
230
+ }
231
+
232
+ return { page, done }
233
+ }
@@ -0,0 +1,41 @@
1
+ export const EXTERNAL_TIMEOUT_MS = 5000
2
+ export const EXTERNAL_CONCURRENCY = 8
3
+
4
+ const REASONS = new Set([405, 501])
5
+
6
+ async function ask(url: string, method: "HEAD" | "GET"): Promise<number> {
7
+ const response = await globalThis.fetch(url, {
8
+ method,
9
+ headers: { "user-agent": "hamur-link-checker" },
10
+ signal: AbortSignal.timeout(EXTERNAL_TIMEOUT_MS),
11
+ redirect: "follow",
12
+ })
13
+ await response.body?.cancel()
14
+ return response.status
15
+ }
16
+
17
+ /** The finding text of one external URL, or `undefined` when it answers below 400; `HEAD`, then `GET` once for a 405 or 501. */
18
+ export async function probe(url: string): Promise<string | undefined> {
19
+ try {
20
+ let status = await ask(url, "HEAD")
21
+ if (REASONS.has(status)) status = await ask(url, "GET")
22
+ return status >= 400 ? `external link ${url} answered ${status}` : undefined
23
+ } catch (error) {
24
+ const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")
25
+ return `external link ${url} failed: ${timedOut ? `no answer in ${EXTERNAL_TIMEOUT_MS / 1000} s` : error instanceof Error ? error.message : String(error)}`
26
+ }
27
+ }
28
+
29
+ /** Each distinct URL once, at most `EXTERNAL_CONCURRENCY` at a time; the map holds the finding text of the URLs that failed. */
30
+ export async function probeAll(urls: Iterable<string>): Promise<Map<string, string>> {
31
+ const queue = [...new Set(urls)]
32
+ const failed = new Map<string, string>()
33
+ const worker = async () => {
34
+ for (let url = queue.shift(); url !== undefined; url = queue.shift()) {
35
+ const message = await probe(url)
36
+ if (message !== undefined) failed.set(url, message)
37
+ }
38
+ }
39
+ await Promise.all(Array.from({ length: Math.min(EXTERNAL_CONCURRENCY, queue.length) }, worker))
40
+ return failed
41
+ }
@@ -0,0 +1,69 @@
1
+ import type { LinkCheckerConfig, LinkRuleId } from "../types.ts"
2
+ import { DiagnosticError } from "hamur/kit"
3
+
4
+ export type LinkLevel = "error" | "warning"
5
+
6
+ export const LINK_RULES: Record<LinkRuleId, LinkLevel> = {
7
+ broken: "error",
8
+ "missing-anchor": "warning",
9
+ redirect: "warning",
10
+ "trailing-slash": "warning",
11
+ "absolute-site-url": "warning",
12
+ "javascript-href": "error",
13
+ "empty-text": "warning",
14
+ "double-slash": "warning",
15
+ uppercase: "warning",
16
+ whitespace: "warning",
17
+ "external-broken": "warning",
18
+ }
19
+
20
+ export interface ResolvedLinkChecker {
21
+ failOnError: boolean
22
+ external: boolean
23
+ report: Array<"json" | "markdown" | "html">
24
+ exclude: string[]
25
+ rules: Partial<Record<LinkRuleId, LinkLevel | false>>
26
+ }
27
+
28
+ const KEYS = ["failOnError", "external", "report", "exclude", "rules"]
29
+ const FORMATS = ["json", "markdown", "html"]
30
+
31
+ const show = (value: unknown): string => JSON.stringify(value) ?? String(value)
32
+
33
+ function fail(message: string): never {
34
+ throw new DiagnosticError("HAMUR_E6401", message)
35
+ }
36
+
37
+ /** `seo.linkChecker`, `true` when unset; `undefined` when it is `false`. */
38
+ export function resolveLinkChecker(input: unknown): ResolvedLinkChecker | undefined {
39
+ const base: ResolvedLinkChecker = { failOnError: false, external: false, report: [], exclude: [], rules: {} }
40
+ if (input === undefined || input === true) return base
41
+ if (input === false) return undefined
42
+ if (typeof input !== "object" || input === null || Array.isArray(input))
43
+ fail(`seo.linkChecker must be a boolean or an object (got ${show(input)})`)
44
+ for (const key of Object.keys(input)) if (!KEYS.includes(key)) fail(`seo.linkChecker.${key} is not an option`)
45
+ const { failOnError = false, external = false, report = [], exclude = [], rules = {} } = input as LinkCheckerConfig
46
+ if (typeof failOnError !== "boolean") fail(`seo.linkChecker.failOnError must be a boolean (got ${show(failOnError)})`)
47
+ if (typeof external !== "boolean") fail(`seo.linkChecker.external must be a boolean (got ${show(external)})`)
48
+ if (!Array.isArray(report))
49
+ fail(`seo.linkChecker.report must be an array of "json", "markdown" or "html" (got ${show(report)})`)
50
+ report.forEach((format, index) => {
51
+ if (!FORMATS.includes(format))
52
+ fail(`seo.linkChecker.report[${index}] must be "json", "markdown" or "html" (got ${show(format)})`)
53
+ })
54
+ if (!Array.isArray(exclude))
55
+ fail(`seo.linkChecker.exclude must be an array of route rule patterns (got ${show(exclude)})`)
56
+ exclude.forEach((pattern, index) => {
57
+ if (typeof pattern !== "string" || !pattern.startsWith("/"))
58
+ fail(`seo.linkChecker.exclude[${index}] must be a route rule pattern starting with "/"`)
59
+ })
60
+ if (typeof rules !== "object" || rules === null || Array.isArray(rules))
61
+ fail(`seo.linkChecker.rules must be an object (got ${show(rules)})`)
62
+ for (const [id, level] of Object.entries(rules)) {
63
+ if (!Object.hasOwn(LINK_RULES, id))
64
+ fail(`seo.linkChecker.rules.${id} is not a link rule (have: ${Object.keys(LINK_RULES).join(", ")})`)
65
+ if (level !== "error" && level !== "warning" && level !== false)
66
+ fail(`seo.linkChecker.rules.${id} must be "error", "warning" or false (got ${show(level)})`)
67
+ }
68
+ return { failOnError, external, report: [...report], exclude: [...exclude], rules: { ...rules } }
69
+ }
@@ -0,0 +1,49 @@
1
+ import { mkdir, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { escapeXml, type LinkFinding } from "hamur/server/internal"
4
+
5
+ export type ReportFormat = "json" | "markdown" | "html"
6
+
7
+ const FILES: Record<ReportFormat, string> = {
8
+ json: "link-checker.json",
9
+ markdown: "link-checker.md",
10
+ html: "link-checker.html",
11
+ }
12
+
13
+ const cell = (text: string) => text.replace(/\|/g, "\\|").replace(/\n/g, " ")
14
+
15
+ function markdown(findings: LinkFinding[]): string {
16
+ const rows = findings.map(
17
+ ({ page, level, rule, link, message }) => `| ${[page, level, rule, link, message].map(cell).join(" | ")} |`,
18
+ )
19
+ return ["| Page | Level | Rule | Link | Message |", "|---|---|---|---|---|", ...rows, ""].join("\n")
20
+ }
21
+
22
+ function html(pages: number, findings: LinkFinding[]): string {
23
+ const rows = findings.map(
24
+ ({ page, level, rule, link, message }) =>
25
+ `<tr><td>${[page, level, rule, link, message].map(escapeXml).join("</td><td>")}</td></tr>`,
26
+ )
27
+ return `<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><title>Link checker</title><style>body{font:14px system-ui,sans-serif;margin:2rem}table{border-collapse:collapse}td,th{border:1px solid #888;padding:.25rem .5rem;text-align:left}</style></head><body><h1>Link checker</h1><p>${pages} pages, ${findings.length} findings</p><table><thead><tr><th>Page</th><th>Level</th><th>Rule</th><th>Link</th><th>Message</th></tr></thead><tbody>${rows.join("")}</tbody></table></body></html>\n`
28
+ }
29
+
30
+ /** The files of `seo.linkChecker.report` under `<buildDir>/reports/`, never in `.output/`. */
31
+ export async function writeReports(
32
+ buildDir: string,
33
+ formats: ReportFormat[],
34
+ pages: number,
35
+ findings: LinkFinding[],
36
+ ): Promise<void> {
37
+ if (!formats.length) return
38
+ const dir = join(buildDir, "reports")
39
+ await mkdir(dir, { recursive: true })
40
+ for (const format of new Set(formats)) {
41
+ const body =
42
+ format === "json"
43
+ ? `${JSON.stringify({ pages, findings }, null, 2)}\n`
44
+ : format === "markdown"
45
+ ? markdown(findings)
46
+ : html(pages, findings)
47
+ await writeFile(join(dir, FILES[format]), body)
48
+ }
49
+ }
@@ -0,0 +1,123 @@
1
+ export interface ScannedLink {
2
+ href: string
3
+ /** Whether the link has text, an `aria-label`, `aria-labelledby`, a `title` or an `<img alt>`. */
4
+ named: boolean
5
+ }
6
+
7
+ export interface PageScan {
8
+ links: ScannedLink[]
9
+ ids: Set<string>
10
+ }
11
+
12
+ const INERT = /<(script|style)\b[\s\S]*?<\/\1\s*>|<!--[\s\S]*?-->/gi
13
+ const TAG = /<(\/?)([a-zA-Z][^\s>/]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g
14
+ const ATTRIBUTE = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g
15
+ const ENTITY = /&(?:#x([0-9a-f]+)|#(\d+)|([a-z]+));/gi
16
+ const NAMED: Record<string, string> = {
17
+ amp: "&",
18
+ quot: '"',
19
+ lt: "<",
20
+ gt: ">",
21
+ apos: "'",
22
+ nbsp: " ",
23
+ copy: "©",
24
+ reg: "®",
25
+ trade: "™",
26
+ hellip: "…",
27
+ mdash: "—",
28
+ ndash: "–",
29
+ lsquo: "‘",
30
+ rsquo: "’",
31
+ ldquo: "“",
32
+ rdquo: "”",
33
+ laquo: "«",
34
+ raquo: "»",
35
+ middot: "·",
36
+ bull: "•",
37
+ times: "×",
38
+ }
39
+
40
+ export function decode(text: string): string {
41
+ return text.replace(ENTITY, (whole, hex?: string, decimal?: string, name?: string) => {
42
+ if (name) return Object.hasOwn(NAMED, name.toLowerCase()) ? NAMED[name.toLowerCase()]! : whole
43
+ const code = Number.parseInt((hex ?? decimal)!, hex ? 16 : 10)
44
+ return code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : ""
45
+ })
46
+ }
47
+
48
+ export function attributes(source: string): Map<string, string> {
49
+ const found = new Map<string, string>()
50
+ for (const [, name, quoted, single, bare] of source.matchAll(ATTRIBUTE)) {
51
+ const key = name!.toLowerCase()
52
+ if (!found.has(key)) found.set(key, decode(quoted ?? single ?? bare ?? ""))
53
+ }
54
+ return found
55
+ }
56
+
57
+ /** The `<a href>` elements of a page with their accessible text, and every `id` and `<a name>`, by a tag scan. */
58
+ export function scanPage(html: string): PageScan {
59
+ const links: ScannedLink[] = []
60
+ const ids = new Set<string>()
61
+ const source = html.replace(INERT, (match) => " ".repeat(match.length))
62
+ let open: { href: string; named: boolean; text: string } | undefined
63
+ const close = () => {
64
+ if (open) links.push({ href: open.href, named: open.named || open.text.trim() !== "" })
65
+ open = undefined
66
+ }
67
+ let last = 0
68
+ for (const match of source.matchAll(TAG)) {
69
+ if (open) open.text += decode(source.slice(last, match.index!))
70
+ last = match.index! + match[0].length
71
+ const [, closing, rawName, rest] = match
72
+ const name = rawName!.toLowerCase()
73
+ if (closing) {
74
+ if (name === "a") close()
75
+ continue
76
+ }
77
+ const attrs = attributes(rest!)
78
+ const id = attrs.get("id")
79
+ if (id) ids.add(id)
80
+ if (name === "a") {
81
+ close()
82
+ const anchor = attrs.get("name")
83
+ if (anchor) ids.add(anchor)
84
+ const href = attrs.get("href")
85
+ if (href !== undefined)
86
+ open = {
87
+ href,
88
+ named: ["aria-label", "aria-labelledby", "title"].some((key) => (attrs.get(key) ?? "").trim() !== ""),
89
+ text: "",
90
+ }
91
+ } else if (name === "img" && open && (attrs.get("alt") ?? "").trim() !== "") {
92
+ open.named = true
93
+ }
94
+ }
95
+ if (open) open.text += decode(source.slice(last))
96
+ close()
97
+ return { links, ids }
98
+ }
99
+
100
+ export type HtmlToken =
101
+ { text: string } | { open: string; attrs: Map<string, string>; selfClosing: boolean } | { close: string }
102
+
103
+ const DECLARATION = /<![^>]*>|<\?[\s\S]*?\?>/g
104
+
105
+ /** The tags and text of a page in order, comments, scripts, styles and declarations left out; text is raw, entities not decoded. */
106
+ export function tokenize(html: string): HtmlToken[] {
107
+ const source = html.replace(INERT, "").replace(DECLARATION, "")
108
+ const tokens: HtmlToken[] = []
109
+ let last = 0
110
+ const text = (to: number) => {
111
+ if (to > last) tokens.push({ text: source.slice(last, to) })
112
+ }
113
+ for (const match of source.matchAll(TAG)) {
114
+ text(match.index!)
115
+ last = match.index! + match[0].length
116
+ const [, closing, rawName, rest] = match
117
+ const name = rawName!.toLowerCase()
118
+ if (closing) tokens.push({ close: name })
119
+ else tokens.push({ open: name, attrs: attributes(rest!), selfClosing: rest!.trimEnd().endsWith("/") })
120
+ }
121
+ text(source.length)
122
+ return tokens
123
+ }