@hamur/seo 0.0.0-stage → 0.0.1

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 +106 -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,222 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { alternates, baseURL, chunkSize, paths, signature, sources } from "#hamur/seo/sitemap"
3
+ import {
4
+ $fetch,
5
+ defineCachedFunction,
6
+ defineHandler,
7
+ FetchError,
8
+ prerenderRoutes,
9
+ useLogger,
10
+ useSiteConfig,
11
+ type HamurEvent,
12
+ } from "hamur/server"
13
+ import { mergeUrls, oversize, partCount, partRange, rootXml } from "../sitemap/answer.ts"
14
+ import { readCount, readRows, readSource } from "../sitemap/entries.ts"
15
+ import { absoluteUrl, urlsetXml, type SitemapUrl } from "../sitemap/xml.ts"
16
+
17
+ const NEEDS_URL = "@hamur/seo: sitemap needs site.url (set site.url or HAMUR_SITE_URL)"
18
+ const LOOP = "@hamur/seo: a sitemap source fetched the sitemap"
19
+ const LOOP_HEADER = "x-hamur-sitemap-source"
20
+ const XML = { "content-type": "application/xml; charset=utf-8" }
21
+
22
+ class SourceFailure extends Error {
23
+ constructor(
24
+ readonly source: string,
25
+ message: string,
26
+ ) {
27
+ super(message)
28
+ }
29
+ }
30
+
31
+ const failed = (event: HamurEvent, log: string, body: string, status = 500): Response => {
32
+ useLogger(event).child({ name: "seo" }).error(log)
33
+ return new Response(body, { status, headers: { "content-type": "text/plain; charset=utf-8" } })
34
+ }
35
+
36
+ const reason = (error: unknown): string =>
37
+ error instanceof FetchError ? String(error.status) : error instanceof Error ? error.message : String(error)
38
+
39
+ interface PagedCount {
40
+ source: string
41
+ total: number
42
+ }
43
+
44
+ interface Listing {
45
+ urls: SitemapUrl[]
46
+ paged: PagedCount[]
47
+ }
48
+
49
+ async function askSource(source: string, offset: number, limit: number): Promise<unknown> {
50
+ try {
51
+ return (await $fetch.raw<unknown>(source, { retry: 0, query: { offset, limit }, headers: { [LOOP_HEADER]: "1" } }))
52
+ .data
53
+ } catch (error) {
54
+ throw new SourceFailure(source, `sitemap source ${source} failed: ${reason(error)}`)
55
+ }
56
+ }
57
+
58
+ const cachedListing = defineCachedFunction(
59
+ async (event: HamurEvent, origin: string): Promise<Listing> => {
60
+ const log = useLogger(event).child({ name: "seo" })
61
+ const pages = paths.map((path): SitemapUrl => {
62
+ const alternate = alternates[path]
63
+ return {
64
+ loc: absoluteUrl(origin, baseURL, path),
65
+ ...(alternate
66
+ ? {
67
+ alternates: alternate.map(([hreflang, other]) => ({
68
+ hreflang,
69
+ href: absoluteUrl(origin, baseURL, other),
70
+ })),
71
+ }
72
+ : {}),
73
+ }
74
+ })
75
+ const settled = await Promise.allSettled(
76
+ sources.map(async (source): Promise<{ urls: SitemapUrl[] } | { count: PagedCount }> => {
77
+ const data = await askSource(source, 0, 0)
78
+ try {
79
+ if (Array.isArray(data))
80
+ return { urls: readSource(source, data, { origin, baseURL, warn: (message) => log.warn(message) }) }
81
+ return { count: { source, total: readCount(source, data) } }
82
+ } catch (error) {
83
+ throw new SourceFailure(source, reason(error))
84
+ }
85
+ }),
86
+ )
87
+ const answers = settled.map((result) => {
88
+ if (result.status === "rejected") throw result.reason
89
+ return result.value
90
+ })
91
+ return {
92
+ urls: mergeUrls([pages, ...answers.flatMap((answer) => ("urls" in answer ? [answer.urls] : []))]),
93
+ paged: answers.flatMap((answer) => ("count" in answer ? [answer.count] : [])),
94
+ }
95
+ },
96
+ { maxAge: 600, swr: false, getKey: (_event, origin) => `${signature}:${origin}` },
97
+ )
98
+
99
+ const total = (listing: Listing): number => listing.paged.reduce((sum, { total }) => sum + total, listing.urls.length)
100
+
101
+ async function readRange(
102
+ event: HamurEvent,
103
+ origin: string,
104
+ listing: Listing,
105
+ from: number,
106
+ to: number,
107
+ ): Promise<SitemapUrl[]> {
108
+ const log = useLogger(event).child({ name: "seo" })
109
+ const urls = listing.urls.slice(from, to)
110
+ let start = listing.urls.length
111
+ for (const { source, total } of listing.paged) {
112
+ const lo = Math.max(from, start)
113
+ const hi = Math.min(to, start + total)
114
+ if (lo < hi) {
115
+ const data = await askSource(source, lo - start, hi - lo)
116
+ try {
117
+ urls.push(
118
+ ...readSource(source, readRows(source, data, hi - lo), {
119
+ origin,
120
+ baseURL,
121
+ warn: (message) => log.warn(message),
122
+ }),
123
+ )
124
+ } catch (error) {
125
+ throw new SourceFailure(source, reason(error))
126
+ }
127
+ }
128
+ start += total
129
+ }
130
+ return urls
131
+ }
132
+
133
+ const sourceFailed = (event: HamurEvent, error: unknown): Response =>
134
+ error instanceof SourceFailure
135
+ ? failed(event, error.message, `@hamur/seo: sitemap source ${error.source} failed`)
136
+ : failed(event, `sitemap failed: ${reason(error)}`, "@hamur/seo: sitemap failed")
137
+
138
+ async function sitemapListing(event: HamurEvent): Promise<{ listing: Listing; origin: string } | Response> {
139
+ if (event.request.headers.has(LOOP_HEADER)) return failed(event, LOOP, LOOP, 508)
140
+ const { url: origin } = useSiteConfig(event)
141
+ if (origin === undefined) return failed(event, NEEDS_URL, NEEDS_URL)
142
+ try {
143
+ return { listing: await cachedListing(event, origin), origin }
144
+ } catch (error) {
145
+ return sourceFailed(event, error)
146
+ }
147
+ }
148
+
149
+ export async function sitemapUrls(event: HamurEvent): Promise<SitemapUrl[] | Response> {
150
+ const found = await sitemapListing(event)
151
+ if (found instanceof Response) return found
152
+ const { listing, origin } = found
153
+ try {
154
+ const urls: SitemapUrl[] = []
155
+ const count = total(listing)
156
+ for (let from = 0; from < count; from += chunkSize)
157
+ urls.push(...(await readRange(event, origin, listing, from, Math.min(from + chunkSize, count))))
158
+ return urls
159
+ } catch (error) {
160
+ return sourceFailed(event, error)
161
+ }
162
+ }
163
+
164
+ const answer = (event: HamurEvent, path: string, xml: string): Response => {
165
+ const large = oversize(path, xml)
166
+ if (large) useLogger(event).child({ name: "seo" }).warn(large)
167
+ return new Response(xml, { headers: XML })
168
+ }
169
+
170
+ export const sitemapXml = defineHandler({
171
+ route: "/sitemap.xml",
172
+ method: "GET",
173
+ raw: true,
174
+ async handler(_, { event }) {
175
+ const found = await sitemapListing(event)
176
+ if (found instanceof Response) return found
177
+ const { listing, origin } = found
178
+ const part = (number: number) => `${baseURL}sitemap-${number}.xml`
179
+ const count = total(listing)
180
+ const parts = partCount(count, chunkSize)
181
+ let urls = listing.urls
182
+ if (parts) prerenderRoutes(event, ...Array.from({ length: parts }, (_, index) => part(index + 1)))
183
+ else {
184
+ try {
185
+ urls = await readRange(event, origin, listing, 0, count)
186
+ } catch (error) {
187
+ return sourceFailed(event, error)
188
+ }
189
+ }
190
+ return answer(
191
+ event,
192
+ `${baseURL}sitemap.xml`,
193
+ rootXml(urls, parts, (number) => new URL(part(number), origin).href),
194
+ )
195
+ },
196
+ })
197
+
198
+ export const sitemapPart = defineHandler({
199
+ route: "/sitemap-:n.xml",
200
+ method: "GET",
201
+ raw: true,
202
+ async handler(_, { event }) {
203
+ const notFound = () =>
204
+ new Response("Not Found", { status: 404, headers: { "content-type": "text/plain; charset=utf-8" } })
205
+ const number = /^[1-9]\d*$/.test(String(event.params.n)) ? Number(event.params.n) : 0
206
+ if (number === 0) return notFound()
207
+ const found = await sitemapListing(event)
208
+ if (found instanceof Response) return found
209
+ const { listing, origin } = found
210
+ const range = partRange(total(listing), chunkSize, number)
211
+ if (range === undefined) return notFound()
212
+ try {
213
+ return answer(
214
+ event,
215
+ `${baseURL}sitemap-${number}.xml`,
216
+ urlsetXml(await readRange(event, origin, listing, range[0], range[1])),
217
+ )
218
+ } catch (error) {
219
+ return sourceFailed(event, error)
220
+ }
221
+ },
222
+ })
package/src/share.ts ADDED
@@ -0,0 +1,56 @@
1
+ export interface ShareLinks {
2
+ x: string
3
+ facebook: string
4
+ linkedin: string
5
+ bluesky: string
6
+ email: string
7
+ whatsapp: string
8
+ reddit: string
9
+ telegram: string
10
+ mastodon?: string
11
+ }
12
+
13
+ export interface ShareLinksInput {
14
+ url: string
15
+ title: string
16
+ text?: string
17
+ mastodon?: string
18
+ }
19
+
20
+ const hostName = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d{1,5})?$/i
21
+
22
+ export function shareLinks(input: ShareLinksInput): ShareLinks {
23
+ let scheme: string
24
+ try {
25
+ scheme = new URL(input.url).protocol
26
+ } catch {
27
+ scheme = ""
28
+ }
29
+ if (scheme !== "http:" && scheme !== "https:")
30
+ throw new Error(`shareLinks: url must be absolute (got ${JSON.stringify(input.url)})`)
31
+ if (input.mastodon !== undefined && !hostName.test(input.mastodon)) {
32
+ throw new Error(
33
+ `shareLinks: mastodon must be a host name such as "mastodon.social" (got ${JSON.stringify(input.mastodon)})`,
34
+ )
35
+ }
36
+
37
+ const e = encodeURIComponent
38
+ const url = e(input.url)
39
+ const title = e(input.title)
40
+ const text = input.text ?? input.title
41
+ const textOnly = e(text)
42
+ const textAndUrl = e(`${text} ${input.url}`)
43
+
44
+ const links: ShareLinks = {
45
+ x: `https://x.com/intent/tweet?url=${url}&text=${textOnly}`,
46
+ facebook: `https://www.facebook.com/sharer/sharer.php?u=${url}`,
47
+ linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${url}`,
48
+ bluesky: `https://bsky.app/intent/compose?text=${textAndUrl}`,
49
+ email: `mailto:?subject=${title}&body=${e(`${text}\n\n${input.url}`)}`,
50
+ whatsapp: `https://wa.me/?text=${textAndUrl}`,
51
+ reddit: `https://www.reddit.com/submit?url=${url}&title=${title}`,
52
+ telegram: `https://t.me/share/url?url=${url}&text=${textOnly}`,
53
+ }
54
+ if (input.mastodon !== undefined) links.mastodon = `https://${input.mastodon}/share?text=${textAndUrl}`
55
+ return links
56
+ }
@@ -0,0 +1,66 @@
1
+ export interface I18nLocales {
2
+ locales: Array<{ code: string; language: string }>
3
+ defaultLocale: string
4
+ }
5
+
6
+ export interface PageRoute {
7
+ name: string
8
+ path: string
9
+ }
10
+
11
+ export type Alternates = Record<string, Array<[string, string]>>
12
+
13
+ const SEPARATOR = "___"
14
+
15
+ export function readLocales(input: unknown): I18nLocales | undefined {
16
+ if (typeof input !== "object" || input === null) return undefined
17
+ const { locales, defaultLocale } = input as { locales?: unknown; defaultLocale?: unknown }
18
+ if (!Array.isArray(locales) || typeof defaultLocale !== "string") return undefined
19
+ const found = locales.flatMap((locale: unknown) => {
20
+ const entry =
21
+ typeof locale === "string" ? { code: locale } : (locale as { code?: unknown; language?: unknown } | null)
22
+ if (typeof entry?.code !== "string") return []
23
+ return [
24
+ {
25
+ code: entry.code,
26
+ language:
27
+ typeof (entry as { language?: unknown }).language === "string"
28
+ ? (entry as { language: string }).language
29
+ : entry.code,
30
+ },
31
+ ]
32
+ })
33
+ return found.length ? { locales: found, defaultLocale } : undefined
34
+ }
35
+
36
+ export function pageAlternates(
37
+ pages: PageRoute[],
38
+ i18n: I18nLocales,
39
+ listed: ReadonlySet<string>,
40
+ clean: (path: string) => string | undefined,
41
+ ): Alternates {
42
+ const byName = new Map<string, Map<string, string>>()
43
+ for (const { name, path } of pages) {
44
+ const index = name.indexOf(SEPARATOR)
45
+ const base = index === -1 ? name : name.slice(0, index)
46
+ const code = index === -1 ? i18n.defaultLocale : name.slice(index + SEPARATOR.length)
47
+ const cleaned = clean(path)
48
+ if (cleaned === undefined || /[:*]/.test(path)) continue
49
+ const copies = byName.get(base) ?? new Map<string, string>()
50
+ copies.set(code, cleaned)
51
+ byName.set(base, copies)
52
+ }
53
+ const result: Alternates = {}
54
+ for (const copies of byName.values()) {
55
+ const pairs: Array<[string, string]> = []
56
+ for (const { code, language } of i18n.locales) {
57
+ const path = copies.get(code)
58
+ if (path !== undefined && listed.has(path)) pairs.push([language, path])
59
+ }
60
+ const fallback = copies.get(i18n.defaultLocale)
61
+ if (fallback !== undefined && listed.has(fallback)) pairs.push(["x-default", fallback])
62
+ if (pairs.length === 0) continue
63
+ for (const path of copies.values()) if (listed.has(path)) result[path] = pairs
64
+ }
65
+ return result
66
+ }
@@ -0,0 +1,42 @@
1
+ import { indexXml, urlsetXml, type SitemapUrl } from "./xml.ts"
2
+
3
+ export function mergeUrls(lists: SitemapUrl[][]): SitemapUrl[] {
4
+ const byLoc = new Map<string, SitemapUrl>()
5
+ for (const list of lists) for (const url of list) byLoc.set(url.loc, url)
6
+ return [...byLoc.values()]
7
+ }
8
+
9
+ export const partCount = (total: number, chunkSize: number): number =>
10
+ total > chunkSize ? Math.ceil(total / chunkSize) : 0
11
+
12
+ export function rootXml(urls: SitemapUrl[], parts: number, partLoc: (part: number) => string): string {
13
+ return parts === 0 ? urlsetXml(urls) : indexXml(Array.from({ length: parts }, (_, index) => partLoc(index + 1)))
14
+ }
15
+
16
+ export function partRange(total: number, chunkSize: number, part: number): [from: number, to: number] | undefined {
17
+ if (!Number.isInteger(part) || part < 1 || part > partCount(total, chunkSize)) return undefined
18
+ return [(part - 1) * chunkSize, Math.min(part * chunkSize, total)]
19
+ }
20
+
21
+ const LIMIT = 52_428_800
22
+
23
+ function utf8Length(text: string): number {
24
+ let bytes = 0
25
+ for (let index = 0; index < text.length; index++) {
26
+ const code = text.charCodeAt(index)
27
+ bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : 3
28
+ if (code >= 0xd800 && code < 0xdc00 && index + 1 < text.length) {
29
+ index++
30
+ bytes++
31
+ }
32
+ }
33
+ return bytes
34
+ }
35
+
36
+ export function oversize(path: string, xml: string): string | undefined {
37
+ if (xml.length * 3 <= LIMIT) return undefined
38
+ const bytes = utf8Length(xml)
39
+ return bytes > LIMIT
40
+ ? `${path} is ${Math.ceil(bytes / 1_048_576)} MB, over the 50 MB a sitemap may hold; lower seo.sitemap.chunkSize`
41
+ : undefined
42
+ }
@@ -0,0 +1,136 @@
1
+ import type { SitemapEntry } from "../types.ts"
2
+ import { resolveUrl, type SitemapUrl } from "./xml.ts"
3
+
4
+ export interface SourceContext {
5
+ origin: string
6
+ baseURL: string
7
+ warn(message: string): void
8
+ }
9
+
10
+ const CHANGE_FREQUENCIES = ["always", "hourly", "daily", "weekly", "monthly", "yearly", "never"]
11
+
12
+ const isObject = (value: unknown): value is Record<string, unknown> =>
13
+ typeof value === "object" && value !== null && !Array.isArray(value)
14
+ const isText = (value: unknown): value is string => typeof value === "string" && value !== ""
15
+
16
+ const W3C_DATETIME = /^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/
17
+
18
+ function dateOf(value: unknown): string | undefined {
19
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : value.toISOString()
20
+ if (typeof value !== "string" || !W3C_DATETIME.test(value) || Number.isNaN(Date.parse(value))) return undefined
21
+ return value
22
+ }
23
+
24
+ const isWeb = (url: string | undefined): url is string => url !== undefined && /^https?:\/\//.test(url)
25
+
26
+ export function readCount(path: string, answer: unknown): number {
27
+ if (
28
+ !isObject(answer) ||
29
+ !Array.isArray(answer.entries) ||
30
+ typeof answer.total !== "number" ||
31
+ !Number.isInteger(answer.total) ||
32
+ answer.total < 0
33
+ ) {
34
+ throw new Error(`sitemap source ${path} answered a value that is not an array of entries`)
35
+ }
36
+ return answer.total
37
+ }
38
+
39
+ export function readRows(path: string, answer: unknown, limit: number): unknown[] {
40
+ readCount(path, answer)
41
+ return (answer as { entries: unknown[] }).entries.slice(0, limit)
42
+ }
43
+
44
+ export function readSource(path: string, answer: unknown, { origin, baseURL, warn }: SourceContext): SitemapUrl[] {
45
+ const bad = () => new Error(`sitemap source ${path} answered a value that is not an array of entries`)
46
+ if (!Array.isArray(answer)) throw bad()
47
+ const said = new Set<string>()
48
+ const siteOrigin = new URL(origin).origin
49
+ const web = (value: string) => {
50
+ const url = resolveUrl(origin, baseURL, value)
51
+ return isWeb(url) ? url : undefined
52
+ }
53
+ return answer.flatMap((value: unknown): SitemapUrl[] => {
54
+ if (!isObject(value) || typeof value.loc !== "string") throw bad()
55
+ const entry = value as unknown as SitemapEntry & Record<string, unknown>
56
+ const loc = web(entry.loc)
57
+ const leave = (field: string, message: string) => {
58
+ if (said.has(field)) return
59
+ said.add(field)
60
+ warn(`sitemap entry ${entry.loc}: ${message}; left out`)
61
+ }
62
+ if (loc === undefined || new URL(loc).origin !== siteOrigin) {
63
+ leave("loc", `loc is not an http(s) URL on ${siteOrigin}`)
64
+ return []
65
+ }
66
+ const url: SitemapUrl = { loc }
67
+ if (entry.lastmod !== undefined) {
68
+ const lastmod = dateOf(entry.lastmod)
69
+ if (lastmod === undefined)
70
+ leave("lastmod", `lastmod ${JSON.stringify(entry.lastmod) ?? String(entry.lastmod)} is not a date`)
71
+ else url.lastmod = lastmod
72
+ }
73
+ if (entry.changefreq !== undefined) {
74
+ if (typeof entry.changefreq === "string" && CHANGE_FREQUENCIES.includes(entry.changefreq))
75
+ url.changefreq = entry.changefreq
76
+ else
77
+ leave(
78
+ "changefreq",
79
+ `changefreq ${JSON.stringify(entry.changefreq) ?? String(entry.changefreq)} is not one of ${CHANGE_FREQUENCIES.join(", ")}`,
80
+ )
81
+ }
82
+ if (entry.priority !== undefined) {
83
+ if (typeof entry.priority === "number" && entry.priority >= 0 && entry.priority <= 1)
84
+ url.priority = entry.priority
85
+ else leave("priority", `priority ${JSON.stringify(entry.priority) ?? String(entry.priority)} is outside 0 to 1`)
86
+ }
87
+ const images = (Array.isArray(entry.images) ? entry.images : []).flatMap((image: unknown) => {
88
+ const resolved = isObject(image) && isText(image.loc) ? web(image.loc) : undefined
89
+ if (resolved === undefined) leave("images", "an image needs an http(s) loc")
90
+ return resolved === undefined ? [] : [resolved]
91
+ })
92
+ if (images.length) url.images = images
93
+ const videos = (Array.isArray(entry.videos) ? entry.videos : []).flatMap((video: unknown) => {
94
+ if (!isObject(video) || !isText(video.thumbnail_loc) || !isText(video.title) || !isText(video.description)) {
95
+ leave("videos", "a video needs thumbnail_loc, title and description")
96
+ return []
97
+ }
98
+ if (!isText(video.content_loc) && !isText(video.player_loc)) {
99
+ leave("videos", "a video needs content_loc or player_loc")
100
+ return []
101
+ }
102
+ const thumbnail = web(video.thumbnail_loc)
103
+ const content = isText(video.content_loc) ? web(video.content_loc) : undefined
104
+ const player = isText(video.player_loc) ? web(video.player_loc) : undefined
105
+ if (
106
+ thumbnail === undefined ||
107
+ (isText(video.content_loc) && content === undefined) ||
108
+ (isText(video.player_loc) && player === undefined)
109
+ ) {
110
+ leave("videos", "a video URL is not an http(s) URL")
111
+ return []
112
+ }
113
+ return [
114
+ {
115
+ thumbnail_loc: thumbnail,
116
+ title: video.title,
117
+ description: video.description,
118
+ ...(content === undefined ? {} : { content_loc: content }),
119
+ ...(player === undefined ? {} : { player_loc: player }),
120
+ ...(typeof video.duration === "number" && Number.isFinite(video.duration)
121
+ ? { duration: video.duration }
122
+ : {}),
123
+ },
124
+ ]
125
+ })
126
+ if (videos.length) url.videos = videos
127
+ const alternates = (Array.isArray(entry.alternates) ? entry.alternates : []).flatMap((alternate: unknown) => {
128
+ const href =
129
+ isObject(alternate) && isText(alternate.hreflang) && isText(alternate.href) ? web(alternate.href) : undefined
130
+ if (href === undefined) leave("alternates", "an alternate needs hreflang and an http(s) href")
131
+ return href === undefined ? [] : [{ hreflang: (alternate as { hreflang: string }).hreflang, href }]
132
+ })
133
+ if (alternates.length) url.alternates = alternates
134
+ return [url]
135
+ })
136
+ }
@@ -0,0 +1,47 @@
1
+ import type { SitemapConfig } from "../types.ts"
2
+ import { DiagnosticError } from "hamur/kit"
3
+
4
+ export const MAX_CHUNK_SIZE = 50_000
5
+
6
+ export interface ResolvedSitemap {
7
+ sources: string[]
8
+ exclude: string[]
9
+ chunkSize: number
10
+ }
11
+
12
+ const KEYS = ["sources", "exclude", "chunkSize"]
13
+
14
+ const show = (value: unknown): string => JSON.stringify(value) ?? String(value)
15
+
16
+ function fail(message: string): never {
17
+ throw new DiagnosticError("HAMUR_E6402", message)
18
+ }
19
+
20
+ export function resolveSitemap(input: unknown): ResolvedSitemap | undefined {
21
+ if (input === undefined || input === true) return { sources: [], exclude: [], chunkSize: MAX_CHUNK_SIZE }
22
+ if (input === false) return undefined
23
+ if (typeof input !== "object" || input === null || Array.isArray(input))
24
+ fail(`seo.sitemap must be a boolean or an object (got ${show(input)})`)
25
+ for (const key of Object.keys(input)) if (!KEYS.includes(key)) fail(`seo.sitemap.${key} is not an option`)
26
+ const { sources = [], exclude = [], chunkSize = MAX_CHUNK_SIZE } = input as SitemapConfig
27
+ if (!Array.isArray(sources)) fail(`seo.sitemap.sources must be an array of handler routes (got ${show(sources)})`)
28
+ sources.forEach((source, index) => {
29
+ if (typeof source !== "string" || !source.startsWith("/"))
30
+ fail(`seo.sitemap.sources[${index}] ${show(source)} must be a path starting with "/"`)
31
+ if (source === "/sitemap.xml" || /^\/sitemap-[^/]*\.xml$/.test(source))
32
+ fail(`seo.sitemap.sources[${index}] ${show(source)} is a route of the sitemap itself`)
33
+ if (/[:*]/.test(source))
34
+ fail(
35
+ `seo.sitemap.sources[${index}] ${show(source)} must be the literal route of a handler, without params or wildcards`,
36
+ )
37
+ })
38
+ if (!Array.isArray(exclude))
39
+ fail(`seo.sitemap.exclude must be an array of route rule patterns (got ${show(exclude)})`)
40
+ exclude.forEach((pattern, index) => {
41
+ if (typeof pattern !== "string" || !pattern.startsWith("/"))
42
+ fail(`seo.sitemap.exclude[${index}] must be a route rule pattern starting with "/"`)
43
+ })
44
+ if (!Number.isInteger(chunkSize) || chunkSize < 1 || chunkSize > MAX_CHUNK_SIZE)
45
+ fail(`seo.sitemap.chunkSize must be an integer from 1 to ${MAX_CHUNK_SIZE} (got ${show(chunkSize)})`)
46
+ return { sources: [...sources], exclude: [...exclude], chunkSize }
47
+ }
@@ -0,0 +1,39 @@
1
+ import { createRouteRules } from "hamur/kit"
2
+
3
+ export interface PathsInput {
4
+ /** The paths of the page route table, copies of `@hamur/i18n` included, in table order. */
5
+ pages: string[]
6
+ /** `prerender.routes`. */
7
+ listed: string[]
8
+ rules: Readonly<NonNullable<Parameters<typeof createRouteRules>[0]>>
9
+ exclude: string[]
10
+ }
11
+
12
+ const ORIGIN = "http://localhost"
13
+ const isDynamic = (path: string) => /[:*]/.test(path)
14
+
15
+ /** An app path in the form a request has: query and hash dropped, percent-encoded, one trailing `/` run removed; `undefined` for anything else. */
16
+ export function clean(path: string): string | undefined {
17
+ if (!path.startsWith("/") || path.startsWith("//")) return undefined
18
+ try {
19
+ return new URL(path, ORIGIN).pathname.replace(/(.)\/+$/, "$1")
20
+ } catch {
21
+ return undefined
22
+ }
23
+ }
24
+
25
+ /** The page routes without params, then the paths the build knows the prerender seeds, each once, minus `noindex`, `redirect` and `exclude`. */
26
+ export function sitemapPaths({ pages, listed, rules, exclude }: PathsInput): string[] {
27
+ const matcher = createRouteRules({ ...rules })
28
+ const excluded = createRouteRules(Object.fromEntries(exclude.map((pattern) => [pattern, {}])))
29
+ const found = new Set<string>()
30
+ for (const path of [...pages.filter((page) => !isDynamic(page)), ...listed, ...matcher.prerenderPaths()]) {
31
+ const clear = clean(path)
32
+ if (clear !== undefined) found.add(clear)
33
+ }
34
+ return [...found].filter((path) => {
35
+ if (excluded.match(path).matches.length) return false
36
+ const { rule } = matcher.match(path)
37
+ return rule.noindex !== true && rule.redirect === undefined
38
+ })
39
+ }
@@ -0,0 +1,71 @@
1
+ import { absoluteUrl, escapeXml, resolveUrl } from "hamur/server/internal"
2
+
3
+ export { absoluteUrl, escapeXml, resolveUrl }
4
+
5
+ const NAMESPACE = "http://www.sitemaps.org/schemas/sitemap/0.9"
6
+ const IMAGE_NAMESPACE = "http://www.google.com/schemas/sitemap-image/1.1"
7
+ const VIDEO_NAMESPACE = "http://www.google.com/schemas/sitemap-video/1.1"
8
+ const XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"
9
+
10
+ export interface SitemapUrl {
11
+ loc: string
12
+ lastmod?: string
13
+ changefreq?: string
14
+ priority?: number
15
+ images?: string[]
16
+ videos?: Array<{
17
+ thumbnail_loc: string
18
+ title: string
19
+ description: string
20
+ content_loc?: string
21
+ player_loc?: string
22
+ duration?: number
23
+ }>
24
+ alternates?: Array<{ hreflang: string; href: string }>
25
+ }
26
+
27
+ const element = (name: string, value: string | number): string => `<${name}>${escapeXml(String(value))}</${name}>`
28
+
29
+ function videoXml(video: NonNullable<SitemapUrl["videos"]>[number]): string {
30
+ const fields: Array<[string, string | number | undefined]> = [
31
+ ["thumbnail_loc", video.thumbnail_loc],
32
+ ["title", video.title],
33
+ ["description", video.description],
34
+ ["content_loc", video.content_loc],
35
+ ["player_loc", video.player_loc],
36
+ ["duration", video.duration],
37
+ ]
38
+ return `<video:video>${fields.flatMap(([name, value]) => (value === undefined ? [] : [element(`video:${name}`, value)])).join("")}</video:video>`
39
+ }
40
+
41
+ function urlXml(url: SitemapUrl): string {
42
+ const fields = [
43
+ element("loc", url.loc),
44
+ ...(url.lastmod === undefined ? [] : [element("lastmod", url.lastmod)]),
45
+ ...(url.changefreq === undefined ? [] : [element("changefreq", url.changefreq)]),
46
+ ...(url.priority === undefined ? [] : [element("priority", url.priority)]),
47
+ ...(url.images ?? []).map((loc) => `<image:image>${element("image:loc", loc)}</image:image>`),
48
+ ...(url.videos ?? []).map(videoXml),
49
+ ...(url.alternates ?? []).map(
50
+ ({ hreflang, href }) =>
51
+ `<xhtml:link rel="alternate" hreflang="${escapeXml(hreflang)}" href="${escapeXml(href)}"/>`,
52
+ ),
53
+ ]
54
+ return `<url>${fields.join("")}</url>`
55
+ }
56
+
57
+ const DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>\n'
58
+
59
+ export function urlsetXml(urls: SitemapUrl[]): string {
60
+ const namespaces = [
61
+ `xmlns="${NAMESPACE}"`,
62
+ ...(urls.some((url) => url.images?.length) ? [`xmlns:image="${IMAGE_NAMESPACE}"`] : []),
63
+ ...(urls.some((url) => url.videos?.length) ? [`xmlns:video="${VIDEO_NAMESPACE}"`] : []),
64
+ ...(urls.some((url) => url.alternates?.length) ? [`xmlns:xhtml="${XHTML_NAMESPACE}"`] : []),
65
+ ]
66
+ return `${DECLARATION}<urlset ${namespaces.join(" ")}>${urls.map(urlXml).join("")}</urlset>\n`
67
+ }
68
+
69
+ export function indexXml(locs: string[]): string {
70
+ return `${DECLARATION}<sitemapindex xmlns="${NAMESPACE}">${locs.map((loc) => `<sitemap>${element("loc", loc)}</sitemap>`).join("")}</sitemapindex>\n`
71
+ }