@prunellejs/seo 0.0.0-stage → 0.1.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/llms.txt +48 -0
- package/package.json +24 -4
- package/src/index.ts +474 -0
- package/README.md +0 -3
package/llms.txt
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
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, 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). `sitemapExclude`: `string[]`. `extraUrls`: `() => string[]`.
|
|
19
|
+
- `redirects`: `Record<fromPath, string | { to: string, status?: 301 | 302 | 307 | 308 }>` (mounted as `GET` routes, default `301`).
|
|
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
|
+
## Snippet
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
// prunelle.config.ts
|
|
32
|
+
import { defineConfig } from 'prunelle/config'
|
|
33
|
+
import { seo } from '@prunellejs/seo'
|
|
34
|
+
|
|
35
|
+
export default defineConfig({
|
|
36
|
+
site: 'https://example.com',
|
|
37
|
+
plugins: [
|
|
38
|
+
seo({
|
|
39
|
+
name: 'Acme',
|
|
40
|
+
titleTemplate: '%s | Acme',
|
|
41
|
+
description: 'Fast web apps with Prunelle.',
|
|
42
|
+
favicon: 'public/favicon.svg',
|
|
43
|
+
fonts: [{ family: 'Inter', src: '@fontsource/inter/files/inter-latin-400-normal.woff2', weight: 400 }],
|
|
44
|
+
redirects: { '/old': '/new' },
|
|
45
|
+
}),
|
|
46
|
+
],
|
|
47
|
+
})
|
|
48
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/seo",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.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.1.2"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
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 } 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 } from 'prunelle/config'
|
|
10
|
+
import { escAttr, escJson, raw } from 'prunelle/server'
|
|
11
|
+
|
|
12
|
+
export interface FontEntry {
|
|
13
|
+
family: string
|
|
14
|
+
/** Local relative path or package specifier (e.g. '@fontsource/inter/files/inter-latin-400-normal.woff2'). */
|
|
15
|
+
src: string
|
|
16
|
+
weight?: number | string | undefined
|
|
17
|
+
style?: 'normal' | 'italic' | undefined
|
|
18
|
+
display?: 'swap' | 'optional' | 'fallback' | 'block' | undefined
|
|
19
|
+
preload?: boolean | undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ManifestOptions {
|
|
23
|
+
name?: string | undefined
|
|
24
|
+
shortName?: string | undefined
|
|
25
|
+
description?: string | undefined
|
|
26
|
+
themeColor?: string | undefined
|
|
27
|
+
backgroundColor?: string | undefined
|
|
28
|
+
display?: 'standalone' | 'minimal-ui' | 'fullscreen' | 'browser' | undefined
|
|
29
|
+
startUrl?: string | undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type RedirectTarget = string | { to: string, status?: 301 | 302 | 307 | 308 | undefined }
|
|
33
|
+
|
|
34
|
+
export interface SeoPluginOptions {
|
|
35
|
+
site?: string | undefined
|
|
36
|
+
name?: string | undefined
|
|
37
|
+
titleTemplate?: string | undefined
|
|
38
|
+
description?: string | Record<string, string> | undefined
|
|
39
|
+
image?: string | undefined
|
|
40
|
+
imageAlt?: string | undefined
|
|
41
|
+
locale?: string | undefined
|
|
42
|
+
jsonLd?: Record<string, unknown>[] | undefined
|
|
43
|
+
sitemap?: boolean | undefined
|
|
44
|
+
sitemapExclude?: string[] | undefined
|
|
45
|
+
extraUrls?: (() => string[]) | undefined
|
|
46
|
+
redirects?: Record<string, RedirectTarget> | undefined
|
|
47
|
+
favicon?: string | string[] | undefined
|
|
48
|
+
manifest?: ManifestOptions | undefined
|
|
49
|
+
fonts?: FontEntry[] | undefined
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const JS_SCANNER = new Bun.Transpiler({ loader: 'js' })
|
|
53
|
+
const CANONICAL_LINK_RE = /<link rel="canonical" href="[^"]*">/
|
|
54
|
+
const ABSOLUTE_URL_RE = /^(?:https?:)?\/\//i
|
|
55
|
+
|
|
56
|
+
function serializeJsonLd(schema: Record<string, unknown>): string {
|
|
57
|
+
const payload = '@context' in schema ? schema : { '@context': 'https://schema.org', ...schema }
|
|
58
|
+
return `<script type="application/ld+json">${escJson(JSON.stringify(payload))}</script>`
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Render a page-specific JSON-LD script inside `<Head>{jsonLd({ ... })}</Head>`. */
|
|
62
|
+
export function jsonLd(schema: Record<string, unknown>): Html {
|
|
63
|
+
return raw(serializeJsonLd(schema))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function resolveFileOrPkg(root: string, spec: string): string | undefined {
|
|
67
|
+
const local = resolve(root, spec)
|
|
68
|
+
if (existsSync(local))
|
|
69
|
+
return local
|
|
70
|
+
try {
|
|
71
|
+
return Bun.resolveSync(spec, root)
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return undefined
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function normalizePathname(pathname: string): string {
|
|
79
|
+
const withSlash = pathname.startsWith('/') ? pathname : `/${pathname}`
|
|
80
|
+
return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') || '/' : withSlash
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function stripLocaleFromPath(pathname: string, i18n: ActiveI18nConfig): { locale: string, hasPrefix: boolean, basePath: string } {
|
|
84
|
+
const normalized = normalizePathname(pathname)
|
|
85
|
+
const parts = normalized.split('/')
|
|
86
|
+
const first = parts[1]
|
|
87
|
+
if (first !== undefined && i18n.locales.includes(first)) {
|
|
88
|
+
const rest = normalizePathname(`/${parts.slice(2).join('/')}`)
|
|
89
|
+
return { locale: first, hasPrefix: true, basePath: rest }
|
|
90
|
+
}
|
|
91
|
+
return { locale: i18n.defaultLocale, hasPrefix: false, basePath: normalized }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function localizeSitemapPath(basePath: string, locale: string, i18n: ActiveI18nConfig): string {
|
|
95
|
+
const clean = normalizePathname(basePath)
|
|
96
|
+
if (locale === i18n.defaultLocale && !i18n.prefixDefault)
|
|
97
|
+
return clean
|
|
98
|
+
return clean === '/' ? `/${locale}` : `/${locale}${clean}`
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function localizeRedirectTarget(to: string, locale: string, i18n: ActiveI18nConfig): string {
|
|
102
|
+
if (!to.startsWith('/') || to.startsWith('//'))
|
|
103
|
+
return to
|
|
104
|
+
const cut = to.search(/[?#]/)
|
|
105
|
+
const pathname = cut === -1 ? to : to.slice(0, cut)
|
|
106
|
+
const suffix = cut === -1 ? '' : to.slice(cut)
|
|
107
|
+
const stripped = stripLocaleFromPath(pathname, i18n)
|
|
108
|
+
if (stripped.hasPrefix)
|
|
109
|
+
return to
|
|
110
|
+
return `${localizeSitemapPath(stripped.basePath, locale, i18n)}${suffix}`
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isErrorLikePath(pathname: string, i18n: ActiveI18nConfig | undefined): boolean {
|
|
114
|
+
const base = i18n !== undefined ? stripLocaleFromPath(pathname, i18n).basePath : normalizePathname(pathname)
|
|
115
|
+
return base === '/404' || base === '/500' || base === '/__pru_404__'
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function isApiPath(pathname: string): boolean {
|
|
119
|
+
const norm = normalizePathname(pathname)
|
|
120
|
+
return norm === '/api' || norm.startsWith('/api/')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function isApiRouteFile(outDir: string, relFile: string): boolean {
|
|
124
|
+
const abs = join(outDir, relFile)
|
|
125
|
+
if (!existsSync(abs))
|
|
126
|
+
return false
|
|
127
|
+
try {
|
|
128
|
+
const { exports } = JS_SCANNER.scan(readFileSync(abs, 'utf8'))
|
|
129
|
+
return !exports.includes('default') || exports.includes('GET')
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return false
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function readPngSize(bytes: Uint8Array): { width: number, height: number } | undefined {
|
|
137
|
+
if (bytes.byteLength < 24)
|
|
138
|
+
return undefined
|
|
139
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
140
|
+
if (view.getUint32(0) !== 0x89504E47 || view.getUint32(4) !== 0x0D0A1A0A)
|
|
141
|
+
return undefined
|
|
142
|
+
const width = view.getUint32(16)
|
|
143
|
+
const height = view.getUint32(20)
|
|
144
|
+
return width > 0 && height > 0 ? { width, height } : undefined
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function emitFavicons(ctx: BuildPluginContext, favicon: string | string[]): void {
|
|
148
|
+
const favicons = Array.isArray(favicon) ? favicon : [favicon]
|
|
149
|
+
const resolved: Array<{ abs: string, ext: string, bytes: Uint8Array }> = []
|
|
150
|
+
const extCounts = new Map<string, number>()
|
|
151
|
+
for (const fav of favicons) {
|
|
152
|
+
const abs = resolveFileOrPkg(ctx.root, fav)
|
|
153
|
+
if (abs === undefined)
|
|
154
|
+
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 })\`.`)
|
|
155
|
+
const ext = extname(abs).toLowerCase()
|
|
156
|
+
const key = ext === '.svg' ? '.svg' : ext === '.png' ? '.png' : '.ico'
|
|
157
|
+
extCounts.set(key, (extCounts.get(key) ?? 0) + 1)
|
|
158
|
+
resolved.push({ abs, ext: key, bytes: new Uint8Array(readFileSync(abs)) })
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const usedNames = new Set<string>()
|
|
162
|
+
for (const item of resolved) {
|
|
163
|
+
const size = item.ext === '.png' ? readPngSize(item.bytes) : undefined
|
|
164
|
+
let outName: string
|
|
165
|
+
if ((extCounts.get(item.ext) ?? 0) === 1) {
|
|
166
|
+
outName = `favicon${item.ext}`
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
const stem = basename(item.abs, extname(item.abs)).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'favicon'
|
|
170
|
+
const candidate = `${stem}${item.ext}`
|
|
171
|
+
if (!usedNames.has(candidate)) {
|
|
172
|
+
outName = candidate
|
|
173
|
+
}
|
|
174
|
+
else if (size !== undefined && !usedNames.has(`${stem}-${size.width}x${size.height}${item.ext}`)) {
|
|
175
|
+
outName = `${stem}-${size.width}x${size.height}${item.ext}`
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
outName = `${stem}-${Bun.hash(item.bytes).toString(36).slice(0, 6)}${item.ext}`
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
usedNames.add(outName)
|
|
182
|
+
const href = ctx.emitPublic(outName, item.bytes)
|
|
183
|
+
const type = item.ext === '.svg' ? 'image/svg+xml' : item.ext === '.png' ? 'image/png' : 'image/x-icon'
|
|
184
|
+
const sizesAttr = size !== undefined ? ` sizes="${size.width}x${size.height}"` : ''
|
|
185
|
+
ctx.addHead(`<link rel="icon" href="${escAttr(href)}" type="${type}"${sizesAttr}>`)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function emitManifest(ctx: BuildPluginContext, options: SeoPluginOptions): void {
|
|
190
|
+
const m = options.manifest
|
|
191
|
+
if (m === undefined)
|
|
192
|
+
return
|
|
193
|
+
const defaultDesc = typeof options.description === 'string'
|
|
194
|
+
? options.description
|
|
195
|
+
: (options.description ? Object.values(options.description)[0] : undefined)
|
|
196
|
+
const body = JSON.stringify({
|
|
197
|
+
name: m.name ?? options.name ?? '',
|
|
198
|
+
short_name: m.shortName ?? m.name ?? options.name ?? '',
|
|
199
|
+
description: m.description ?? defaultDesc,
|
|
200
|
+
start_url: m.startUrl ?? '/',
|
|
201
|
+
display: m.display ?? 'standalone',
|
|
202
|
+
theme_color: m.themeColor,
|
|
203
|
+
background_color: m.backgroundColor,
|
|
204
|
+
}, null, 2)
|
|
205
|
+
const href = ctx.emitPublic('manifest.webmanifest', body)
|
|
206
|
+
ctx.addHead(`<link rel="manifest" href="${escAttr(href)}">`)
|
|
207
|
+
if (m.themeColor)
|
|
208
|
+
ctx.addHead(`<meta name="theme-color" content="${escAttr(m.themeColor)}">`)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function emitFonts(ctx: BuildPluginContext, fonts: FontEntry[]): void {
|
|
212
|
+
const cssRules: string[] = []
|
|
213
|
+
for (const font of fonts) {
|
|
214
|
+
const abs = resolveFileOrPkg(ctx.root, font.src)
|
|
215
|
+
if (abs === undefined)
|
|
216
|
+
throw new Error(`@prunellejs/seo: could not resolve font "${font.src}"`)
|
|
217
|
+
const bytes = new Uint8Array(readFileSync(abs))
|
|
218
|
+
const hash = Bun.hash(bytes).toString(36)
|
|
219
|
+
const ext = extname(abs).toLowerCase() || '.woff2'
|
|
220
|
+
const stem = basename(abs, ext).toLowerCase().replace(/[^a-z0-9-_]/g, '-')
|
|
221
|
+
const url = ctx.emitAsset(`fonts/${stem}-${hash}${ext}`, bytes)
|
|
222
|
+
const weight = font.weight ?? 400
|
|
223
|
+
const style = font.style ?? 'normal'
|
|
224
|
+
const display = font.display ?? 'swap'
|
|
225
|
+
const format = ext === '.woff2' ? 'woff2' : ext === '.woff' ? 'woff' : 'truetype'
|
|
226
|
+
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)});}`)
|
|
227
|
+
if (font.preload !== false && ext === '.woff2')
|
|
228
|
+
ctx.addHead(`<link rel="preload" href="${escAttr(url)}" as="font" type="font/woff2" crossorigin>`)
|
|
229
|
+
}
|
|
230
|
+
if (cssRules.length > 0) {
|
|
231
|
+
const css = cssRules.join('\n')
|
|
232
|
+
const cssHash = Bun.hash(css).toString(36)
|
|
233
|
+
const cssUrl = ctx.emitAsset(`fonts-${cssHash}.css`, css)
|
|
234
|
+
ctx.addStyle(cssUrl)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function emitSitemap(
|
|
239
|
+
ctx: FinalizeBuildContext,
|
|
240
|
+
site: string,
|
|
241
|
+
options: SeoPluginOptions,
|
|
242
|
+
i18nCfg: ActiveI18nConfig | undefined,
|
|
243
|
+
): void {
|
|
244
|
+
const excluded = new Set(options.sitemapExclude ?? [])
|
|
245
|
+
const urls = new Set<string>()
|
|
246
|
+
for (const r of ctx.routes) {
|
|
247
|
+
if (isApiPath(r.path) || isErrorLikePath(r.path, i18nCfg) || isApiRouteFile(ctx.outDir, r.file))
|
|
248
|
+
continue
|
|
249
|
+
if (r.prerendered) {
|
|
250
|
+
for (const u of Object.keys(r.prerendered)) {
|
|
251
|
+
if (!excluded.has(u) && !isApiPath(u) && !isErrorLikePath(u, i18nCfg))
|
|
252
|
+
urls.add(u)
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
else if (!r.path.includes(':') && !r.path.includes('*')) {
|
|
256
|
+
if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
|
|
257
|
+
for (const loc of i18nCfg.locales) {
|
|
258
|
+
const localized = localizeSitemapPath(r.path, loc, i18nCfg)
|
|
259
|
+
if (!excluded.has(localized) && !excluded.has(r.path))
|
|
260
|
+
urls.add(localized)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
else if (!excluded.has(r.path)) {
|
|
264
|
+
urls.add(r.path)
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
if (options.extraUrls !== undefined) {
|
|
269
|
+
for (const u of options.extraUrls()) {
|
|
270
|
+
if (!excluded.has(u) && !isErrorLikePath(u, i18nCfg))
|
|
271
|
+
urls.add(u)
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const sortedUrls = [...urls].sort()
|
|
275
|
+
if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
|
|
276
|
+
const localeOrder = new Map(i18nCfg.locales.map((l, idx) => [l, idx]))
|
|
277
|
+
const byBase = new Map<string, Array<{ locale: string, path: string }>>()
|
|
278
|
+
for (const u of sortedUrls) {
|
|
279
|
+
const { locale, basePath } = stripLocaleFromPath(u, i18nCfg)
|
|
280
|
+
let group = byBase.get(basePath)
|
|
281
|
+
if (group === undefined) {
|
|
282
|
+
group = []
|
|
283
|
+
byBase.set(basePath, group)
|
|
284
|
+
}
|
|
285
|
+
if (!group.some(item => item.locale === locale))
|
|
286
|
+
group.push({ locale, path: u })
|
|
287
|
+
}
|
|
288
|
+
for (const group of byBase.values())
|
|
289
|
+
group.sort((a, b) => (localeOrder.get(a.locale) ?? 999) - (localeOrder.get(b.locale) ?? 999))
|
|
290
|
+
|
|
291
|
+
const entries = sortedUrls.map((u) => {
|
|
292
|
+
const { basePath } = stripLocaleFromPath(u, i18nCfg)
|
|
293
|
+
const group = byBase.get(basePath) ?? []
|
|
294
|
+
const alts = group
|
|
295
|
+
.map(a => `<xhtml:link rel="alternate" hreflang="${escAttr(a.locale)}" href="${escAttr(`${site}${a.path === '/' ? '/' : a.path}`)}"/>`)
|
|
296
|
+
.join('')
|
|
297
|
+
return ` <url><loc>${escAttr(`${site}${u === '/' ? '/' : u}`)}</loc>${alts}</url>`
|
|
298
|
+
}).join('\n')
|
|
299
|
+
const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n${entries}\n</urlset>\n`
|
|
300
|
+
ctx.emitPublic('sitemap.xml', xml)
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
const entries = sortedUrls.map(u => ` <url><loc>${escAttr(`${site}${u === '/' ? '/' : u}`)}</loc></url>`).join('\n')
|
|
304
|
+
const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries}\n</urlset>\n`
|
|
305
|
+
ctx.emitPublic('sitemap.xml', xml)
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function registerRedirects(
|
|
310
|
+
api: ServerPluginAPI,
|
|
311
|
+
redirects: Record<string, RedirectTarget>,
|
|
312
|
+
i18nCfg: ActiveI18nConfig | undefined,
|
|
313
|
+
): void {
|
|
314
|
+
for (const [from, target] of Object.entries(redirects)) {
|
|
315
|
+
const to = typeof target === 'string' ? target : target.to
|
|
316
|
+
const status = typeof target === 'string' ? 301 : (target.status ?? 301)
|
|
317
|
+
// 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.
|
|
318
|
+
if (i18nCfg !== undefined && stripLocaleFromPath(from, i18nCfg).hasPrefix) {
|
|
319
|
+
const source = normalizePathname(from)
|
|
320
|
+
api.use((ctx, next) => {
|
|
321
|
+
const read = ctx.request.method === 'GET' || ctx.request.method === 'HEAD'
|
|
322
|
+
return read && normalizePathname(ctx.url.pathname) === source ? ctx.redirect(to, status) : next()
|
|
323
|
+
}, { scope: source })
|
|
324
|
+
continue
|
|
325
|
+
}
|
|
326
|
+
api.route('GET', from, (ctx) => {
|
|
327
|
+
if (i18nCfg === undefined)
|
|
328
|
+
return ctx.redirect(to, status)
|
|
329
|
+
const locale = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string'
|
|
330
|
+
? ctx.locals.locale
|
|
331
|
+
: i18nCfg.defaultLocale
|
|
332
|
+
return ctx.redirect(localizeRedirectTarget(to, locale, i18nCfg), status)
|
|
333
|
+
})
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function resolveFallbackDescription(
|
|
338
|
+
description: SeoPluginOptions['description'],
|
|
339
|
+
ctx: RequestContext,
|
|
340
|
+
i18nCfg: ActiveI18nConfig | undefined,
|
|
341
|
+
): string | undefined {
|
|
342
|
+
if (typeof description === 'string')
|
|
343
|
+
return description
|
|
344
|
+
if (description === undefined)
|
|
345
|
+
return undefined
|
|
346
|
+
const loc = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string' ? ctx.locals.locale : undefined
|
|
347
|
+
const fallbackLoc = i18nCfg?.defaultLocale
|
|
348
|
+
return (loc && description[loc]) ?? (fallbackLoc && description[fallbackLoc]) ?? Object.values(description)[0]
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function applySeoHead(
|
|
352
|
+
head: DocumentHeadContext,
|
|
353
|
+
ctx: RequestContext,
|
|
354
|
+
options: SeoPluginOptions,
|
|
355
|
+
activeSite: string | undefined,
|
|
356
|
+
activeI18n: ActiveI18nConfig | undefined,
|
|
357
|
+
errorRequests: WeakSet<Request>,
|
|
358
|
+
seoCanonicalRequests: WeakSet<Request>,
|
|
359
|
+
): void {
|
|
360
|
+
if (options.titleTemplate || options.name) {
|
|
361
|
+
if (head.title !== undefined) {
|
|
362
|
+
if (options.titleTemplate && (!options.name || !head.title.includes(options.name))) {
|
|
363
|
+
const safeTemplate = escAttr(options.titleTemplate)
|
|
364
|
+
head.title = safeTemplate.replace('%s', () => head.title!)
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
else if (options.name) {
|
|
368
|
+
head.title = escAttr(options.name)
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const fallbackDesc = resolveFallbackDescription(options.description, ctx, activeI18n)
|
|
373
|
+
if (fallbackDesc && !head.headHtml.includes('name="description"')) {
|
|
374
|
+
const content = escAttr(fallbackDesc)
|
|
375
|
+
head.add(`<meta name="description" content="${content}">`)
|
|
376
|
+
if (!head.headHtml.includes('property="og:description"'))
|
|
377
|
+
head.add(`<meta property="og:description" content="${content}">`)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (options.image && !head.headHtml.includes('property="og:image"')) {
|
|
381
|
+
const imgUrl = ABSOLUTE_URL_RE.test(options.image) || !activeSite
|
|
382
|
+
? options.image
|
|
383
|
+
: `${activeSite}${options.image.startsWith('/') ? '' : '/'}${options.image}`
|
|
384
|
+
head.add(`<meta property="og:image" content="${escAttr(imgUrl)}">`)
|
|
385
|
+
if (!head.headHtml.includes('name="twitter:card"'))
|
|
386
|
+
head.add('<meta name="twitter:card" content="summary_large_image">')
|
|
387
|
+
if (options.imageAlt && !head.headHtml.includes('property="og:image:alt"'))
|
|
388
|
+
head.add(`<meta property="og:image:alt" content="${escAttr(options.imageAlt)}">`)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
if (activeSite && !head.headHtml.includes('rel="canonical"') && !errorRequests.has(ctx.request) && !isErrorLikePath(ctx.url.pathname, activeI18n)) {
|
|
392
|
+
const canonical = escAttr(`${activeSite}${ctx.url.pathname}`)
|
|
393
|
+
head.add(`<link rel="canonical" href="${canonical}">`)
|
|
394
|
+
seoCanonicalRequests.add(ctx.request)
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
|
|
399
|
+
let activeSite = options.site?.replace(/\/$/, '')
|
|
400
|
+
let activeI18n: ActiveI18nConfig | undefined
|
|
401
|
+
const errorRequests = new WeakSet<Request>()
|
|
402
|
+
const seoCanonicalRequests = new WeakSet<Request>()
|
|
403
|
+
|
|
404
|
+
const resolveSite = (ctxSite?: string): string | undefined =>
|
|
405
|
+
options.site?.replace(/\/$/, '') ?? ctxSite?.replace(/\/$/, '') ?? activeSite
|
|
406
|
+
|
|
407
|
+
return definePlugin({
|
|
408
|
+
name: '@prunellejs/seo',
|
|
409
|
+
after: ['@prunellejs/i18n'],
|
|
410
|
+
readsLocals: ['locale'],
|
|
411
|
+
|
|
412
|
+
requires(ctx) {
|
|
413
|
+
return resolveSite(ctx.site) === undefined
|
|
414
|
+
? ['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()`).']
|
|
415
|
+
: []
|
|
416
|
+
},
|
|
417
|
+
|
|
418
|
+
onError({ request }) {
|
|
419
|
+
errorRequests.add(request)
|
|
420
|
+
},
|
|
421
|
+
|
|
422
|
+
server(api) {
|
|
423
|
+
activeSite = resolveSite(api.site)
|
|
424
|
+
activeI18n = api.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
|
|
425
|
+
if (options.redirects !== undefined)
|
|
426
|
+
registerRedirects(api, options.redirects, activeI18n)
|
|
427
|
+
|
|
428
|
+
// Strip auto-injected canonical tag on 4xx/5xx fallback pages (e.g. _404.tsx / load() -> notFound()).
|
|
429
|
+
api.use(async (ctx, next) => {
|
|
430
|
+
const res = await next()
|
|
431
|
+
if (res.status >= 400 && seoCanonicalRequests.has(ctx.request) && !res.headers.has('content-encoding') && (res.headers.get('content-type') ?? '').includes('text/html')) {
|
|
432
|
+
const html = await res.text()
|
|
433
|
+
const cleaned = html.replace(CANONICAL_LINK_RE, '')
|
|
434
|
+
if (cleaned !== html) {
|
|
435
|
+
const headers = new Headers(res.headers)
|
|
436
|
+
headers.delete('content-length')
|
|
437
|
+
return new Response(cleaned, { status: res.status, statusText: res.statusText, headers })
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return res
|
|
441
|
+
}, { scope: 'dynamic' })
|
|
442
|
+
},
|
|
443
|
+
|
|
444
|
+
build(ctx) {
|
|
445
|
+
activeSite = resolveSite(ctx.site)
|
|
446
|
+
activeI18n = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
|
|
447
|
+
|
|
448
|
+
if (options.name)
|
|
449
|
+
ctx.addHead(`<meta property="og:site_name" content="${escAttr(options.name)}">`)
|
|
450
|
+
if (options.locale)
|
|
451
|
+
ctx.addHead(`<meta property="og:locale" content="${escAttr(options.locale)}">`)
|
|
452
|
+
if (options.jsonLd) {
|
|
453
|
+
for (const schema of options.jsonLd)
|
|
454
|
+
ctx.addHead(serializeJsonLd(schema))
|
|
455
|
+
}
|
|
456
|
+
if (options.favicon)
|
|
457
|
+
emitFavicons(ctx, options.favicon)
|
|
458
|
+
emitManifest(ctx, options)
|
|
459
|
+
if (options.fonts && options.fonts.length > 0)
|
|
460
|
+
emitFonts(ctx, options.fonts)
|
|
461
|
+
},
|
|
462
|
+
|
|
463
|
+
afterPrerender(ctx) {
|
|
464
|
+
const site = resolveSite(ctx.site)
|
|
465
|
+
const i18nCfg = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE) ?? activeI18n
|
|
466
|
+
if (site && options.sitemap !== false)
|
|
467
|
+
emitSitemap(ctx, site, options, i18nCfg)
|
|
468
|
+
},
|
|
469
|
+
|
|
470
|
+
head(head, ctx) {
|
|
471
|
+
applySeoHead(head, ctx, options, activeSite, activeI18n, errorRequests, seoCanonicalRequests)
|
|
472
|
+
},
|
|
473
|
+
})
|
|
474
|
+
}
|
package/README.md
DELETED