@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,381 @@
1
+ import { decode, tokenize } from "../links/scan.ts"
2
+
3
+ export interface MarkdownOptions {
4
+ /** The absolute URL of the page, which relative `href` and `src` values resolve against. */
5
+ base: string
6
+ /** The id of the app root element, read when the page has no `<main>`. */
7
+ rootId?: string
8
+ }
9
+
10
+ export interface PageInfo {
11
+ title?: string
12
+ description?: string
13
+ noindex: boolean
14
+ }
15
+
16
+ interface Element {
17
+ name: string
18
+ attrs: Map<string, string>
19
+ children: Node[]
20
+ }
21
+
22
+ type Node = string | Element
23
+
24
+ const VOID = new Set([
25
+ "area",
26
+ "base",
27
+ "br",
28
+ "col",
29
+ "embed",
30
+ "hr",
31
+ "img",
32
+ "input",
33
+ "link",
34
+ "meta",
35
+ "param",
36
+ "source",
37
+ "track",
38
+ "wbr",
39
+ ])
40
+ const DROPPED = new Set(["script", "style", "nav", "noscript", "template", "svg", "iframe", "form", "button"])
41
+ const HEADINGS = new Set(["h1", "h2", "h3", "h4", "h5", "h6"])
42
+ const PARAGRAPH_ENDS = new Set([
43
+ "address",
44
+ "article",
45
+ "aside",
46
+ "blockquote",
47
+ "div",
48
+ "dl",
49
+ "fieldset",
50
+ "footer",
51
+ "form",
52
+ "header",
53
+ "hr",
54
+ "main",
55
+ "nav",
56
+ "ol",
57
+ "p",
58
+ "pre",
59
+ "section",
60
+ "table",
61
+ "ul",
62
+ ...HEADINGS,
63
+ ])
64
+ const BLOCKS = new Set([
65
+ ...PARAGRAPH_ENDS,
66
+ "body",
67
+ "details",
68
+ "dd",
69
+ "dt",
70
+ "figcaption",
71
+ "figure",
72
+ "hgroup",
73
+ "html",
74
+ "li",
75
+ "summary",
76
+ "tbody",
77
+ "td",
78
+ "tfoot",
79
+ "th",
80
+ "thead",
81
+ "tr",
82
+ ])
83
+ const IMPLICIT: Record<string, ReadonlySet<string>> = {
84
+ li: new Set(["li"]),
85
+ tr: new Set(["td", "th", "tr"]),
86
+ td: new Set(["td", "th"]),
87
+ th: new Set(["td", "th"]),
88
+ dt: new Set(["dt", "dd"]),
89
+ dd: new Set(["dt", "dd"]),
90
+ }
91
+ const P_ONLY: ReadonlySet<string> = new Set(["p"])
92
+
93
+ function parse(html: string): Element {
94
+ const root: Element = { name: "#root", attrs: new Map(), children: [] }
95
+ const stack: Element[] = [root]
96
+ const top = () => stack[stack.length - 1]!
97
+ for (const token of tokenize(html)) {
98
+ if ("text" in token) {
99
+ top().children.push(token.text)
100
+ } else if ("open" in token) {
101
+ const closes = IMPLICIT[token.open] ?? (PARAGRAPH_ENDS.has(token.open) ? P_ONLY : undefined)
102
+ while (closes && stack.length > 1 && closes.has(top().name)) stack.pop()
103
+ const element: Element = { name: token.open, attrs: token.attrs, children: [] }
104
+ top().children.push(element)
105
+ if (!VOID.has(token.open) && !token.selfClosing) stack.push(element)
106
+ } else {
107
+ const at = stack.findLastIndex((element, index) => index > 0 && element.name === token.close)
108
+ if (at !== -1) stack.length = at
109
+ }
110
+ }
111
+ return root
112
+ }
113
+
114
+ function find(
115
+ node: Node,
116
+ test: (element: Element) => boolean,
117
+ skip?: (element: Element) => boolean,
118
+ ): Element | undefined {
119
+ if (typeof node === "string") return undefined
120
+ if (node.name !== "#root" && test(node)) return node
121
+ if (skip?.(node)) return undefined
122
+ for (const child of node.children) {
123
+ const found = find(child, test, skip)
124
+ if (found) return found
125
+ }
126
+ return undefined
127
+ }
128
+
129
+ const plain = (nodes: readonly Node[]): string =>
130
+ nodes
131
+ .map((node) => (typeof node === "string" ? decode(node) : DROPPED.has(node.name) ? "" : plain(node.children)))
132
+ .join("")
133
+
134
+ const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim()
135
+
136
+ /** The title, the description and whether the robots meta holds `noindex`, read from a rendered page. */
137
+ export function pageInfo(html: string): PageInfo {
138
+ const tree = parse(html)
139
+ const title = find(
140
+ tree,
141
+ (element) => element.name === "title",
142
+ (element) => element.name === "svg",
143
+ )
144
+ const metas: Element[] = []
145
+ const walk = (node: Node) => {
146
+ if (typeof node === "string") return
147
+ if (node.name === "meta") metas.push(node)
148
+ node.children.forEach(walk)
149
+ }
150
+ walk(tree)
151
+ const meta = (name: string) =>
152
+ metas.find((element) => element.attrs.get("name")?.toLowerCase() === name)?.attrs.get("content")
153
+ const titleText = title ? oneLine(plain(title.children)) : ""
154
+ const description = oneLine(meta("description") ?? "")
155
+ return {
156
+ ...(titleText ? { title: titleText } : {}),
157
+ ...(description ? { description } : {}),
158
+ noindex: /(^|[\s,])(noindex|none)([\s,]|$)/i.test(meta("robots") ?? ""),
159
+ }
160
+ }
161
+
162
+ class Run {
163
+ text = ""
164
+
165
+ constructor(private readonly trimStart = true) {}
166
+
167
+ add(piece: string): void {
168
+ if (piece === "") return
169
+ const spaced = this.text === "" ? this.trimStart : /[ \n]$/.test(this.text)
170
+ this.text += spaced && piece.startsWith(" ") ? piece.slice(1) : piece
171
+ }
172
+ }
173
+
174
+ const fence = (text: string, char: string, least: number): string =>
175
+ char.repeat(
176
+ Math.max(least, Math.max(0, ...(text.match(new RegExp(`${char}+`, "g")) ?? []).map((run) => run.length)) + 1),
177
+ )
178
+
179
+ const indent = (text: string, by: string): string =>
180
+ text
181
+ .split("\n")
182
+ .map((line, index) => (index === 0 || line === "" ? line : by + line))
183
+ .join("\n")
184
+
185
+ function rawText(nodes: readonly Node[]): string {
186
+ return nodes
187
+ .map((node) =>
188
+ typeof node === "string"
189
+ ? decode(node)
190
+ : node.name === "br"
191
+ ? "\n"
192
+ : DROPPED.has(node.name)
193
+ ? ""
194
+ : rawText(node.children),
195
+ )
196
+ .join("")
197
+ }
198
+
199
+ class Converter {
200
+ constructor(private readonly base: string) {}
201
+
202
+ private url(value: string): string {
203
+ try {
204
+ return new URL(value.trim(), this.base).href
205
+ } catch {
206
+ return value.trim()
207
+ }
208
+ }
209
+
210
+ inline(nodes: readonly Node[], trimStart = true): string {
211
+ const run = new Run(trimStart)
212
+ for (const node of nodes) this.addInline(run, node)
213
+ return run.text
214
+ }
215
+
216
+ private addInline(run: Run, node: Node): void {
217
+ if (typeof node === "string") {
218
+ run.add(decode(node).replace(/\s+/g, " "))
219
+ return
220
+ }
221
+ if (DROPPED.has(node.name)) return
222
+ switch (node.name) {
223
+ case "br":
224
+ run.text = run.text.replace(/ +$/, "")
225
+ run.text += " \n"
226
+ return
227
+ case "img": {
228
+ const src = node.attrs.get("src")?.trim()
229
+ if (src) run.add(`![${oneLine(node.attrs.get("alt") ?? "")}](${this.url(src)})`)
230
+ return
231
+ }
232
+ case "strong":
233
+ case "b":
234
+ run.add(this.emphasis(node, "**"))
235
+ return
236
+ case "em":
237
+ case "i":
238
+ run.add(this.emphasis(node, "*"))
239
+ return
240
+ case "code": {
241
+ const code = oneLine(rawText(node.children))
242
+ if (code === "") return
243
+ const ticks = fence(code, "`", 1)
244
+ run.add(code.startsWith("`") || code.endsWith("`") ? `${ticks} ${code} ${ticks}` : `${ticks}${code}${ticks}`)
245
+ return
246
+ }
247
+ case "a": {
248
+ const text = oneLine(this.inline(node.children))
249
+ const href = node.attrs.get("href")?.trim()
250
+ if (text === "") return
251
+ run.add(href && !/^javascript:/i.test(href) ? `[${text}](${this.url(href)})` : text)
252
+ return
253
+ }
254
+ }
255
+ if (BLOCKS.has(node.name)) {
256
+ run.add(" ")
257
+ for (const child of node.children) this.addInline(run, child)
258
+ run.add(" ")
259
+ return
260
+ }
261
+ for (const child of node.children) this.addInline(run, child)
262
+ }
263
+
264
+ private emphasis(node: Element, mark: string): string {
265
+ const text = this.inline(node.children, false)
266
+ const core = text.trim()
267
+ if (core === "") return text
268
+ return `${text.slice(0, text.length - text.trimStart().length)}${mark}${core}${mark}${text.slice(text.trimEnd().length)}`
269
+ }
270
+
271
+ flow(nodes: readonly Node[]): string[] {
272
+ const chunks: string[] = []
273
+ let run = new Run()
274
+ const flush = () => {
275
+ const text = run.text.trim().replace(/\n{3,}/g, "\n\n")
276
+ if (text !== "") chunks.push(text)
277
+ run = new Run()
278
+ }
279
+ for (const node of nodes) {
280
+ if (typeof node !== "string" && BLOCKS.has(node.name) && !DROPPED.has(node.name)) {
281
+ flush()
282
+ chunks.push(...this.block(node))
283
+ } else {
284
+ this.addInline(run, node)
285
+ }
286
+ }
287
+ flush()
288
+ return chunks
289
+ }
290
+
291
+ private block(node: Element): string[] {
292
+ const name = node.name
293
+ if (HEADINGS.has(name)) {
294
+ const text = oneLine(this.inline(node.children))
295
+ return text === "" ? [] : [`${"#".repeat(Number(name.slice(1)))} ${text}`]
296
+ }
297
+ switch (name) {
298
+ case "hr":
299
+ return ["---"]
300
+ case "pre":
301
+ return [this.pre(node)]
302
+ case "blockquote": {
303
+ const body = this.flow(node.children).join("\n\n")
304
+ return body === ""
305
+ ? []
306
+ : [
307
+ body
308
+ .split("\n")
309
+ .map((line) => (line === "" ? ">" : `> ${line}`))
310
+ .join("\n"),
311
+ ]
312
+ }
313
+ case "ul":
314
+ case "ol":
315
+ return this.list(node)
316
+ case "table":
317
+ return this.table(node)
318
+ }
319
+ return this.flow(node.children)
320
+ }
321
+
322
+ private pre(node: Element): string {
323
+ const code = find(node, (element) => element.name === "code")
324
+ const language = /(?:^|\s)language-(\S+)/.exec(code?.attrs.get("class") ?? "")?.[1] ?? ""
325
+ const text = rawText(node.children).replace(/^\n/, "").replace(/\s+$/, "")
326
+ const ticks = fence(text, "`", 3)
327
+ return `${ticks}${language}\n${text}\n${ticks}`
328
+ }
329
+
330
+ private list(node: Element): string[] {
331
+ const ordered = node.name === "ol"
332
+ const start = Number.parseInt(node.attrs.get("start") ?? "1", 10)
333
+ let number = Number.isNaN(start) ? 1 : start
334
+ const items: string[] = []
335
+ for (const child of node.children) {
336
+ if (typeof child === "string" || child.name !== "li") continue
337
+ const body = this.flow(child.children).join("\n")
338
+ const marker = ordered ? `${number++}.` : "-"
339
+ items.push(`${marker} ${indent(body, " ".repeat(marker.length + 1))}`.trimEnd())
340
+ }
341
+ return items.length ? [items.join("\n")] : []
342
+ }
343
+
344
+ private table(node: Element): string[] {
345
+ const rows: string[][] = []
346
+ const walk = (parent: Element) => {
347
+ for (const child of parent.children) {
348
+ if (typeof child === "string") continue
349
+ if (child.name === "tr") {
350
+ rows.push(
351
+ child.children.flatMap((cell) =>
352
+ typeof cell !== "string" && (cell.name === "td" || cell.name === "th")
353
+ ? [oneLine(this.inline(cell.children)).replaceAll("|", "\\|")]
354
+ : [],
355
+ ),
356
+ )
357
+ } else if (child.name === "thead" || child.name === "tbody" || child.name === "tfoot") {
358
+ walk(child)
359
+ }
360
+ }
361
+ }
362
+ walk(node)
363
+ const width = Math.max(0, ...rows.map((row) => row.length))
364
+ if (width === 0) return []
365
+ const line = (row: string[]) => `| ${Array.from({ length: width }, (_, index) => row[index] ?? "").join(" | ")} |`
366
+ const [header, ...body] = rows
367
+ return [[line(header!), line(Array.from({ length: width }, () => "---")), ...body.map(line)].join("\n")]
368
+ }
369
+ }
370
+
371
+ /** The Markdown of a page's `<main>`, else of the app root element, else of its `<body>`. */
372
+ export function htmlToMarkdown(html: string, { base, rootId }: MarkdownOptions): string {
373
+ const tree = parse(html)
374
+ const root =
375
+ find(tree, (element) => element.name === "main") ??
376
+ (rootId === undefined ? undefined : find(tree, (element) => element.attrs.get("id") === rootId)) ??
377
+ find(tree, (element) => element.name === "body") ??
378
+ tree
379
+ const text = new Converter(base).flow(root.children).join("\n\n").trim()
380
+ return text === "" ? "" : `${text}\n`
381
+ }
@@ -0,0 +1,22 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import schema from "#hamur/seo/schema-org"
3
+ import { definePlugin } from "hamur/app"
4
+ import { createSchemaStore, setSchemaStore, type SchemaPage } from "./schema-store.ts"
5
+
6
+ const initialPage = (event: { url: URL } | undefined): SchemaPage => {
7
+ const url = event?.url ?? (typeof location === "undefined" ? undefined : new URL(location.href))
8
+ return { pathname: url?.pathname ?? "/", search: url?.search ?? "" }
9
+ }
10
+
11
+ export default definePlugin((app) => {
12
+ const store = createSchemaStore(app, schema, initialPage(app.event))
13
+ setSchemaStore(app, store)
14
+ store.sync()
15
+ if (typeof document === "undefined") return
16
+ const prefix = schema.baseURL.replace(/\/+$/, "")
17
+ app.hooks.hook("page:start", (route) => {
18
+ const url = new URL(route.fullPath, "http://localhost")
19
+ store.setPage({ pathname: `${prefix}${url.pathname}`, search: url.search })
20
+ })
21
+ app.hooks.hook("page:finish", () => store.sync())
22
+ })
@@ -0,0 +1,144 @@
1
+ import { siteConfigOf, canonicalURL } from "hamur/adapter"
2
+ import type { AppContext, HeadEntry } from "hamur/app"
3
+ import { buildGraph } from "../schema/graph.ts"
4
+ import type { IdentityNode, SchemaNode } from "../schema.ts"
5
+
6
+ export interface SchemaOrgRuntime {
7
+ enabled: boolean
8
+ identity: IdentityNode | null
9
+ baseURL: string
10
+ trailingSlash: "ignore" | "redirect" | "always" | "strict"
11
+ /** Route name → the string-literal `meta.title` of its page, read at build. */
12
+ titles: Record<string, string>
13
+ }
14
+
15
+ export interface SchemaPage {
16
+ pathname: string
17
+ search: string
18
+ }
19
+
20
+ export interface SchemaStore {
21
+ /** Replaces the nodes of the call `key`; the first `set` of a key fixes its place in the graph. */
22
+ set(key: unknown, nodes: SchemaNode[]): void
23
+ remove(key: unknown): void
24
+ clear(): void
25
+ setPage(page: SchemaPage): void
26
+ readonly titles: Record<string, string>
27
+ /** `app.baseURL` without its trailing slash. */
28
+ readonly base: string
29
+ /** The canonical URL of an app path below `app.baseURL`, `undefined` without `site.url`. */
30
+ urlOf(path: string): string | undefined
31
+ /** Rebuilds the graph and patches the plugin's one head entry. */
32
+ sync(): void
33
+ }
34
+
35
+ const dev = (): boolean => (import.meta as { dev?: boolean }).dev === true
36
+ const browser = typeof document !== "undefined"
37
+ const warned = new Set<string>()
38
+
39
+ function warnOnce(message: string): void {
40
+ if (!dev() || warned.has(message)) return
41
+ warned.add(message)
42
+ console.warn(message)
43
+ }
44
+
45
+ export function createSchemaStore(app: AppContext, options: SchemaOrgRuntime, initial: SchemaPage): SchemaStore {
46
+ const calls = new Map<unknown, { text: string; nodes: SchemaNode[] }>()
47
+ let page = initial
48
+ let entry: HeadEntry | undefined
49
+ let applying = false
50
+
51
+ const graph = () => {
52
+ const site = siteConfigOf(app)
53
+ if (site.url === undefined) {
54
+ warnOnce("[seo] schema.org needs site.url for @id URLs; no graph is written")
55
+ return undefined
56
+ }
57
+ if (app.error?.get()) return undefined
58
+ const pageURL = canonicalURL(site, { baseURL: options.baseURL, trailingSlash: options.trailingSlash, ...page })!
59
+ return buildGraph({
60
+ siteURL: site.url,
61
+ baseURL: options.baseURL,
62
+ pageURL,
63
+ ...(site.name === undefined ? {} : { name: site.name }),
64
+ ...(site.description === undefined ? {} : { description: site.description }),
65
+ ...(options.identity ? { identity: options.identity } : {}),
66
+ nodes: [...calls.values()].flatMap((call) => call.nodes),
67
+ })
68
+ }
69
+
70
+ const store: SchemaStore = {
71
+ titles: options.titles,
72
+ base: options.baseURL.replace(/\/+$/, ""),
73
+ urlOf: (path) =>
74
+ canonicalURL(siteConfigOf(app), {
75
+ baseURL: options.baseURL,
76
+ trailingSlash: options.trailingSlash,
77
+ pathname: `${options.baseURL.replace(/\/+$/, "")}${path}`,
78
+ search: "",
79
+ }),
80
+ set(key, nodes) {
81
+ if (!options.enabled) {
82
+ if (nodes.length === 0) return
83
+ warnOnce("[seo] useSchemaOrg is called but seo.schemaOrg is false; no schema.org graph is written")
84
+ return
85
+ }
86
+ const text = JSON.stringify(nodes)
87
+ if (calls.get(key)?.text === text) return
88
+ calls.set(key, { text, nodes })
89
+ store.sync()
90
+ },
91
+ remove(key) {
92
+ if (calls.delete(key)) store.sync()
93
+ },
94
+ clear() {
95
+ if (calls.size) {
96
+ calls.clear()
97
+ store.sync()
98
+ }
99
+ },
100
+ setPage(next) {
101
+ page = next
102
+ store.sync()
103
+ },
104
+ sync() {
105
+ const next = options.enabled ? graph() : undefined
106
+ if (!next) {
107
+ entry?.dispose()
108
+ entry = undefined
109
+ } else if (entry) entry.patch({ jsonLd: next })
110
+ else entry = app.head.push({ jsonLd: next }, { layer: "plugin" })
111
+ if (browser && !applying) {
112
+ applying = true
113
+ queueMicrotask(() => {
114
+ applying = false
115
+ app.head.apply()
116
+ })
117
+ }
118
+ },
119
+ }
120
+ return store
121
+ }
122
+
123
+ const stores = new WeakMap<object, SchemaStore>()
124
+
125
+ export function setSchemaStore(app: AppContext, store: SchemaStore): void {
126
+ stores.set(app, store)
127
+ }
128
+
129
+ export function schemaStoreOf(app: AppContext): SchemaStore {
130
+ const store = stores.get(app)
131
+ if (!store) throw new Error('useSchemaOrg() needs the "@hamur/seo" module in modules')
132
+ return store
133
+ }
134
+
135
+ export const nodeList = (nodes: SchemaNode | SchemaNode[]): SchemaNode[] => (Array.isArray(nodes) ? nodes : [nodes])
136
+
137
+ /** The app of a `useSchemaOrg` call, with the message of `useHead` when there is none. */
138
+ export function appOfCall(useApp: () => AppContext): AppContext {
139
+ try {
140
+ return useApp()
141
+ } catch {
142
+ throw new Error("useSchemaOrg() must be called inside a Hamur app")
143
+ }
144
+ }
@@ -0,0 +1,125 @@
1
+ import type { JsonLdGraph } from "hamur/app"
2
+ import type { SchemaNode } from "../schema.ts"
3
+
4
+ export interface GraphInput {
5
+ siteURL: string
6
+ baseURL: string
7
+ pageURL: string
8
+ name?: string
9
+ description?: string
10
+ identity?: SchemaNode
11
+ nodes: SchemaNode[]
12
+ }
13
+
14
+ type Node = Record<string, unknown>
15
+
16
+ const URL_KEYS = new Set(["url", "image", "logo", "item", "contentUrl", "thumbnailUrl", "embedUrl", "sameAs"])
17
+ const WEB_PAGES = new Set([
18
+ "WebPage",
19
+ "AboutPage",
20
+ "CheckoutPage",
21
+ "CollectionPage",
22
+ "ContactPage",
23
+ "FAQPage",
24
+ "ItemPage",
25
+ "MedicalWebPage",
26
+ "ProfilePage",
27
+ "QAPage",
28
+ "RealEstateListing",
29
+ "SearchResultsPage",
30
+ ])
31
+ const ARTICLES = new Set(["Article", "BlogPosting", "NewsArticle", "TechArticle", "Report", "ScholarlyArticle"])
32
+
33
+ const isPlain = (value: unknown): value is Node => {
34
+ if (typeof value !== "object" || value === null || value instanceof Date) return false
35
+ const proto = Object.getPrototypeOf(value)
36
+ return proto === Object.prototype || proto === null
37
+ }
38
+
39
+ const typesOf = (node: Node): string[] =>
40
+ [node["@type"]].flat().filter((type): type is string => typeof type === "string")
41
+
42
+ /** URL strings made absolute, a `Date` an ISO string, an `undefined` value dropped. */
43
+ function clean(value: unknown, key: string | undefined, root: URL, path: object[]): unknown {
44
+ if (value instanceof Date) return value.toISOString()
45
+ if (typeof value === "string") {
46
+ if (key === undefined || !URL_KEYS.has(key)) return value
47
+ try {
48
+ return new URL(value, root).href
49
+ } catch {
50
+ return value
51
+ }
52
+ }
53
+ const array = Array.isArray(value)
54
+ if (!array && !isPlain(value)) return value
55
+ if (path.includes(value as object)) throw new TypeError("Converting circular structure to JSON")
56
+ path.push(value as object)
57
+ try {
58
+ if (array) return (value as unknown[]).map((item) => clean(item, key, root, path))
59
+ const out: Node = {}
60
+ for (const [name, item] of Object.entries(value as Node))
61
+ if (item !== undefined) out[name] = clean(item, name, root, path)
62
+ return out
63
+ } finally {
64
+ path.pop()
65
+ }
66
+ }
67
+
68
+ /** The page's graph: the default nodes, then each node of `nodes` in order, merged by `@id`. */
69
+ export function buildGraph(input: GraphInput): JsonLdGraph {
70
+ const root = new URL(input.baseURL.endsWith("/") ? input.baseURL : `${input.baseURL}/`, input.siteURL)
71
+ const websiteId = `${root.href}#website`
72
+ const identityId = `${root.href}#identity`
73
+ const webpageId = `${input.pageURL}#webpage`
74
+ const nodes = new Map<string, Node>()
75
+ const counts = new Map<string, number>()
76
+
77
+ const register = (node: Node, id: string): void => {
78
+ let target = nodes.get(id)
79
+ if (!target) nodes.set(id, (target = { "@id": id }))
80
+ for (const [name, value] of Object.entries(node)) if (name !== "@id") target[name] = lift(value, id, name)
81
+ }
82
+ const liftOne = (value: unknown, fallback: string): unknown => {
83
+ if (!isPlain(value) || !("@type" in value)) return value
84
+ const id = typeof value["@id"] === "string" ? value["@id"] : fallback
85
+ register(value, id)
86
+ return { "@id": id }
87
+ }
88
+ const lift = (value: unknown, parent: string, name: string): unknown =>
89
+ Array.isArray(value)
90
+ ? value.map((item, index) => liftOne(item, `${parent}/${name}/${index}`))
91
+ : liftOne(value, `${parent}/${name}`)
92
+ const idOf = (node: Node): string => {
93
+ if (typeof node["@id"] === "string") return node["@id"]
94
+ const type = typesOf(node)[0] ?? "Thing"
95
+ if (type === "WebSite") return websiteId
96
+ if (WEB_PAGES.has(type)) return webpageId
97
+ const base = `${input.pageURL}#${type.toLowerCase()}`
98
+ const count = (counts.get(base) ?? 0) + 1
99
+ counts.set(base, count)
100
+ return count === 1 ? base : `${base}-${count}`
101
+ }
102
+ const add = (node: unknown): void => {
103
+ const cleaned = clean(node, undefined, root, []) as Node
104
+ register(cleaned, idOf(cleaned))
105
+ }
106
+
107
+ add({ "@type": "WebSite", "@id": websiteId, url: root.href, name: input.name, description: input.description })
108
+ if (input.identity) add({ ...input.identity, "@id": identityId })
109
+ add({ "@type": "WebPage", "@id": webpageId, url: input.pageURL })
110
+ for (const node of input.nodes) add(node)
111
+
112
+ const reference = (id: string) => ({ "@id": id })
113
+ const breadcrumb = [...nodes].find(([, node]) => typesOf(node).includes("BreadcrumbList"))?.[0]
114
+ for (const node of nodes.values()) {
115
+ const types = typesOf(node)
116
+ if (types.some((type) => WEB_PAGES.has(type))) {
117
+ node.isPartOf ??= reference(websiteId)
118
+ if (breadcrumb && node["@id"] === webpageId) node.breadcrumb ??= reference(breadcrumb)
119
+ }
120
+ if (input.identity && types.some((type) => type === "WebSite" || ARTICLES.has(type)))
121
+ node.publisher ??= reference(identityId)
122
+ if (types.some((type) => ARTICLES.has(type))) node.mainEntityOfPage ??= reference(webpageId)
123
+ }
124
+ return { "@context": "https://schema.org", "@graph": [...nodes.values()] as JsonLdGraph["@graph"] }
125
+ }