@prunellejs/seo 0.0.0-stage → 0.7.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt ADDED
@@ -0,0 +1,57 @@
1
+ # @prunellejs/seo Reference
2
+
3
+ > SEO `<head>` tags, `titleTemplate`, localized descriptions, canonical URLs, JSON-LD, `sitemap.xml` (i18n-aware), redirects, web manifest, favicons, and self-hosted fonts.
4
+
5
+ ## Imports
6
+
7
+ - `@prunellejs/seo`: `seo`, `jsonLd`; types `SeoPluginOptions`, `FontEntry`, `ManifestOptions`, `RedirectTarget`.
8
+
9
+ ## Plugin Setup (`seo(options?)`)
10
+
11
+ - `site`: public origin (`https://example.com`, inherits `PrunelleConfig.site`). Required for canonical links (the path, plus `?page=N` for a list page past the first; any other query is left out), absolute `og:image`, and `sitemap.xml`; a production start refuses without it.
12
+ - `name`: site name (`og:site_name` and fallback `<title>`).
13
+ - `titleTemplate`: e.g. `'%s | My App'` (skips wrapping if `<title>` already contains `name`).
14
+ - `description`: `string` or `Record<locale, string>` (localized fallback when a page doesn't emit `<meta name="description">`; reads `ctx.locals.locale` from `@prunellejs/i18n`).
15
+ - `image`, `imageAlt`: default `og:image`, `twitter:card` (`summary_large_image`), and `og:image:alt`.
16
+ - `locale`: default `og:locale`.
17
+ - `jsonLd`: array of Schema.org objects injected globally (`@context: 'https://schema.org'` auto-added).
18
+ - `sitemap`: `boolean` (default `true`, emitted in `afterPrerender` as `/sitemap.xml` with `xhtml:link` alternates when `@prunellejs/i18n` is active; past 50,000 URLs it becomes a sitemap index over `sitemap-1.xml`, `sitemap-2.xml`, ...). `sitemapExclude`: `string[]`. `extraUrls`: `() => string[]`.
19
+ - `redirects`: `Record<fromPath, string | { to: string, status?: 301 | 302 | 307 | 308 }>` (mounted as `GET` routes, default `301`; a `--static` export writes them to `dist/_redirects` instead, and `prunelle build --static` adds the exact-path ones to its Caddy and nginx snippets).
20
+ - `favicon`: `string | string[]` (relative path or package specifier; emits `favicon.{svg,png,ico}` and `<link rel="icon">`; a path that resolves to no file fails the build). `image` is prefixed with `site` unless it starts with `http://`, `https://` or `//`.
21
+ - `manifest`: `{ name?, shortName?, description?, themeColor?, backgroundColor?, display?, startUrl? }` (emits `/manifest.webmanifest`).
22
+ - `fonts`: `Array<{ family, src, weight?, style?, display?, preload? }>` (resolves local paths or `@fontsource/*` specifiers, emits content-hashed assets + `@font-face` stylesheet + `<link rel="preload">`).
23
+
24
+ ## Page-Specific JSON-LD
25
+
26
+ - `jsonLd(schema)` returns a branded `Html` value for `<Head>`: `<Head>{jsonLd({ '@type': 'Article', headline: title })}</Head>`.
27
+
28
+ ## Validation (`prunelle check`)
29
+
30
+ - Warns with `[seo/missing-site]` when neither `prunelle.config.ts` `site` nor `seo({ site })` is set.
31
+ - Warns with `[seo/missing-title]` and `[seo/missing-description]` on page routes without `<title>` or `<meta name="description">` (respecting ancestor `_layout.tsx` and `seo({ description })`).
32
+ - Warns with `[seo/long-title]` (> 60 chars, including `titleTemplate`) and `[seo/long-description]` (> 160 chars) on static routes, `seo()` defaults, and prerendered HTML.
33
+ - Warns with `[seo/duplicate-title]` and `[seo/duplicate-description]` when two static routes or prerendered pages share the same title or description.
34
+ - Warns with `[seo/noindex-in-sitemap]` when a route or prerendered page sets `noindex` while still included in `sitemap.xml` (not in `sitemapExclude` and `sitemap !== false`).
35
+ - Warns with `[seo/missing-image]` when `site` is configured and a page has neither `seo({ image })` nor `<meta property="og:image">`, and with `[seo/missing-image-file]` when a `seo({ image })` path names no file in `publicDir`.
36
+
37
+ ## Snippet
38
+
39
+ ```ts
40
+ // prunelle.config.ts
41
+ import { defineConfig } from 'prunelle/config'
42
+ import { seo } from '@prunellejs/seo'
43
+
44
+ export default defineConfig({
45
+ site: 'https://example.com',
46
+ plugins: [
47
+ seo({
48
+ name: 'Acme',
49
+ titleTemplate: '%s | Acme',
50
+ description: 'Fast web apps with Prunelle.',
51
+ favicon: 'public/favicon.svg',
52
+ fonts: [{ family: 'Inter', src: '@fontsource/inter/files/inter-latin-400-normal.woff2', weight: 400 }],
53
+ redirects: { '/old': '/new' },
54
+ }),
55
+ ],
56
+ })
57
+ ```
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@prunellejs/seo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.2",
4
+ "description": "SEO meta, JSON-LD, sitemap, redirects, and self-hosted fonts plugin for Prunelle",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "src",
10
+ "llms.txt"
11
+ ],
12
+ "exports": {
13
+ ".": "./src/index.ts"
14
+ },
15
+ "engines": {
16
+ "bun": ">=1.4.0"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/Kayno0o/prunelle",
21
+ "directory": "packages/plugin-seo"
22
+ },
23
+ "peerDependencies": {
24
+ "prunelle": "^0.7.2"
25
+ }
26
+ }
package/src/check.ts ADDED
@@ -0,0 +1,599 @@
1
+ // Static & prerendered SEO diagnostics for `@prunellejs/seo`'s `prunelle check` hook.
2
+
3
+ import type { CheckPluginContext } from 'prunelle/config'
4
+ import type { SeoPluginOptions } from './index'
5
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
6
+ import { basename, dirname, join, relative } from 'node:path'
7
+ import { getAppContext } from 'prunelle/internal/server'
8
+
9
+ const MAX_TITLE = 60
10
+ const MAX_DESC = 160
11
+ const TS_EXT_RE = /\.(?:tsx|ts)$/
12
+ const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
13
+ const HEAD_BLOCK_RE = /<Head(?:\s(?:[^>"']|"[^"]*"|'[^']*')*)?(?<!\/)>([\s\S]*?)<\/Head>/g
14
+ const TITLE_TAG_RE = /<title(?:\s[^>]*)?>([\s\S]*?)<\/title>/g
15
+ const HTML_HEAD_RE = /<head\b[^>]*>([\s\S]*?)<\/head>/i
16
+ const HTML_TITLE_RE = /<title\b[^>]*>([\s\S]*?)<\/title>/i
17
+ const HTML_META_RE = /<meta\b[^>]*>/gi
18
+ const HTML_ATTR_RE = /([a-zA-Z_:][a-zA-Z0-9_.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g
19
+ const NOINDEX_RE = /\bnoindex\b/i
20
+ const PRERENDER_TRUE_RE = /\bexport\s+(?:const|let|var)\s+prerender\s*=\s*true\b/
21
+ const ENTITY_RE = /&(?:#(\d+)|#x([0-9a-fA-F]+)|([a-zA-Z]+));/g
22
+ const SKIP_PRERENDER_DIRS = new Set(['_pru', 'client', 'server', 'public', 'node_modules'])
23
+ const CONFIG_FILES = ['prunelle.config.ts', 'prunelle.config.js', 'prunelle.config.mjs']
24
+ const NAMED_ENTITIES: Record<string, string> = {
25
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: '\u00A0', ndash: '\u2013',
26
+ mdash: '\u2014', hellip: '\u2026', laquo: '\u00AB', raquo: '\u00BB', copy: '\u00A9', reg: '\u00AE', trade: '\u2122',
27
+ }
28
+ const TS_SCANNER = new Bun.Transpiler({ loader: 'ts' })
29
+ const TSX_SCANNER = new Bun.Transpiler({ loader: 'tsx' })
30
+
31
+ interface TextEntry { value: string | undefined, offset: number }
32
+ interface RouteHeadInfo {
33
+ titles: TextEntry[]
34
+ emptyTitleOffset?: number | undefined
35
+ descriptions: TextEntry[]
36
+ emptyDescriptionOffset?: number | undefined
37
+ hasOgImage: boolean
38
+ noindexOffset?: number | undefined
39
+ }
40
+ interface OwnedEntry { value: string | undefined, file: string, code: string, offset: number, fromLayout: boolean }
41
+ interface StaticState {
42
+ longTitleUrls: Set<string>
43
+ longDescUrls: Set<string>
44
+ noindexUrls: Set<string>
45
+ dupTitles: Set<string>
46
+ dupDescs: Set<string>
47
+ warnedLayouts: Set<string>
48
+ seenTitles: Map<string, { relFile: string, routePath: string }>
49
+ seenDescs: Map<string, { relFile: string, routePath: string }>
50
+ }
51
+ interface ParsedAttr { staticValue?: string | undefined, isDynamic: boolean }
52
+
53
+ const relPosix = (root: string, file: string): string => relative(root, file).replaceAll('\\', '/')
54
+
55
+ function normalizePath(p: string): string {
56
+ const s = p.startsWith('/') ? p : `/${p}`
57
+ return s.length > 1 ? s.replace(/\/+$/, '') || '/' : s
58
+ }
59
+
60
+ function isSkippedPath(p: string): boolean {
61
+ const n = normalizePath(p)
62
+ return n === '/api' || n.startsWith('/api/') || n === '/404' || n === '/500' || n === '/__pru_404__'
63
+ }
64
+
65
+ function fileToRoutePath(routesDir: string, file: string): string {
66
+ const rel = relPosix(routesDir, file).replace(TS_EXT_RE, '')
67
+ if (rel === 'index') return '/'
68
+ const clean = rel.endsWith('/index') ? rel.slice(0, -6) : rel
69
+ return `/${clean.replace(/\[\.\.\.([^\]]+)\]/g, '*$1').replace(/\[([^\]]+)\]/g, ':$1')}`
70
+ }
71
+
72
+ function formatWarn(relFile: string, code: string | undefined, offset: number, rule: string, detail: string, fix: string): string {
73
+ let line = 1
74
+ let col = 1
75
+ if (code !== undefined) {
76
+ for (let i = 0, end = Math.min(Math.max(0, offset), code.length); i < end; i++) {
77
+ if (code.charCodeAt(i) === 10) { line++; col = 1 }
78
+ else { col++ }
79
+ }
80
+ }
81
+ return `${relFile}:${line}:${col}: warning: [seo/${rule}] ${detail}: ${fix}.`
82
+ }
83
+
84
+ function decodeEntities(str: string): string {
85
+ if (!str.includes('&')) return str
86
+ return str.replace(ENTITY_RE, (m, dec?: string, hex?: string, named?: string) => {
87
+ const cp = dec !== undefined ? Number.parseInt(dec, 10) : hex !== undefined ? Number.parseInt(hex, 16) : -1
88
+ if (cp > 0 && cp <= 0x10FFFF) return String.fromCodePoint(cp)
89
+ return named !== undefined && Object.hasOwn(NAMED_ENTITIES, named) ? NAMED_ENTITIES[named]! : m
90
+ })
91
+ }
92
+
93
+ function skipQuoted(src: string, start: number): number {
94
+ const q = src[start]!
95
+ for (let i = start + 1; i < src.length; i++) {
96
+ if (src[i] === '\\') i++
97
+ else if (src[i] === q) return i
98
+ }
99
+ return src.length - 1
100
+ }
101
+
102
+ function stripCommentsPreserveOffsets(code: string): string {
103
+ const chars = code.split('')
104
+ let i = 0
105
+ let quote = ''
106
+ let braceDepth = 0
107
+ const tplDepths: number[] = []
108
+ while (i < chars.length) {
109
+ const ch = chars[i]!
110
+ const next = chars[i + 1]
111
+ if (quote !== '') {
112
+ if (ch === '\\') { i += 2; continue }
113
+ if (quote === '`' && ch === '$' && next === '{') { tplDepths.push(braceDepth++); quote = ''; i += 2; continue }
114
+ if (ch === quote) quote = ''
115
+ i++
116
+ continue
117
+ }
118
+ if (ch === '/' && next === '/') {
119
+ while (i < chars.length && chars[i] !== '\n' && chars[i] !== '\r') chars[i++] = ' '
120
+ continue
121
+ }
122
+ if (ch === '/' && next === '*') {
123
+ chars[i++] = ' '; chars[i++] = ' '
124
+ while (i < chars.length && !(chars[i] === '*' && chars[i + 1] === '/')) {
125
+ if (chars[i] !== '\n' && chars[i] !== '\r') chars[i] = ' '
126
+ i++
127
+ }
128
+ if (i + 1 < chars.length) { chars[i++] = ' '; chars[i++] = ' ' }
129
+ continue
130
+ }
131
+ if (ch === '\'' || ch === '"' || ch === '`') quote = ch
132
+ else if (ch === '{') braceDepth++
133
+ else if (ch === '}' && tplDepths[tplDepths.length - 1] === --braceDepth) { tplDepths.pop(); quote = '`' }
134
+ i++
135
+ }
136
+ return chars.join('')
137
+ }
138
+
139
+ function unquoteStringLiteral(expr: string): string | undefined {
140
+ const t = expr.trim()
141
+ const q = t[0]
142
+ if (t.length < 2 || t[t.length - 1] !== q) return undefined
143
+ const body = t.slice(1, -1)
144
+ if (q === '`') return /(?<!\\)\$\{|(?<!\\)`/.test(body) ? undefined : body.replace(/\\(.)/g, '$1')
145
+ if (q !== '"' && q !== '\'') return undefined
146
+ if (new RegExp(`(?<!\\\\)${q}`).test(body)) return undefined
147
+ return body.replace(/\\([nrt"'\\])/g, (_, e: string) => (e === 'n' ? '\n' : e === 't' ? '\t' : e === 'r' ? '\r' : e))
148
+ }
149
+
150
+ function readBalancedBrace(src: string, openIndex: number): number {
151
+ let depth = 1
152
+ for (let i = openIndex + 1; i < src.length; i++) {
153
+ const ch = src[i]!
154
+ if (ch === '\'' || ch === '"' || ch === '`') i = skipQuoted(src, i)
155
+ else if (ch === '{') depth++
156
+ else if (ch === '}' && --depth === 0) return i
157
+ }
158
+ return -1
159
+ }
160
+
161
+ function analyzeTitleChildren(raw: string): { kind: 'empty' } | { kind: 'static', value: string } | { kind: 'dynamic' } {
162
+ let out = ''
163
+ let i = 0
164
+ while (i < raw.length) {
165
+ const open = raw.indexOf('{', i)
166
+ if (open === -1) { out += decodeEntities(raw.slice(i)); break }
167
+ out += decodeEntities(raw.slice(i, open))
168
+ const close = readBalancedBrace(raw, open)
169
+ if (close === -1) return { kind: 'dynamic' }
170
+ const expr = raw.slice(open + 1, close).trim()
171
+ if (expr !== '' && expr !== 'null' && expr !== 'undefined' && expr !== 'false') {
172
+ const lit = unquoteStringLiteral(expr)
173
+ if (lit === undefined) return { kind: 'dynamic' }
174
+ out += lit
175
+ }
176
+ i = close + 1
177
+ }
178
+ const normalized = out.replace(/\s+/g, ' ').trim()
179
+ return normalized.length === 0 ? { kind: 'empty' } : { kind: 'static', value: normalized }
180
+ }
181
+
182
+ function scanMetaTags(headBody: string, bodyOffset: number): Array<{ attrs: string, offset: number }> {
183
+ const tags: Array<{ attrs: string, offset: number }> = []
184
+ let i = 0
185
+ while (i < headBody.length) {
186
+ const start = headBody.indexOf('<meta', i)
187
+ if (start === -1) break
188
+ const after = headBody[start + 5]
189
+ if (after !== undefined && !/[\s/>]/.test(after)) { i = start + 5; continue }
190
+ let j = start + 5
191
+ let depth = 0
192
+ while (j < headBody.length) {
193
+ const ch = headBody[j]!
194
+ if (ch === '\'' || ch === '"' || ch === '`') j = skipQuoted(headBody, j)
195
+ else if (ch === '{') depth++
196
+ else if (ch === '}' && depth > 0) depth--
197
+ else if (ch === '>' && depth === 0) break
198
+ j++
199
+ }
200
+ if (j >= headBody.length) break
201
+ tags.push({ attrs: headBody.slice(start + 5, j).replace(/\/\s*$/, ''), offset: bodyOffset + start })
202
+ i = j + 1
203
+ }
204
+ return tags
205
+ }
206
+
207
+ function parseJsxAttrs(src: string): { attrs: Map<string, ParsedAttr>, hasSpread: boolean } {
208
+ const attrs = new Map<string, ParsedAttr>()
209
+ let hasSpread = false
210
+ let i = 0
211
+ while (i < src.length) {
212
+ while (i < src.length && /\s/.test(src[i]!)) i++
213
+ if (i >= src.length) break
214
+ if (src[i] === '{') {
215
+ const close = readBalancedBrace(src, i)
216
+ if (close === -1) break
217
+ if (src.slice(i + 1, close).trim().startsWith('...')) hasSpread = true
218
+ i = close + 1
219
+ continue
220
+ }
221
+ const start = i
222
+ while (i < src.length && /[a-zA-Z0-9_:-]/.test(src[i]!)) i++
223
+ const name = src.slice(start, i).toLowerCase()
224
+ if (name === '') { i++; continue }
225
+ while (i < src.length && /\s/.test(src[i]!)) i++
226
+ if (src[i] !== '=') { attrs.set(name, { staticValue: '', isDynamic: false }); continue }
227
+ i++
228
+ while (i < src.length && /\s/.test(src[i]!)) i++
229
+ const ch = src[i]
230
+ if (ch === '"' || ch === '\'') {
231
+ const end = skipQuoted(src, i)
232
+ attrs.set(name, { staticValue: decodeEntities(src.slice(i + 1, end)), isDynamic: false })
233
+ i = end + 1
234
+ }
235
+ else if (ch === '{') {
236
+ const close = readBalancedBrace(src, i)
237
+ if (close === -1) break
238
+ const expr = src.slice(i + 1, close).trim()
239
+ const lit = unquoteStringLiteral(expr)
240
+ if (lit !== undefined) attrs.set(name, { staticValue: lit, isDynamic: false })
241
+ else if (expr === '' || expr === 'undefined' || expr === 'null' || expr === 'false') attrs.set(name, { staticValue: '', isDynamic: false })
242
+ else attrs.set(name, { isDynamic: true })
243
+ i = close + 1
244
+ }
245
+ }
246
+ return { attrs, hasSpread }
247
+ }
248
+
249
+ function extractRouteHead(stripped: string): RouteHeadInfo {
250
+ const info: RouteHeadInfo = { titles: [], descriptions: [], hasOgImage: false }
251
+ HEAD_BLOCK_RE.lastIndex = 0
252
+ for (let hm = HEAD_BLOCK_RE.exec(stripped); hm !== null; hm = HEAD_BLOCK_RE.exec(stripped)) {
253
+ const body = hm[1]!
254
+ const bodyOffset = hm.index + hm[0].indexOf('>') + 1
255
+ TITLE_TAG_RE.lastIndex = 0
256
+ for (let tm = TITLE_TAG_RE.exec(body); tm !== null; tm = TITLE_TAG_RE.exec(body)) {
257
+ const res = analyzeTitleChildren(tm[1]!)
258
+ if (res.kind === 'empty') info.emptyTitleOffset ??= bodyOffset + tm.index
259
+ else info.titles.push({ value: res.kind === 'static' ? res.value : undefined, offset: bodyOffset + tm.index })
260
+ }
261
+ for (const meta of scanMetaTags(body, bodyOffset)) {
262
+ const { attrs, hasSpread } = parseJsxAttrs(meta.attrs)
263
+ const nameVal = attrs.get('name')?.staticValue?.trim().toLowerCase()
264
+ const propVal = attrs.get('property')?.staticValue?.trim().toLowerCase()
265
+ const content = attrs.get('content')
266
+ const contentVal = content?.staticValue?.trim()
267
+ if (nameVal === 'description') {
268
+ if (content?.isDynamic || hasSpread) info.descriptions.push({ value: undefined, offset: meta.offset })
269
+ else if (contentVal) info.descriptions.push({ value: contentVal, offset: meta.offset })
270
+ else info.emptyDescriptionOffset ??= meta.offset
271
+ }
272
+ else if (nameVal === 'robots' && contentVal && NOINDEX_RE.test(contentVal)) {
273
+ info.noindexOffset ??= meta.offset
274
+ }
275
+ else if ((propVal === 'og:image' || nameVal === 'og:image') && (hasSpread || content?.isDynamic || Boolean(contentVal))) {
276
+ info.hasOgImage = true
277
+ }
278
+ }
279
+ }
280
+ return info
281
+ }
282
+
283
+ function hasTopLevelSiteInObject(stripped: string, braceStart: number): boolean {
284
+ let depth = 0
285
+ for (let i = braceStart; i < stripped.length; i++) {
286
+ const ch = stripped[i]!
287
+ if (ch === '\'' || ch === '"' || ch === '`') { i = skipQuoted(stripped, i); continue }
288
+ if (ch === '{') { depth++; continue }
289
+ if (ch === '}') { if (--depth === 0) return false; continue }
290
+ if (depth !== 1 || !stripped.startsWith('site', i)) continue
291
+ const prev = stripped[i - 1]
292
+ if (prev !== undefined && !/[\s,{]/.test(prev)) continue
293
+ const rest = stripped.slice(i + 4)
294
+ if (/^\s*[,}]/.test(rest)) return true
295
+ const m = /^\s*:\s*([^,\n}]+)/.exec(rest)
296
+ if (m !== null && !['undefined', 'null', '\'\'', '""', '``'].includes(m[1]!.trim())) return true
297
+ }
298
+ return false
299
+ }
300
+
301
+ function hasConfiguredSite(root: string, options: SeoPluginOptions, activeSite: string | undefined): boolean {
302
+ if (options.site?.trim() || activeSite?.trim() || getAppContext()?.site?.trim()) return true
303
+ for (const name of CONFIG_FILES) {
304
+ const full = join(root, name)
305
+ if (!existsSync(full)) continue
306
+ const stripped = stripCommentsPreserveOffsets(readFileSync(full, 'utf8'))
307
+ const m = /defineConfig\s*\(\s*\{|export\s+default\s*\{/.exec(stripped)
308
+ if (m !== null && hasTopLevelSiteInObject(stripped, m.index + m[0].length - 1)) return true
309
+ }
310
+ return false
311
+ }
312
+
313
+ function applyTitleTemplate(title: string, options: SeoPluginOptions): string {
314
+ return options.titleTemplate && (!options.name || !title.includes(options.name))
315
+ ? options.titleTemplate.replace('%s', () => title)
316
+ : title
317
+ }
318
+
319
+ function walkRouteFiles(dir: string): string[] {
320
+ const out: string[] = []
321
+ if (!existsSync(dir)) return out
322
+ const stack = [dir]
323
+ while (stack.length > 0) {
324
+ const cur = stack.pop()!
325
+ for (const e of readdirSync(cur, { withFileTypes: true })) {
326
+ if (e.isDirectory() && !e.name.startsWith('_') && !e.name.startsWith('.') && e.name !== 'node_modules' && e.name !== 'dist')
327
+ stack.push(join(cur, e.name))
328
+ else if (e.isFile() && TS_EXT_RE.test(e.name) && !e.name.endsWith('.d.ts') && !TEST_FILE_RE.test(e.name))
329
+ out.push(join(cur, e.name))
330
+ }
331
+ }
332
+ return out.sort()
333
+ }
334
+
335
+ function scanExports(file: string, code: string): string[] | undefined {
336
+ try { return (file.endsWith('.tsx') ? TSX_SCANNER : TS_SCANNER).scan(code).exports }
337
+ catch { return undefined }
338
+ }
339
+
340
+ function ancestorLayouts(routesDir: string, routeFile: string): string[] {
341
+ const result: string[] = []
342
+ const relDir = relative(routesDir, dirname(routeFile))
343
+ const parts = relDir === '' ? [] : relDir.split(/[/\\]/)
344
+ let cur = routesDir
345
+ for (let i = 0; i <= parts.length; i++) {
346
+ if (i > 0) cur = join(cur, parts[i - 1]!)
347
+ const candidate = join(cur, '_layout.tsx')
348
+ if (existsSync(candidate)) result.push(candidate)
349
+ }
350
+ return result
351
+ }
352
+
353
+ function checkConfigOptions(options: SeoPluginOptions, siteConfigured: boolean, warn: (m: string) => void): void {
354
+ if (!siteConfigured)
355
+ warn(formatWarn('prunelle.config.ts', undefined, 0, 'missing-site', 'no `site` is configured, so canonical links, absolute `og:image` URLs, and `sitemap.xml` are disabled', 'set `site` in `prunelle.config.ts` or pass `seo({ site })`'))
356
+ if (options.name !== undefined && options.name.trim().length > MAX_TITLE)
357
+ warn(formatWarn('prunelle.config.ts', undefined, 0, 'long-title', `default seo({ name }) is ${options.name.trim().length} characters (recommended max ${MAX_TITLE})`, `shorten \`name\` to ${MAX_TITLE} characters or fewer`))
358
+ if (typeof options.description === 'string') {
359
+ const len = options.description.trim().length
360
+ if (len > MAX_DESC)
361
+ warn(formatWarn('prunelle.config.ts', undefined, 0, 'long-description', `default seo({ description }) is ${len} characters (recommended max ${MAX_DESC})`, `shorten \`description\` to ${MAX_DESC} characters or fewer`))
362
+ }
363
+ else if (options.description !== undefined) {
364
+ for (const [locale, text] of Object.entries(options.description).sort(([a], [b]) => a.localeCompare(b))) {
365
+ const len = text.trim().length
366
+ if (len > MAX_DESC)
367
+ warn(formatWarn('prunelle.config.ts', undefined, 0, 'long-description', `seo({ description }) for locale "${locale}" is ${len} characters (recommended max ${MAX_DESC})`, `shorten it to ${MAX_DESC} characters or fewer`))
368
+ }
369
+ }
370
+ }
371
+
372
+ const REMOTE_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i
373
+
374
+ // A share image served by the app itself has to be a file of its public folder, or every preview of every page shows a broken image.
375
+ function checkImageFile(ctx: CheckPluginContext, image: string | undefined): void {
376
+ const path = image?.trim().split(/[?#]/)[0]
377
+ if (path === undefined || path === '' || ctx.publicDir === undefined || REMOTE_URL_RE.test(path))
378
+ return
379
+ const file = join(ctx.publicDir, decodeURIComponent(path.replace(/^\/+/, '')))
380
+ if (!existsSync(file))
381
+ ctx.warn(formatWarn('prunelle.config.ts', undefined, 0, 'missing-image-file', `seo({ image }) is "${image}", but ${relative(ctx.root, file)} does not exist, so share previews show no image`, `add the image to ${relative(ctx.root, ctx.publicDir) || '.'}/, or point \`image\` at a file there or at an absolute URL`))
382
+ }
383
+
384
+ function lastOwned(entries: readonly TextEntry[], file: string, code: string, fromLayout: boolean): OwnedEntry | undefined {
385
+ const last = entries[entries.length - 1]
386
+ return last === undefined ? undefined : { value: last.value, file, code, offset: last.offset, fromLayout }
387
+ }
388
+
389
+ function resolveEffectiveHead(
390
+ file: string,
391
+ code: string,
392
+ pageInfo: RouteHeadInfo,
393
+ layouts: readonly string[],
394
+ cache: Map<string, { code: string, info: RouteHeadInfo }>,
395
+ ): { title: OwnedEntry | undefined, description: OwnedEntry | undefined, hasOgImage: boolean, noindex: { file: string, offset: number } | undefined } {
396
+ let title: OwnedEntry | undefined
397
+ let description: OwnedEntry | undefined
398
+ let hasOgImage = pageInfo.hasOgImage
399
+ let noindex: { file: string, offset: number } | undefined
400
+
401
+ for (const lf of layouts) {
402
+ let c = cache.get(lf)
403
+ if (c === undefined) {
404
+ const lCode = readFileSync(lf, 'utf8')
405
+ c = { code: lCode, info: extractRouteHead(stripCommentsPreserveOffsets(lCode)) }
406
+ cache.set(lf, c)
407
+ }
408
+ title = lastOwned(c.info.titles, lf, c.code, true) ?? title
409
+ description = lastOwned(c.info.descriptions, lf, c.code, true) ?? description
410
+ if (c.info.hasOgImage) hasOgImage = true
411
+ if (c.info.noindexOffset !== undefined) noindex = { file: lf, offset: c.info.noindexOffset }
412
+ }
413
+ title = lastOwned(pageInfo.titles, file, code, false) ?? title
414
+ description = lastOwned(pageInfo.descriptions, file, code, false) ?? description
415
+ if (pageInfo.noindexOffset !== undefined) noindex = { file, offset: pageInfo.noindexOffset }
416
+ return { title, description, hasOgImage, noindex }
417
+ }
418
+
419
+ function checkRouteTitle(ctx: CheckPluginContext, options: SeoPluginOptions, state: StaticState, relFile: string, routePath: string, code: string, pageInfo: RouteHeadInfo, title: OwnedEntry | undefined): void {
420
+ if (title === undefined) {
421
+ ctx.warn(formatWarn(relFile, code, pageInfo.emptyTitleOffset ?? 0, 'missing-title', `route "${routePath}" has no <title> in <Head>`, `add <Head><title>...</title></Head> to ${relFile} or its _layout.tsx`))
422
+ return
423
+ }
424
+ if (title.value === undefined) return
425
+ const rendered = applyTitleTemplate(title.value, options)
426
+ if (rendered.length > MAX_TITLE) {
427
+ const ownerRel = relPosix(ctx.root, title.file)
428
+ const key = `title:${ownerRel}:${title.offset}`
429
+ if (!title.fromLayout || !state.warnedLayouts.has(key)) {
430
+ state.warnedLayouts.add(key)
431
+ ctx.warn(formatWarn(ownerRel, title.code, title.offset, 'long-title', `title "${rendered}" is ${rendered.length} characters (recommended max ${MAX_TITLE})`, `shorten the <title>${rendered !== title.value ? ' or titleTemplate' : ''} to ${MAX_TITLE} characters or fewer`))
432
+ }
433
+ state.longTitleUrls.add(routePath)
434
+ }
435
+ const prev = state.seenTitles.get(rendered)
436
+ if (prev !== undefined) {
437
+ ctx.warn(formatWarn(relFile, code, title.fromLayout ? 0 : title.offset, 'duplicate-title', `route "${routePath}" has the same <title> ("${rendered}") as "${prev.routePath}" (${prev.relFile})`, 'give each page a unique <title>'))
438
+ state.dupTitles.add(rendered)
439
+ }
440
+ else {
441
+ state.seenTitles.set(rendered, { relFile, routePath })
442
+ }
443
+ }
444
+
445
+ function checkRouteDescription(ctx: CheckPluginContext, state: StaticState, fallbackDesc: boolean, relFile: string, routePath: string, code: string, pageInfo: RouteHeadInfo, description: OwnedEntry | undefined): void {
446
+ if (description === undefined) {
447
+ if (!fallbackDesc)
448
+ ctx.warn(formatWarn(relFile, code, pageInfo.emptyDescriptionOffset ?? 0, 'missing-description', `route "${routePath}" has no meta description`, 'add <meta name="description" content="..." /> inside <Head> or set `description` in `seo()`'))
449
+ return
450
+ }
451
+ if (description.value === undefined) return
452
+ const desc = description.value
453
+ if (desc.length > MAX_DESC) {
454
+ const ownerRel = relPosix(ctx.root, description.file)
455
+ const key = `desc:${ownerRel}:${description.offset}`
456
+ if (!description.fromLayout || !state.warnedLayouts.has(key)) {
457
+ state.warnedLayouts.add(key)
458
+ ctx.warn(formatWarn(ownerRel, description.code, description.offset, 'long-description', `meta description is ${desc.length} characters (recommended max ${MAX_DESC})`, `shorten the description to ${MAX_DESC} characters or fewer`))
459
+ }
460
+ state.longDescUrls.add(routePath)
461
+ }
462
+ const prev = state.seenDescs.get(desc)
463
+ if (prev !== undefined) {
464
+ ctx.warn(formatWarn(relFile, code, description.fromLayout ? 0 : description.offset, 'duplicate-description', `route "${routePath}" has the same meta description as "${prev.routePath}" (${prev.relFile})`, 'give each page a unique meta description'))
465
+ state.dupDescs.add(desc)
466
+ }
467
+ else {
468
+ state.seenDescs.set(desc, { relFile, routePath })
469
+ }
470
+ }
471
+
472
+ function checkStaticRoutes(ctx: CheckPluginContext, options: SeoPluginOptions, siteConfigured: boolean, excluded: ReadonlySet<string>): StaticState {
473
+ const state: StaticState = {
474
+ longTitleUrls: new Set(), longDescUrls: new Set(), noindexUrls: new Set(),
475
+ dupTitles: new Set(), dupDescs: new Set(), warnedLayouts: new Set(),
476
+ seenTitles: new Map(), seenDescs: new Map(),
477
+ }
478
+ const layoutCache = new Map<string, { code: string, info: RouteHeadInfo }>()
479
+ const descOpt = options.description
480
+ const fallbackDesc = typeof descOpt === 'string' ? descOpt.trim().length > 0 : descOpt !== undefined && Object.values(descOpt).some(v => v.trim().length > 0)
481
+ const hasDefaultImage = Boolean(options.image?.trim())
482
+
483
+ for (const file of walkRouteFiles(ctx.routesDir)) {
484
+ if (basename(file).startsWith('_')) continue
485
+ const code = readFileSync(file, 'utf8')
486
+ const exports = scanExports(file, code)
487
+ if (exports === undefined || !exports.includes('default') || exports.includes('GET')) continue
488
+ const routePath = fileToRoutePath(ctx.routesDir, file)
489
+ if (isSkippedPath(routePath)) continue
490
+
491
+ const relFile = relPosix(ctx.root, file)
492
+ const stripped = stripCommentsPreserveOffsets(code)
493
+ const pageInfo = extractRouteHead(stripped)
494
+ const effective = resolveEffectiveHead(file, code, pageInfo, ancestorLayouts(ctx.routesDir, file), layoutCache)
495
+
496
+ checkRouteTitle(ctx, options, state, relFile, routePath, code, pageInfo, effective.title)
497
+ checkRouteDescription(ctx, state, fallbackDesc, relFile, routePath, code, pageInfo, effective.description)
498
+
499
+ const isDynamic = routePath.includes(':') || routePath.includes('*')
500
+ const hasPrerender = exports.includes('prerender') && PRERENDER_TRUE_RE.test(stripped)
501
+ if (effective.noindex !== undefined && options.sitemap !== false && (!isDynamic || hasPrerender) && !excluded.has(routePath)) {
502
+ ctx.warn(formatWarn(relFile, code, effective.noindex.file === file ? effective.noindex.offset : 0, 'noindex-in-sitemap', `route "${routePath}" sets noindex but is included in sitemap.xml`, `add "${routePath}" to \`seo({ sitemapExclude })\` or remove \`noindex\``))
503
+ state.noindexUrls.add(routePath)
504
+ }
505
+ if (siteConfigured && !hasDefaultImage && !effective.hasOgImage)
506
+ ctx.warn(formatWarn(relFile, code, 0, 'missing-image', `route "${routePath}" has no share image while \`site\` is configured`, 'set `seo({ image: \'/og.png\' })` or add <meta property="og:image" content="..." /> in <Head>'))
507
+ }
508
+ return state
509
+ }
510
+
511
+ function collectHtmlFiles(dir: string, skipTopDirs: boolean): string[] {
512
+ const out: string[] = []
513
+ const walk = (cur: string, top: boolean): void => {
514
+ for (const e of readdirSync(cur, { withFileTypes: true })) {
515
+ if (e.isDirectory() && !e.name.startsWith('.') && !(top && skipTopDirs && SKIP_PRERENDER_DIRS.has(e.name)))
516
+ walk(join(cur, e.name), false)
517
+ else if (e.isFile() && e.name.endsWith('.html'))
518
+ out.push(join(cur, e.name))
519
+ }
520
+ }
521
+ if (existsSync(dir)) walk(dir, true)
522
+ return out.sort()
523
+ }
524
+
525
+ function htmlFileToUrl(htmlRoot: string, file: string): string {
526
+ const rel = relPosix(htmlRoot, file)
527
+ if (rel === 'index.html') return '/'
528
+ if (rel.endsWith('/index.html')) return `/${rel.slice(0, -11)}`
529
+ return rel === '404.html' || rel === '500.html' ? `/${rel.slice(0, -5)}` : `/${rel}`
530
+ }
531
+
532
+ function parsePrerenderedHead(html: string): { title: string | undefined, description: string | undefined, noindex: boolean } {
533
+ const head = HTML_HEAD_RE.exec(html)?.[1] ?? html
534
+ const rawTitle = HTML_TITLE_RE.exec(head)?.[1]
535
+ const title = rawTitle !== undefined ? decodeEntities(rawTitle).replace(/\s+/g, ' ').trim() || undefined : undefined
536
+ let description: string | undefined
537
+ let noindex = false
538
+ HTML_META_RE.lastIndex = 0
539
+ for (let m = HTML_META_RE.exec(head); m !== null; m = HTML_META_RE.exec(head)) {
540
+ const attrs = new Map<string, string>()
541
+ HTML_ATTR_RE.lastIndex = 0
542
+ for (let am = HTML_ATTR_RE.exec(m[0]); am !== null; am = HTML_ATTR_RE.exec(m[0]))
543
+ attrs.set(am[1]!.toLowerCase(), decodeEntities(am[2] ?? am[3] ?? am[4] ?? ''))
544
+ const name = attrs.get('name')?.trim().toLowerCase()
545
+ const content = attrs.get('content')?.trim()
546
+ if (name === 'description' && content) description = content
547
+ else if (name === 'robots' && content && NOINDEX_RE.test(content)) noindex = true
548
+ }
549
+ return { title, description, noindex }
550
+ }
551
+
552
+ function checkPrerenderedHtml(ctx: CheckPluginContext, options: SeoPluginOptions, excluded: ReadonlySet<string>, state: StaticState): void {
553
+ const outDir = getAppContext()?.outDir ?? join(ctx.root, 'dist')
554
+ const prerenderDir = join(outDir, 'prerendered')
555
+ const htmlRoot = existsSync(prerenderDir) ? prerenderDir : (existsSync(join(outDir, '.prunelle-output')) || existsSync(join(outDir, 'index.html'))) ? outDir : undefined
556
+ if (htmlRoot === undefined) return
557
+
558
+ const seenTitles = new Map<string, string>()
559
+ const seenDescs = new Map<string, string>()
560
+ const publicDir = ctx.publicDir ?? join(ctx.root, 'public')
561
+ for (const file of collectHtmlFiles(htmlRoot, htmlRoot === outDir)) {
562
+ const url = htmlFileToUrl(htmlRoot, file)
563
+ if (isSkippedPath(url)) continue
564
+ const html = readFileSync(file)
565
+ // A static export copies public/ beside its pages: a file that is still byte for byte the app's own is no page of the app (#72).
566
+ const shipped = join(publicDir, relative(htmlRoot, file))
567
+ if (htmlRoot === outDir && existsSync(shipped) && readFileSync(shipped).equals(html)) continue
568
+ const relFile = relPosix(ctx.root, file)
569
+ const { title, description, noindex } = parsePrerenderedHead(html.toString('utf8'))
570
+
571
+ if (title !== undefined) {
572
+ if (title.length > MAX_TITLE && !state.longTitleUrls.has(url))
573
+ ctx.warn(formatWarn(relFile, undefined, 0, 'long-title', `prerendered page "${url}" has a ${title.length}-character <title> (recommended max ${MAX_TITLE})`, `shorten the title to ${MAX_TITLE} characters or fewer`))
574
+ const prev = seenTitles.get(title)
575
+ if (prev !== undefined && !state.dupTitles.has(title))
576
+ ctx.warn(formatWarn(relFile, undefined, 0, 'duplicate-title', `prerendered page "${url}" has the same <title> ("${title}") as "${prev}"`, 'give each prerendered page a unique <title>'))
577
+ else if (prev === undefined) seenTitles.set(title, url)
578
+ }
579
+ if (description !== undefined) {
580
+ if (description.length > MAX_DESC && !state.longDescUrls.has(url))
581
+ ctx.warn(formatWarn(relFile, undefined, 0, 'long-description', `prerendered page "${url}" has a ${description.length}-character meta description (recommended max ${MAX_DESC})`, `shorten the description to ${MAX_DESC} characters or fewer`))
582
+ const prev = seenDescs.get(description)
583
+ if (prev !== undefined && !state.dupDescs.has(description))
584
+ ctx.warn(formatWarn(relFile, undefined, 0, 'duplicate-description', `prerendered page "${url}" has the same meta description as "${prev}"`, 'give each prerendered page a unique meta description'))
585
+ else if (prev === undefined) seenDescs.set(description, url)
586
+ }
587
+ if (noindex && options.sitemap !== false && !excluded.has(url) && !state.noindexUrls.has(url))
588
+ ctx.warn(formatWarn(relFile, undefined, 0, 'noindex-in-sitemap', `prerendered page "${url}" sets noindex but is included in sitemap.xml`, `add "${url}" to \`seo({ sitemapExclude })\` or remove \`noindex\``))
589
+ }
590
+ }
591
+
592
+ export function checkSeo(ctx: CheckPluginContext, options: SeoPluginOptions, activeSite: string | undefined): void {
593
+ const siteConfigured = hasConfiguredSite(ctx.root, options, activeSite)
594
+ const excluded = new Set((options.sitemapExclude ?? []).map(normalizePath))
595
+ checkConfigOptions(options, siteConfigured, ctx.warn)
596
+ checkImageFile(ctx, options.image)
597
+ const state = checkStaticRoutes(ctx, options, siteConfigured, excluded)
598
+ checkPrerenderedHtml(ctx, options, excluded, state)
599
+ }
package/src/index.ts ADDED
@@ -0,0 +1,617 @@
1
+ // @prunellejs/seo — SEO metadata, titleTemplate, JSON-LD, sitemap.xml, redirects, manifest, favicon, and self-hosted fonts.
2
+ // Built strictly on the public PrunellePlugin API (server, build, transformHtml).
3
+
4
+ import type { Html } from 'prunelle'
5
+ import type { ActiveI18nConfig, BuildPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunellePlugin, ServerPluginAPI, WebManifestIcon, WebManifestInfo } from 'prunelle/config'
6
+ import type { RequestContext } from 'prunelle/server'
7
+ import { existsSync, readFileSync } from 'node:fs'
8
+ import { basename, extname, join, resolve } from 'node:path'
9
+ import { definePlugin, I18N_CONFIG_SERVICE, WEB_MANIFEST_SERVICE } from 'prunelle/config'
10
+ import { escAttr, escJson, escXml, raw } from 'prunelle/server'
11
+ import { checkSeo } from './check'
12
+
13
+ export interface FontEntry {
14
+ family: string
15
+ /** Local relative path or package specifier (e.g. '@fontsource/inter/files/inter-latin-400-normal.woff2'). */
16
+ src: string
17
+ weight?: number | string | undefined
18
+ style?: 'normal' | 'italic' | undefined
19
+ display?: 'swap' | 'optional' | 'fallback' | 'block' | undefined
20
+ preload?: boolean | undefined
21
+ }
22
+
23
+ export interface ManifestOptions {
24
+ name?: string | undefined
25
+ shortName?: string | undefined
26
+ description?: string | undefined
27
+ themeColor?: string | undefined
28
+ backgroundColor?: string | undefined
29
+ display?: 'standalone' | 'minimal-ui' | 'fullscreen' | 'browser' | undefined
30
+ startUrl?: string | undefined
31
+ icons?: WebManifestIcon[] | undefined
32
+ }
33
+
34
+ export type RedirectTarget = string | { to: string, status?: 301 | 302 | 307 | 308 | undefined }
35
+
36
+ export interface SeoPluginOptions {
37
+ site?: string | undefined
38
+ name?: string | undefined
39
+ titleTemplate?: string | undefined
40
+ description?: string | Record<string, string> | undefined
41
+ image?: string | undefined
42
+ imageAlt?: string | undefined
43
+ locale?: string | undefined
44
+ jsonLd?: Record<string, unknown>[] | undefined
45
+ sitemap?: boolean | undefined
46
+ sitemapExclude?: string[] | undefined
47
+ extraUrls?: (() => string[]) | undefined
48
+ redirects?: Record<string, RedirectTarget> | undefined
49
+ favicon?: string | string[] | undefined
50
+ manifest?: ManifestOptions | undefined
51
+ fonts?: FontEntry[] | undefined
52
+ }
53
+
54
+ const JS_SCANNER = new Bun.Transpiler({ loader: 'js' })
55
+ const CANONICAL_LINK_RE = /<link rel="canonical" href="[^"]*">/
56
+ // A list page past the first, the one query parameter a canonical link keeps: page 1 is the bare URL.
57
+ const LIST_PAGE_RE = /^(?:[2-9]|[1-9]\d+)$/
58
+ const ABSOLUTE_URL_RE = /^(?:https?:)?\/\//i
59
+ const META_TAG_RE = /<meta\b[^>]*>/gi
60
+ const ROBOTS_NAME_RE = /\bname\s*=\s*(?:"robots"|'robots'|robots(?:\s|>|\/|$))/i
61
+ const CONTENT_ATTR_RE = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i
62
+ const NOINDEX_TOKEN_RE = /(?:^|[\s,])noindex(?:$|[\s,])/i
63
+ const HTML_ENTITY_RE = /&(?:amp|lt|gt|quot|apos|#39|#x27|#34|#38|#60|#62);/gi
64
+ const HTML_ENTITY_MAP: Record<string, string> = {
65
+ '&amp;': '&',
66
+ '&lt;': '<',
67
+ '&gt;': '>',
68
+ '&quot;': '"',
69
+ '&apos;': '\'',
70
+ '&#39;': '\'',
71
+ '&#x27;': '\'',
72
+ '&#34;': '"',
73
+ '&#38;': '&',
74
+ '&#60;': '<',
75
+ '&#62;': '>',
76
+ }
77
+
78
+ function decodeBasicHtmlEntities(text: string): string {
79
+ return text.includes('&') ? text.replace(HTML_ENTITY_RE, m => HTML_ENTITY_MAP[m.toLowerCase()] ?? m) : text
80
+ }
81
+
82
+ function hasNoindexMeta(html: string): boolean {
83
+ const headEnd = html.toLowerCase().indexOf('</head>')
84
+ const slice = headEnd === -1 ? html : html.slice(0, headEnd)
85
+ META_TAG_RE.lastIndex = 0
86
+ let match = META_TAG_RE.exec(slice)
87
+ while (match !== null) {
88
+ const tag = match[0]
89
+ if (ROBOTS_NAME_RE.test(tag)) {
90
+ const contentMatch = CONTENT_ATTR_RE.exec(tag)
91
+ const content = contentMatch?.[1] ?? contentMatch?.[2] ?? contentMatch?.[3]
92
+ if (content !== undefined && NOINDEX_TOKEN_RE.test(content))
93
+ return true
94
+ }
95
+ match = META_TAG_RE.exec(slice)
96
+ }
97
+ return false
98
+ }
99
+
100
+ function isPrerenderedNoindex(baseDir: string, relHtml: string): boolean {
101
+ const abs = join(baseDir, relHtml)
102
+ if (!existsSync(abs))
103
+ return false
104
+ try {
105
+ return hasNoindexMeta(readFileSync(abs, 'utf8'))
106
+ }
107
+ catch {
108
+ return false
109
+ }
110
+ }
111
+
112
+ function serializeJsonLd(schema: Record<string, unknown>): string {
113
+ const payload = '@context' in schema ? schema : { '@context': 'https://schema.org', ...schema }
114
+ return `<script type="application/ld+json">${escJson(JSON.stringify(payload))}</script>`
115
+ }
116
+
117
+ /** Render a page-specific JSON-LD script inside `<Head>{jsonLd({ ... })}</Head>`. */
118
+ export function jsonLd(schema: Record<string, unknown>): Html {
119
+ return raw(serializeJsonLd(schema))
120
+ }
121
+
122
+ function resolveFileOrPkg(root: string, spec: string): string | undefined {
123
+ const local = resolve(root, spec)
124
+ if (existsSync(local))
125
+ return local
126
+ try {
127
+ return Bun.resolveSync(spec, root)
128
+ }
129
+ catch {
130
+ return undefined
131
+ }
132
+ }
133
+
134
+ function normalizePathname(pathname: string): string {
135
+ const withSlash = pathname.startsWith('/') ? pathname : `/${pathname}`
136
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') || '/' : withSlash
137
+ }
138
+
139
+ function stripLocaleFromPath(pathname: string, i18n: ActiveI18nConfig): { locale: string, hasPrefix: boolean, basePath: string } {
140
+ const normalized = normalizePathname(pathname)
141
+ const parts = normalized.split('/')
142
+ const first = parts[1]
143
+ if (first !== undefined && i18n.locales.includes(first)) {
144
+ const rest = normalizePathname(`/${parts.slice(2).join('/')}`)
145
+ return { locale: first, hasPrefix: true, basePath: rest }
146
+ }
147
+ return { locale: i18n.defaultLocale, hasPrefix: false, basePath: normalized }
148
+ }
149
+
150
+ function localizeSitemapPath(basePath: string, locale: string, i18n: ActiveI18nConfig): string {
151
+ const clean = normalizePathname(basePath)
152
+ if (locale === i18n.defaultLocale && !i18n.prefixDefault)
153
+ return clean
154
+ return clean === '/' ? `/${locale}` : `/${locale}${clean}`
155
+ }
156
+
157
+ function localizeRedirectTarget(to: string, locale: string, i18n: ActiveI18nConfig): string {
158
+ if (!to.startsWith('/') || to.startsWith('//'))
159
+ return to
160
+ const cut = to.search(/[?#]/)
161
+ const pathname = cut === -1 ? to : to.slice(0, cut)
162
+ const suffix = cut === -1 ? '' : to.slice(cut)
163
+ const stripped = stripLocaleFromPath(pathname, i18n)
164
+ if (stripped.hasPrefix)
165
+ return to
166
+ return `${localizeSitemapPath(stripped.basePath, locale, i18n)}${suffix}`
167
+ }
168
+
169
+ function isErrorLikePath(pathname: string, i18n: ActiveI18nConfig | undefined): boolean {
170
+ const base = i18n !== undefined ? stripLocaleFromPath(pathname, i18n).basePath : normalizePathname(pathname)
171
+ return base === '/404' || base === '/500' || base === '/__pru_404__'
172
+ }
173
+
174
+ function isApiPath(pathname: string): boolean {
175
+ const norm = normalizePathname(pathname)
176
+ return norm === '/api' || norm.startsWith('/api/')
177
+ }
178
+
179
+ function isApiRouteFile(outDir: string, relFile: string): boolean {
180
+ const abs = join(outDir, relFile)
181
+ if (!existsSync(abs))
182
+ return false
183
+ try {
184
+ const { exports } = JS_SCANNER.scan(readFileSync(abs, 'utf8'))
185
+ return !exports.includes('default') || exports.includes('GET')
186
+ }
187
+ catch {
188
+ return false
189
+ }
190
+ }
191
+
192
+ function readPngSize(bytes: Uint8Array): { width: number, height: number } | undefined {
193
+ if (bytes.byteLength < 24)
194
+ return undefined
195
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
196
+ if (view.getUint32(0) !== 0x89504E47 || view.getUint32(4) !== 0x0D0A1A0A)
197
+ return undefined
198
+ const width = view.getUint32(16)
199
+ const height = view.getUint32(20)
200
+ return width > 0 && height > 0 ? { width, height } : undefined
201
+ }
202
+
203
+ function emitFavicons(ctx: BuildPluginContext, favicon: string | string[]): WebManifestIcon[] {
204
+ const favicons = Array.isArray(favicon) ? favicon : [favicon]
205
+ const resolved: Array<{ abs: string, ext: string, bytes: Uint8Array }> = []
206
+ const extCounts = new Map<string, number>()
207
+ for (const fav of favicons) {
208
+ const abs = resolveFileOrPkg(ctx.root, fav)
209
+ if (abs === undefined)
210
+ throw new Error(`@prunellejs/seo: favicon "${fav}" is neither a file under the app root nor a package file: fix the path given to \`seo({ favicon })\`.`)
211
+ const ext = extname(abs).toLowerCase()
212
+ const key = ext === '.svg' ? '.svg' : ext === '.png' ? '.png' : '.ico'
213
+ extCounts.set(key, (extCounts.get(key) ?? 0) + 1)
214
+ resolved.push({ abs, ext: key, bytes: new Uint8Array(readFileSync(abs)) })
215
+ }
216
+
217
+ const usedNames = new Set<string>()
218
+ const manifestIcons: WebManifestIcon[] = []
219
+ for (const item of resolved) {
220
+ const size = item.ext === '.png' ? readPngSize(item.bytes) : undefined
221
+ let outName: string
222
+ if ((extCounts.get(item.ext) ?? 0) === 1) {
223
+ outName = `favicon${item.ext}`
224
+ }
225
+ else {
226
+ const stem = basename(item.abs, extname(item.abs)).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'favicon'
227
+ const candidate = `${stem}${item.ext}`
228
+ if (!usedNames.has(candidate)) {
229
+ outName = candidate
230
+ }
231
+ else if (size !== undefined && !usedNames.has(`${stem}-${size.width}x${size.height}${item.ext}`)) {
232
+ outName = `${stem}-${size.width}x${size.height}${item.ext}`
233
+ }
234
+ else {
235
+ outName = `${stem}-${Bun.hash(item.bytes).toString(36).slice(0, 6)}${item.ext}`
236
+ }
237
+ }
238
+ usedNames.add(outName)
239
+ const href = ctx.emitPublic(outName, item.bytes)
240
+ const type = item.ext === '.svg' ? 'image/svg+xml' : item.ext === '.png' ? 'image/png' : 'image/x-icon'
241
+ const sizesAttr = size !== undefined ? ` sizes="${size.width}x${size.height}"` : ''
242
+ ctx.addHead(`<link rel="icon" href="${escAttr(href)}" type="${type}"${sizesAttr}>`)
243
+ if (item.ext === '.svg')
244
+ manifestIcons.push({ src: href, sizes: 'any', type })
245
+ else if (size !== undefined)
246
+ manifestIcons.push({ src: href, sizes: `${size.width}x${size.height}`, type })
247
+ }
248
+ return manifestIcons
249
+ }
250
+
251
+ function deriveFaviconIconsForCheck(root: string, favicon: string | string[] | undefined): WebManifestIcon[] {
252
+ if (favicon === undefined)
253
+ return []
254
+ const favicons = Array.isArray(favicon) ? favicon : [favicon]
255
+ const icons: WebManifestIcon[] = []
256
+ for (const fav of favicons) {
257
+ const abs = resolveFileOrPkg(root, fav)
258
+ if (abs === undefined)
259
+ continue
260
+ const ext = extname(abs).toLowerCase()
261
+ if (ext === '.svg') {
262
+ icons.push({ src: `/${basename(abs)}`, sizes: 'any', type: 'image/svg+xml' })
263
+ }
264
+ else if (ext === '.png') {
265
+ const size = readPngSize(new Uint8Array(readFileSync(abs)))
266
+ if (size !== undefined)
267
+ icons.push({ src: `/${basename(abs)}`, sizes: `${size.width}x${size.height}`, type: 'image/png' })
268
+ }
269
+ }
270
+ return icons
271
+ }
272
+
273
+ function buildManifestInfo(options: SeoPluginOptions, derivedIcons: readonly WebManifestIcon[]): WebManifestInfo | undefined {
274
+ const m = options.manifest
275
+ if (m === undefined)
276
+ return undefined
277
+ const icons = m.icons ?? (derivedIcons.length > 0 ? derivedIcons : undefined)
278
+ return {
279
+ name: m.name ?? options.name ?? '',
280
+ shortName: m.shortName ?? m.name ?? options.name ?? '',
281
+ startUrl: m.startUrl ?? '/',
282
+ display: m.display ?? 'standalone',
283
+ ...(icons !== undefined ? { icons } : {}),
284
+ source: '@prunellejs/seo',
285
+ }
286
+ }
287
+
288
+ function emitManifest(ctx: BuildPluginContext, options: SeoPluginOptions, faviconIcons: readonly WebManifestIcon[]): void {
289
+ const m = options.manifest
290
+ if (m === undefined)
291
+ return
292
+ const info = buildManifestInfo(options, faviconIcons)!
293
+ const defaultDesc = typeof options.description === 'string'
294
+ ? options.description
295
+ : (options.description ? Object.values(options.description)[0] : undefined)
296
+ const body = JSON.stringify({
297
+ name: info.name,
298
+ short_name: info.shortName,
299
+ description: m.description ?? defaultDesc,
300
+ start_url: info.startUrl,
301
+ display: info.display,
302
+ theme_color: m.themeColor,
303
+ background_color: m.backgroundColor,
304
+ ...(info.icons !== undefined && info.icons.length > 0 ? { icons: info.icons } : {}),
305
+ }, null, 2)
306
+ const href = ctx.emitPublic('manifest.webmanifest', body)
307
+ ctx.addHead(`<link rel="manifest" href="${escAttr(href)}">`)
308
+ if (m.themeColor)
309
+ ctx.addHead(`<meta name="theme-color" content="${escAttr(m.themeColor)}">`)
310
+ ctx.provide(WEB_MANIFEST_SERVICE, info)
311
+ }
312
+
313
+ function emitFonts(ctx: BuildPluginContext, fonts: FontEntry[]): void {
314
+ const cssRules: string[] = []
315
+ for (const font of fonts) {
316
+ const abs = resolveFileOrPkg(ctx.root, font.src)
317
+ if (abs === undefined)
318
+ throw new Error(`@prunellejs/seo: could not resolve font "${font.src}"`)
319
+ const bytes = new Uint8Array(readFileSync(abs))
320
+ const hash = Bun.hash(bytes).toString(36)
321
+ const ext = extname(abs).toLowerCase() || '.woff2'
322
+ const stem = basename(abs, ext).toLowerCase().replace(/[^a-z0-9-_]/g, '-')
323
+ const url = ctx.emitAsset(`fonts/${stem}-${hash}${ext}`, bytes)
324
+ const weight = font.weight ?? 400
325
+ const style = font.style ?? 'normal'
326
+ const display = font.display ?? 'swap'
327
+ const format = ext === '.woff2' ? 'woff2' : ext === '.woff' ? 'woff' : 'truetype'
328
+ cssRules.push(`@font-face{font-family:${JSON.stringify(font.family)};font-style:${style};font-weight:${weight};font-display:${display};src:url(${JSON.stringify(url)}) format(${JSON.stringify(format)});}`)
329
+ if (font.preload !== false && ext === '.woff2')
330
+ ctx.addHead(`<link rel="preload" href="${escAttr(url)}" as="font" type="font/woff2" crossorigin>`)
331
+ }
332
+ if (cssRules.length > 0) {
333
+ const css = cssRules.join('\n')
334
+ const cssHash = Bun.hash(css).toString(36)
335
+ const cssUrl = ctx.emitAsset(`fonts-${cssHash}.css`, css)
336
+ ctx.addStyle(cssUrl)
337
+ }
338
+ }
339
+
340
+ function emitSitemap(
341
+ ctx: FinalizeBuildContext,
342
+ site: string,
343
+ options: SeoPluginOptions,
344
+ i18nCfg: ActiveI18nConfig | undefined,
345
+ ): void {
346
+ const excluded = new Set(options.sitemapExclude ?? [])
347
+ const prerenderBaseDir = ctx.prerenderDir ?? ctx.outDir
348
+ const urls = new Set<string>()
349
+ for (const r of ctx.routes) {
350
+ if (isApiPath(r.path) || isErrorLikePath(r.path, i18nCfg) || isApiRouteFile(ctx.outDir, r.file))
351
+ continue
352
+ if (r.prerendered) {
353
+ for (const [u, relHtml] of Object.entries(r.prerendered)) {
354
+ if (!excluded.has(u) && !isApiPath(u) && !isErrorLikePath(u, i18nCfg) && !isPrerenderedNoindex(prerenderBaseDir, relHtml))
355
+ urls.add(u)
356
+ }
357
+ }
358
+ else if (!r.path.includes(':') && !r.path.includes('*')) {
359
+ if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
360
+ for (const loc of i18nCfg.locales) {
361
+ const localized = localizeSitemapPath(r.path, loc, i18nCfg)
362
+ if (!excluded.has(localized) && !excluded.has(r.path))
363
+ urls.add(localized)
364
+ }
365
+ }
366
+ else if (!excluded.has(r.path)) {
367
+ urls.add(r.path)
368
+ }
369
+ }
370
+ }
371
+ if (options.extraUrls !== undefined) {
372
+ for (const u of options.extraUrls()) {
373
+ if (!excluded.has(u) && !isErrorLikePath(u, i18nCfg))
374
+ urls.add(u)
375
+ }
376
+ }
377
+ const sortedUrls = [...urls].sort()
378
+ if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
379
+ const localeOrder = new Map(i18nCfg.locales.map((l, idx) => [l, idx]))
380
+ const byBase = new Map<string, Array<{ locale: string, path: string }>>()
381
+ for (const u of sortedUrls) {
382
+ const { locale, basePath } = stripLocaleFromPath(u, i18nCfg)
383
+ let group = byBase.get(basePath)
384
+ if (group === undefined) {
385
+ group = []
386
+ byBase.set(basePath, group)
387
+ }
388
+ if (!group.some(item => item.locale === locale))
389
+ group.push({ locale, path: u })
390
+ }
391
+ for (const group of byBase.values())
392
+ group.sort((a, b) => (localeOrder.get(a.locale) ?? 999) - (localeOrder.get(b.locale) ?? 999))
393
+
394
+ const entries = sortedUrls.map((u) => {
395
+ const { basePath } = stripLocaleFromPath(u, i18nCfg)
396
+ const group = byBase.get(basePath) ?? []
397
+ const alts = group
398
+ .map(a => `<xhtml:link rel="alternate" hreflang="${escXml(a.locale)}" href="${escXml(`${site}${a.path === '/' ? '/' : a.path}`)}"/>`)
399
+ .join('')
400
+ return ` <url><loc>${escXml(`${site}${u === '/' ? '/' : u}`)}</loc>${alts}</url>`
401
+ })
402
+ writeSitemaps(ctx, site, entries, ' xmlns:xhtml="http://www.w3.org/1999/xhtml"')
403
+ }
404
+ else {
405
+ writeSitemaps(ctx, site, sortedUrls.map(u => ` <url><loc>${escXml(`${site}${u === '/' ? '/' : u}`)}</loc></url>`), '')
406
+ }
407
+ }
408
+
409
+ // The most URLs one sitemap file may hold (sitemaps.org).
410
+ const SITEMAP_MAX_URLS = 50_000
411
+
412
+ // One `sitemap.xml`, or past SITEMAP_MAX_URLS, numbered files under a `sitemap.xml` index so robots.txt keeps its link.
413
+ function writeSitemaps(ctx: FinalizeBuildContext, site: string, entries: readonly string[], namespaces: string): void {
414
+ const urlset = (part: readonly string[]): string =>
415
+ `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${namespaces}>\n${part.join('\n')}\n</urlset>\n`
416
+ if (entries.length <= SITEMAP_MAX_URLS) {
417
+ ctx.emitPublic('sitemap.xml', urlset(entries))
418
+ return
419
+ }
420
+ const index: string[] = []
421
+ for (let start = 0; start < entries.length; start += SITEMAP_MAX_URLS) {
422
+ const file = `sitemap-${index.length + 1}.xml`
423
+ ctx.emitPublic(file, urlset(entries.slice(start, start + SITEMAP_MAX_URLS)))
424
+ index.push(` <sitemap><loc>${escXml(`${site}/${file}`)}</loc></sitemap>`)
425
+ }
426
+ ctx.emitPublic('sitemap.xml', `<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${index.join('\n')}\n</sitemapindex>\n`)
427
+ }
428
+
429
+ function registerRedirects(
430
+ api: ServerPluginAPI,
431
+ redirects: Record<string, RedirectTarget>,
432
+ i18nCfg: ActiveI18nConfig | undefined,
433
+ ): void {
434
+ for (const [from, target] of Object.entries(redirects)) {
435
+ const to = typeof target === 'string' ? target : target.to
436
+ const status = typeof target === 'string' ? 301 : (target.status ?? 301)
437
+ // A source with a locale prefix is matched before i18n strips it, so on the raw path, by a middleware scoped to it that leaves every other page alone.
438
+ if (i18nCfg !== undefined && stripLocaleFromPath(from, i18nCfg).hasPrefix) {
439
+ const source = normalizePathname(from)
440
+ api.use((ctx, next) => {
441
+ const read = ctx.request.method === 'GET' || ctx.request.method === 'HEAD'
442
+ return read && normalizePathname(ctx.url.pathname) === source ? ctx.redirect(to, status, { external: true }) : next()
443
+ }, { scope: source })
444
+ continue
445
+ }
446
+ api.route('GET', from, (ctx) => {
447
+ if (i18nCfg === undefined)
448
+ return ctx.redirect(to, status, { external: true })
449
+ const locale = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string'
450
+ ? ctx.locals.locale
451
+ : i18nCfg.defaultLocale
452
+ return ctx.redirect(localizeRedirectTarget(to, locale, i18nCfg), status, { external: true })
453
+ })
454
+ }
455
+ }
456
+
457
+ // A static export has no server to run the redirect routes, so `prunelle build --static` reads them from `_redirects` (Netlify and Cloudflare Pages read it too) and states them in its Caddy and nginx snippets. A source holding a pattern is left out, and one under i18n answers with the default locale.
458
+ function emitRedirectsFile(ctx: FinalizeBuildContext, redirects: Record<string, RedirectTarget>, i18nCfg: ActiveI18nConfig | undefined): void {
459
+ const lines = Object.entries(redirects).map(([from, target]) => {
460
+ const to = typeof target === 'string' ? target : target.to
461
+ const status = typeof target === 'string' ? 301 : (target.status ?? 301)
462
+ return `${from} ${i18nCfg === undefined ? to : localizeRedirectTarget(to, i18nCfg.defaultLocale, i18nCfg)} ${status}`
463
+ })
464
+ if (lines.length > 0)
465
+ ctx.emitPublic('_redirects', `${lines.join('\n')}\n`)
466
+ }
467
+
468
+ function resolveFallbackDescription(
469
+ description: SeoPluginOptions['description'],
470
+ ctx: RequestContext,
471
+ i18nCfg: ActiveI18nConfig | undefined,
472
+ ): string | undefined {
473
+ if (typeof description === 'string')
474
+ return description
475
+ if (description === undefined)
476
+ return undefined
477
+ const loc = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string' ? ctx.locals.locale : undefined
478
+ const fallbackLoc = i18nCfg?.defaultLocale
479
+ return (loc && description[loc]) ?? (fallbackLoc && description[fallbackLoc]) ?? Object.values(description)[0]
480
+ }
481
+
482
+ function applySeoHead(
483
+ head: DocumentHeadContext,
484
+ ctx: RequestContext,
485
+ options: SeoPluginOptions,
486
+ activeSite: string | undefined,
487
+ activeI18n: ActiveI18nConfig | undefined,
488
+ errorRequests: WeakSet<Request>,
489
+ seoCanonicalRequests: WeakSet<Request>,
490
+ ): void {
491
+ if (options.titleTemplate || options.name) {
492
+ if (head.title !== undefined) {
493
+ const hasBrand = options.name !== undefined
494
+ && (head.title.includes(options.name) || decodeBasicHtmlEntities(head.title).includes(options.name))
495
+ if (options.titleTemplate && !hasBrand) {
496
+ const safeTemplate = escAttr(options.titleTemplate)
497
+ head.title = safeTemplate.replace('%s', () => head.title!)
498
+ }
499
+ }
500
+ else if (options.name) {
501
+ head.title = escAttr(options.name)
502
+ }
503
+ }
504
+
505
+ const fallbackDesc = resolveFallbackDescription(options.description, ctx, activeI18n)
506
+ if (fallbackDesc && !head.headHtml.includes('name="description"')) {
507
+ const content = escAttr(fallbackDesc)
508
+ head.add(`<meta name="description" content="${content}">`)
509
+ if (!head.headHtml.includes('property="og:description"'))
510
+ head.add(`<meta property="og:description" content="${content}">`)
511
+ }
512
+
513
+ if (options.image && !head.headHtml.includes('property="og:image"')) {
514
+ const imgUrl = ABSOLUTE_URL_RE.test(options.image) || !activeSite
515
+ ? options.image
516
+ : `${activeSite}${options.image.startsWith('/') ? '' : '/'}${options.image}`
517
+ head.add(`<meta property="og:image" content="${escAttr(imgUrl)}">`)
518
+ if (!head.headHtml.includes('name="twitter:card"'))
519
+ head.add('<meta name="twitter:card" content="summary_large_image">')
520
+ if (options.imageAlt && !head.headHtml.includes('property="og:image:alt"'))
521
+ head.add(`<meta property="og:image:alt" content="${escAttr(options.imageAlt)}">`)
522
+ }
523
+
524
+ if (activeSite && !head.headHtml.includes('rel="canonical"') && !errorRequests.has(ctx.request) && !isErrorLikePath(ctx.url.pathname, activeI18n)) {
525
+ const page = ctx.url.searchParams.get('page')
526
+ const pageQuery = page !== null && LIST_PAGE_RE.test(page) ? `?page=${page}` : ''
527
+ const canonical = escAttr(`${activeSite}${normalizePathname(ctx.url.pathname)}${pageQuery}`)
528
+ head.add(`<link rel="canonical" href="${canonical}">`)
529
+ seoCanonicalRequests.add(ctx.request)
530
+ }
531
+ }
532
+
533
+ export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
534
+ let activeSite = options.site?.replace(/\/$/, '')
535
+ let activeI18n: ActiveI18nConfig | undefined
536
+ const errorRequests = new WeakSet<Request>()
537
+ const seoCanonicalRequests = new WeakSet<Request>()
538
+
539
+ const resolveSite = (ctxSite?: string): string | undefined =>
540
+ options.site?.replace(/\/$/, '') ?? ctxSite?.replace(/\/$/, '') ?? activeSite
541
+
542
+ return definePlugin({
543
+ name: '@prunellejs/seo',
544
+ after: ['@prunellejs/i18n'],
545
+ readsLocals: ['locale'],
546
+
547
+ requires(ctx) {
548
+ return resolveSite(ctx.site) === undefined
549
+ ? ['no `site`, so pages go out with no canonical link, no absolute `og:image` and no sitemap: set `site` in `prunelle.config.ts` (or pass it to `seo()`).']
550
+ : []
551
+ },
552
+
553
+ check(ctx) {
554
+ checkSeo(ctx, options, activeSite)
555
+ const manifestInfo = buildManifestInfo(options, options.manifest?.icons ? [] : deriveFaviconIconsForCheck(ctx.root, options.favicon))
556
+ if (manifestInfo !== undefined)
557
+ ctx.provide?.(WEB_MANIFEST_SERVICE, manifestInfo)
558
+ },
559
+
560
+ onError({ request }) {
561
+ errorRequests.add(request)
562
+ },
563
+
564
+ server(api) {
565
+ activeSite = resolveSite(api.site)
566
+ activeI18n = api.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
567
+ if (options.redirects !== undefined)
568
+ registerRedirects(api, options.redirects, activeI18n)
569
+
570
+ // Strip auto-injected canonical tag on 4xx/5xx fallback pages (e.g. _404.tsx / load() -> notFound()).
571
+ api.use(async (ctx, next) => {
572
+ const res = await next()
573
+ if (res.status >= 400 && seoCanonicalRequests.has(ctx.request) && !res.headers.has('content-encoding') && (res.headers.get('content-type') ?? '').includes('text/html')) {
574
+ const html = await res.text()
575
+ const cleaned = html.replace(CANONICAL_LINK_RE, '')
576
+ if (cleaned !== html) {
577
+ const headers = new Headers(res.headers)
578
+ headers.delete('content-length')
579
+ return new Response(cleaned, { status: res.status, statusText: res.statusText, headers })
580
+ }
581
+ }
582
+ return res
583
+ }, { scope: 'dynamic' })
584
+ },
585
+
586
+ build(ctx) {
587
+ activeSite = resolveSite(ctx.site)
588
+ activeI18n = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
589
+
590
+ if (options.name)
591
+ ctx.addHead(`<meta property="og:site_name" content="${escAttr(options.name)}">`)
592
+ if (options.locale)
593
+ ctx.addHead(`<meta property="og:locale" content="${escAttr(options.locale)}">`)
594
+ if (options.jsonLd) {
595
+ for (const schema of options.jsonLd)
596
+ ctx.addHead(serializeJsonLd(schema))
597
+ }
598
+ const faviconIcons = options.favicon ? emitFavicons(ctx, options.favicon) : []
599
+ emitManifest(ctx, options, faviconIcons)
600
+ if (options.fonts && options.fonts.length > 0)
601
+ emitFonts(ctx, options.fonts)
602
+ },
603
+
604
+ afterPrerender(ctx) {
605
+ const site = resolveSite(ctx.site)
606
+ const i18nCfg = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE) ?? activeI18n
607
+ if (site && options.sitemap !== false)
608
+ emitSitemap(ctx, site, options, i18nCfg)
609
+ if (ctx.isStatic && options.redirects !== undefined)
610
+ emitRedirectsFile(ctx, options.redirects, i18nCfg)
611
+ },
612
+
613
+ head(head, ctx) {
614
+ applySeoHead(head, ctx, options, activeSite, activeI18n, errorRequests, seoCanonicalRequests)
615
+ },
616
+ })
617
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.