@prunellejs/seo 0.8.0 → 0.10.0

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 CHANGED
@@ -13,13 +13,13 @@
13
13
  - `titleTemplate`: e.g. `'%s | My App'` (skips wrapping if `<title>` already contains `name`).
14
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
15
  - `image`, `imageAlt`: default `og:image`, `twitter:card` (`summary_large_image`), and `og:image:alt`.
16
- - `locale`: default `og:locale`.
16
+ - `locale`: `string` or `Record<locale, string>` for `og:locale` (resolved per request from `ctx.locals.locale` when `@prunellejs/i18n` is active, mapping BCP 47 tags to `ll_CC` and emitting `og:locale:alternate` for sibling locales).
17
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).
18
+ - `sitemap`: `boolean` (default `true`, emitted in `afterPrerender` as `/sitemap.xml` with `xhtml:link` alternates including `hreflang="x-default"` when `@prunellejs/i18n` is active; past 50,000 URLs it becomes a sitemap index over `sitemap-1.xml`, `sitemap-2.xml`, ...). `sitemapExclude`: `string[]`. `extraUrls`: `readonly string[] | (() => readonly string[] | Promise<readonly string[]>)`.
19
+ - `redirects`: `Record<fromPath, string | { to: string, status?: 301 | 302 | 307 | 308 }>` (mounted as `GET` and `HEAD` routes, default `301`; a `--static` export writes exact paths — expanded across all configured locales, excluding dynamic patterns — to `dist/_redirects`, and `prunelle build --static` adds them to its Caddy and nginx snippets).
20
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
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">`).
22
+ - `fonts`: `Array<{ family, src, weight?, style?, display?, unicodeRange?, preload? }>` (resolves local paths or `@fontsource/*` specifiers, emits content-hashed assets + `@font-face` stylesheet with `format("opentype")` for `.otf` and optional `unicode-range`; auto-preloads `.woff2` entries without `unicodeRange` unless `preload` is set explicitly).
23
23
 
24
24
  ## Page-Specific JSON-LD
25
25
 
@@ -31,7 +31,8 @@
31
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
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
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`).
34
+ - Warns with `[seo/noindex-in-sitemap]` when a non-prerendered route sets `noindex` while still included in `sitemap.xml` (prerendered `noindex` pages are excluded from `sitemap.xml` automatically).
35
+ - Warns with `[seo/excessive-font-preload]` when `seo({ fonts })` preloads more than 2 font files.
35
36
  - 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
 
37
38
  ## Snippet
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/seo",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "SEO meta, JSON-LD, sitemap, redirects, and self-hosted fonts plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,6 @@
21
21
  "directory": "packages/plugin-seo"
22
22
  },
23
23
  "peerDependencies": {
24
- "prunelle": "^0.8.0"
24
+ "prunelle": "^0.10.0"
25
25
  }
26
26
  }
package/src/check.ts CHANGED
@@ -3,12 +3,14 @@
3
3
  import type { CheckPluginContext } from 'prunelle/config'
4
4
  import type { SeoPluginOptions } from './index'
5
5
  import { existsSync, readdirSync, readFileSync } from 'node:fs'
6
- import { basename, dirname, join, relative } from 'node:path'
6
+ import { basename, dirname, extname, join, relative } from 'node:path'
7
7
  import { isInside } from 'prunelle/config'
8
8
  import { getAppContext } from 'prunelle/internal/server'
9
+ import { shouldPreloadFont } from './index'
9
10
 
10
11
  const MAX_TITLE = 60
11
12
  const MAX_DESC = 160
13
+ const MAX_FONT_PRELOADS = 2
12
14
  const TS_EXT_RE = /\.(?:tsx|ts)$/
13
15
  const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
14
16
  const HEAD_BLOCK_RE = /<Head(?:\s(?:[^>"']|"[^"]*"|'[^']*')*)?(?<!\/)>([\s\S]*?)<\/Head>/g
@@ -42,7 +44,6 @@ interface OwnedEntry { value: string | undefined, file: string, code: string, of
42
44
  interface StaticState {
43
45
  longTitleUrls: Set<string>
44
46
  longDescUrls: Set<string>
45
- noindexUrls: Set<string>
46
47
  dupTitles: Set<string>
47
48
  dupDescs: Set<string>
48
49
  warnedLayouts: Set<string>
@@ -70,7 +71,13 @@ function fileToRoutePath(routesDir: string, file: string): string {
70
71
  return `/${clean.replace(/\[\.\.\.([^\]]+)\]/g, '*$1').replace(/\[([^\]]+)\]/g, ':$1')}`
71
72
  }
72
73
 
73
- function formatWarn(relFile: string, code: string | undefined, offset: number, rule: string, detail: string, fix: string): string {
74
+ type SeoRule = 'missing-site' | 'long-title' | 'long-description' | 'excessive-font-preload' | 'missing-image-file' | 'missing-title' | 'duplicate-title' | 'missing-description' | 'duplicate-description' | 'noindex-in-sitemap' | 'missing-image'
75
+
76
+ declare module 'prunelle/config' {
77
+ interface PrunellePluginRules extends Record<`seo/${SeoRule}`, true> {}
78
+ }
79
+
80
+ function formatWarn(relFile: string, code: string | undefined, offset: number, rule: SeoRule, detail: string, fix: string): string {
74
81
  let line = 1
75
82
  let col = 1
76
83
  if (code !== undefined) {
@@ -368,6 +375,11 @@ function checkConfigOptions(options: SeoPluginOptions, siteConfigured: boolean,
368
375
  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`))
369
376
  }
370
377
  }
378
+ if (options.fonts !== undefined && options.fonts.length > MAX_FONT_PRELOADS) {
379
+ const preloaded = options.fonts.filter(f => shouldPreloadFont(f, extname(f.src).toLowerCase() || '.woff2')).length
380
+ if (preloaded > MAX_FONT_PRELOADS)
381
+ warn(formatWarn('prunelle.config.ts', undefined, 0, 'excessive-font-preload', `seo({ fonts }) preloads ${preloaded} fonts, which delays initial rendering and downloads unused weights`, `set \`preload: false\` on non-critical fonts so at most ${MAX_FONT_PRELOADS} are preloaded`))
382
+ }
371
383
  }
372
384
 
373
385
  const REMOTE_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i
@@ -485,7 +497,7 @@ function checkRouteDescription(ctx: CheckPluginContext, state: StaticState, fall
485
497
 
486
498
  function checkStaticRoutes(ctx: CheckPluginContext, options: SeoPluginOptions, siteConfigured: boolean, excluded: ReadonlySet<string>): StaticState {
487
499
  const state: StaticState = {
488
- longTitleUrls: new Set(), longDescUrls: new Set(), noindexUrls: new Set(),
500
+ longTitleUrls: new Set(), longDescUrls: new Set(),
489
501
  dupTitles: new Set(), dupDescs: new Set(), warnedLayouts: new Set(),
490
502
  seenTitles: new Map(), seenDescs: new Map(),
491
503
  }
@@ -512,10 +524,9 @@ function checkStaticRoutes(ctx: CheckPluginContext, options: SeoPluginOptions, s
512
524
 
513
525
  const isDynamic = routePath.includes(':') || routePath.includes('*')
514
526
  const hasPrerender = exports.includes('prerender') && PRERENDER_TRUE_RE.test(stripped)
515
- if (effective.noindex !== undefined && options.sitemap !== false && (!isDynamic || hasPrerender) && !excluded.has(routePath)) {
527
+ // Prerendered pages are already filtered out of sitemap.xml by `isPrerenderedNoindex`; only non-prerendered SSR routes stay in sitemap.xml unless excluded.
528
+ if (effective.noindex !== undefined && options.sitemap !== false && !isDynamic && !hasPrerender && !excluded.has(routePath))
516
529
  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\``))
517
- state.noindexUrls.add(routePath)
518
- }
519
530
  if (siteConfigured && !hasDefaultImage && !effective.hasOgImage)
520
531
  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>'))
521
532
  }
@@ -543,12 +554,11 @@ function htmlFileToUrl(htmlRoot: string, file: string): string {
543
554
  return rel === '404.html' || rel === '500.html' ? `/${rel.slice(0, -5)}` : `/${rel}`
544
555
  }
545
556
 
546
- function parsePrerenderedHead(html: string): { title: string | undefined, description: string | undefined, noindex: boolean } {
557
+ function parsePrerenderedHead(html: string): { title: string | undefined, description: string | undefined } {
547
558
  const head = HTML_HEAD_RE.exec(html)?.[1] ?? html
548
559
  const rawTitle = HTML_TITLE_RE.exec(head)?.[1]
549
560
  const title = rawTitle !== undefined ? decodeEntities(rawTitle).replace(/\s+/g, ' ').trim() || undefined : undefined
550
561
  let description: string | undefined
551
- let noindex = false
552
562
  HTML_META_RE.lastIndex = 0
553
563
  for (let m = HTML_META_RE.exec(head); m !== null; m = HTML_META_RE.exec(head)) {
554
564
  const attrs = new Map<string, string>()
@@ -558,12 +568,11 @@ function parsePrerenderedHead(html: string): { title: string | undefined, descri
558
568
  const name = attrs.get('name')?.trim().toLowerCase()
559
569
  const content = attrs.get('content')?.trim()
560
570
  if (name === 'description' && content) description = content
561
- else if (name === 'robots' && content && NOINDEX_RE.test(content)) noindex = true
562
571
  }
563
- return { title, description, noindex }
572
+ return { title, description }
564
573
  }
565
574
 
566
- function checkPrerenderedHtml(ctx: CheckPluginContext, options: SeoPluginOptions, excluded: ReadonlySet<string>, state: StaticState): void {
575
+ function checkPrerenderedHtml(ctx: CheckPluginContext, state: StaticState): void {
567
576
  const outDir = getAppContext()?.outDir ?? join(ctx.root, 'dist')
568
577
  const prerenderDir = join(outDir, 'prerendered')
569
578
  const htmlRoot = existsSync(prerenderDir) ? prerenderDir : (existsSync(join(outDir, '.prunelle-output')) || existsSync(join(outDir, 'index.html'))) ? outDir : undefined
@@ -580,7 +589,7 @@ function checkPrerenderedHtml(ctx: CheckPluginContext, options: SeoPluginOptions
580
589
  const shipped = join(publicDir, relative(htmlRoot, file))
581
590
  if (htmlRoot === outDir && existsSync(shipped) && readFileSync(shipped).equals(html)) continue
582
591
  const relFile = relPosix(ctx.root, file)
583
- const { title, description, noindex } = parsePrerenderedHead(html.toString('utf8'))
592
+ const { title, description } = parsePrerenderedHead(html.toString('utf8'))
584
593
 
585
594
  if (title !== undefined) {
586
595
  if (title.length > MAX_TITLE && !state.longTitleUrls.has(url))
@@ -598,8 +607,6 @@ function checkPrerenderedHtml(ctx: CheckPluginContext, options: SeoPluginOptions
598
607
  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'))
599
608
  else if (prev === undefined) seenDescs.set(description, url)
600
609
  }
601
- if (noindex && options.sitemap !== false && !excluded.has(url) && !state.noindexUrls.has(url))
602
- 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\``))
603
610
  }
604
611
  }
605
612
 
@@ -609,5 +616,5 @@ export function checkSeo(ctx: CheckPluginContext, options: SeoPluginOptions, act
609
616
  checkConfigOptions(options, siteConfigured, ctx.warn)
610
617
  checkImageFile(ctx, options.image)
611
618
  const state = checkStaticRoutes(ctx, options, siteConfigured, excluded)
612
- checkPrerenderedHtml(ctx, options, excluded, state)
619
+ checkPrerenderedHtml(ctx, state)
613
620
  }
package/src/index.ts CHANGED
@@ -2,13 +2,15 @@
2
2
  // Built strictly on the public PrunellePlugin API (server, build, transformHtml).
3
3
 
4
4
  import type { Html } from 'prunelle'
5
- import type { ActiveI18nConfig, BuildPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunellePlugin, ServerPluginAPI, WebManifestIcon, WebManifestInfo } from 'prunelle/config'
5
+ import type { ActiveI18nConfig, BuildPluginContext, DocumentHeadContext, PrunellePlugin, ServerPluginAPI, WebManifestIcon, WebManifestInfo } from 'prunelle/config'
6
6
  import type { RequestContext } from 'prunelle/server'
7
7
  import { existsSync, readFileSync } from 'node:fs'
8
- import { basename, extname, join, resolve } from 'node:path'
8
+ import { basename, extname, resolve } from 'node:path'
9
9
  import { definePlugin, I18N_CONFIG_SERVICE, WEB_MANIFEST_SERVICE } from 'prunelle/config'
10
- import { escAttr, escJson, escXml, raw } from 'prunelle/server'
10
+ import { getAppContext } from 'prunelle/internal/server'
11
+ import { escAttr, escJson, raw } from 'prunelle/server'
11
12
  import { checkSeo } from './check'
13
+ import { emitRedirectsFile, emitSitemap, isErrorLikePath, localizeRedirectTarget, normalizePathname, stripLocaleFromPath } from './sitemap'
12
14
 
13
15
  export interface FontEntry {
14
16
  family: string
@@ -17,6 +19,8 @@ export interface FontEntry {
17
19
  weight?: number | string | undefined
18
20
  style?: 'normal' | 'italic' | undefined
19
21
  display?: 'swap' | 'optional' | 'fallback' | 'block' | undefined
22
+ /** Optional CSS `unicode-range` descriptor (e.g. `'U+0000-00FF, U+0131'`). Entries with a `unicodeRange` do not auto-preload unless `preload: true`. */
23
+ unicodeRange?: string | undefined
20
24
  preload?: boolean | undefined
21
25
  }
22
26
 
@@ -40,26 +44,21 @@ export interface SeoPluginOptions {
40
44
  description?: string | Record<string, string> | undefined
41
45
  image?: string | undefined
42
46
  imageAlt?: string | undefined
43
- locale?: string | undefined
47
+ locale?: string | Record<string, string> | undefined
44
48
  jsonLd?: Record<string, unknown>[] | undefined
45
49
  sitemap?: boolean | undefined
46
50
  sitemapExclude?: string[] | undefined
47
- extraUrls?: (() => string[]) | undefined
51
+ extraUrls?: readonly string[] | (() => readonly string[] | Promise<readonly string[]>) | undefined
48
52
  redirects?: Record<string, RedirectTarget> | undefined
49
53
  favicon?: string | string[] | undefined
50
54
  manifest?: ManifestOptions | undefined
51
55
  fonts?: FontEntry[] | undefined
52
56
  }
53
57
 
54
- const JS_SCANNER = new Bun.Transpiler({ loader: 'js' })
55
58
  const CANONICAL_LINK_RE = /<link rel="canonical" href="[^"]*">/
56
59
  // A list page past the first, the one query parameter a canonical link keeps: page 1 is the bare URL.
57
60
  const LIST_PAGE_RE = /^(?:[2-9]|[1-9]\d+)$/
58
61
  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
62
  const HTML_ENTITY_RE = /&(?:amp|lt|gt|quot|apos|#39|#x27|#34|#38|#60|#62);/gi
64
63
  const HTML_ENTITY_MAP: Record<string, string> = {
65
64
  '&amp;': '&',
@@ -75,38 +74,13 @@ const HTML_ENTITY_MAP: Record<string, string> = {
75
74
  '&#62;': '>',
76
75
  }
77
76
 
78
- function decodeBasicHtmlEntities(text: string): string {
79
- return text.includes('&') ? text.replace(HTML_ENTITY_RE, m => HTML_ENTITY_MAP[m.toLowerCase()] ?? m) : text
77
+ function normalizeSite(site: string | undefined): string | undefined {
78
+ const clean = site?.replace(/\/$/, '')
79
+ return clean !== undefined && clean !== '' ? clean : undefined
80
80
  }
81
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
- }
82
+ function decodeBasicHtmlEntities(text: string): string {
83
+ return text.includes('&') ? text.replace(HTML_ENTITY_RE, m => HTML_ENTITY_MAP[m.toLowerCase()] ?? m) : text
110
84
  }
111
85
 
112
86
  function serializeJsonLd(schema: Record<string, unknown>): string {
@@ -131,64 +105,6 @@ function resolveFileOrPkg(root: string, spec: string): string | undefined {
131
105
  }
132
106
  }
133
107
 
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
108
  function readPngSize(bytes: Uint8Array): { width: number, height: number } | undefined {
193
109
  if (bytes.byteLength < 24)
194
110
  return undefined
@@ -310,6 +226,24 @@ function emitManifest(ctx: BuildPluginContext, options: SeoPluginOptions, favico
310
226
  ctx.provide(WEB_MANIFEST_SERVICE, info)
311
227
  }
312
228
 
229
+ export function shouldPreloadFont(font: FontEntry, ext: string): boolean {
230
+ if (ext !== '.woff2')
231
+ return false
232
+ if (font.preload !== undefined)
233
+ return font.preload
234
+ return font.unicodeRange === undefined || font.unicodeRange.trim() === ''
235
+ }
236
+
237
+ function fontFormatForExt(ext: string): string {
238
+ if (ext === '.woff2')
239
+ return 'woff2'
240
+ if (ext === '.woff')
241
+ return 'woff'
242
+ if (ext === '.otf')
243
+ return 'opentype'
244
+ return 'truetype'
245
+ }
246
+
313
247
  function emitFonts(ctx: BuildPluginContext, fonts: FontEntry[]): void {
314
248
  const cssRules: string[] = []
315
249
  for (const font of fonts) {
@@ -324,9 +258,11 @@ function emitFonts(ctx: BuildPluginContext, fonts: FontEntry[]): void {
324
258
  const weight = font.weight ?? 400
325
259
  const style = font.style ?? 'normal'
326
260
  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')
261
+ const format = fontFormatForExt(ext)
262
+ const range = font.unicodeRange?.trim().replace(/;+$/, '')
263
+ const unicodeRange = range !== undefined && range !== '' ? `unicode-range:${range};` : ''
264
+ cssRules.push(`@font-face{font-family:${JSON.stringify(font.family)};font-style:${style};font-weight:${weight};font-display:${display};${unicodeRange}src:url(${JSON.stringify(url)}) format(${JSON.stringify(format)});}`)
265
+ if (shouldPreloadFont(font, ext))
330
266
  ctx.addHead(`<link rel="preload" href="${escAttr(url)}" as="font" type="font/woff2" crossorigin>`)
331
267
  }
332
268
  if (cssRules.length > 0) {
@@ -337,108 +273,6 @@ function emitFonts(ctx: BuildPluginContext, fonts: FontEntry[]): void {
337
273
  }
338
274
  }
339
275
 
340
- const SAFE_SITEMAP_PATH_RE = /^\/[A-Za-z0-9\-._~/]*$/
341
- const XML_FORBIDDEN_RE = /[\0-\x08\v\f\x0E-\x1F\uFFFE\uFFFF\uD800-\uDFFF]/gu
342
-
343
- function encodeSitemapPath(urlPath: string): string {
344
- if (SAFE_SITEMAP_PATH_RE.test(urlPath))
345
- return urlPath
346
- const cut = urlPath.search(/[?#]/)
347
- const rawPath = (cut === -1 ? urlPath : urlPath.slice(0, cut)).replace(XML_FORBIDDEN_RE, '')
348
- const suffix = cut === -1 ? '' : urlPath.slice(cut)
349
- const encoded = rawPath.split('/').map(encodeURIComponent).join('/')
350
- return `${encoded}${suffix}`
351
- }
352
-
353
- function emitSitemap(
354
- ctx: FinalizeBuildContext,
355
- site: string,
356
- options: SeoPluginOptions,
357
- i18nCfg: ActiveI18nConfig | undefined,
358
- ): void {
359
- const excluded = new Set(options.sitemapExclude ?? [])
360
- const prerenderBaseDir = ctx.prerenderDir ?? ctx.outDir
361
- const urls = new Set<string>()
362
- for (const r of ctx.routes) {
363
- if (isApiPath(r.path) || isErrorLikePath(r.path, i18nCfg) || isApiRouteFile(ctx.outDir, r.file))
364
- continue
365
- if (r.prerendered) {
366
- for (const [u, relHtml] of Object.entries(r.prerendered)) {
367
- if (!excluded.has(u) && !isApiPath(u) && !isErrorLikePath(u, i18nCfg) && !isPrerenderedNoindex(prerenderBaseDir, relHtml))
368
- urls.add(u)
369
- }
370
- }
371
- else if (!r.path.includes(':') && !r.path.includes('*')) {
372
- if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
373
- for (const loc of i18nCfg.locales) {
374
- const localized = localizeSitemapPath(r.path, loc, i18nCfg)
375
- if (!excluded.has(localized) && !excluded.has(r.path))
376
- urls.add(localized)
377
- }
378
- }
379
- else if (!excluded.has(r.path)) {
380
- urls.add(r.path)
381
- }
382
- }
383
- }
384
- if (options.extraUrls !== undefined) {
385
- for (const u of options.extraUrls()) {
386
- if (!excluded.has(u) && !isErrorLikePath(u, i18nCfg))
387
- urls.add(u)
388
- }
389
- }
390
- const sortedUrls = [...urls].sort()
391
- if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
392
- const localeOrder = new Map(i18nCfg.locales.map((l, idx) => [l, idx]))
393
- const byBase = new Map<string, Array<{ locale: string, path: string }>>()
394
- for (const u of sortedUrls) {
395
- const { locale, basePath } = stripLocaleFromPath(u, i18nCfg)
396
- let group = byBase.get(basePath)
397
- if (group === undefined) {
398
- group = []
399
- byBase.set(basePath, group)
400
- }
401
- if (!group.some(item => item.locale === locale))
402
- group.push({ locale, path: u })
403
- }
404
- for (const group of byBase.values())
405
- group.sort((a, b) => (localeOrder.get(a.locale) ?? 999) - (localeOrder.get(b.locale) ?? 999))
406
-
407
- const entries = sortedUrls.map((u) => {
408
- const { basePath } = stripLocaleFromPath(u, i18nCfg)
409
- const group = byBase.get(basePath) ?? []
410
- const alts = group
411
- .map(a => `<xhtml:link rel="alternate" hreflang="${escXml(a.locale)}" href="${escXml(`${site}${encodeSitemapPath(a.path)}`)}"/>`)
412
- .join('')
413
- return ` <url><loc>${escXml(`${site}${encodeSitemapPath(u)}`)}</loc>${alts}</url>`
414
- })
415
- writeSitemaps(ctx, site, entries, ' xmlns:xhtml="http://www.w3.org/1999/xhtml"')
416
- }
417
- else {
418
- writeSitemaps(ctx, site, sortedUrls.map(u => ` <url><loc>${escXml(`${site}${encodeSitemapPath(u)}`)}</loc></url>`), '')
419
- }
420
- }
421
-
422
- // The most URLs one sitemap file may hold (sitemaps.org).
423
- const SITEMAP_MAX_URLS = 50_000
424
-
425
- // One `sitemap.xml`, or past SITEMAP_MAX_URLS, numbered files under a `sitemap.xml` index so robots.txt keeps its link.
426
- function writeSitemaps(ctx: FinalizeBuildContext, site: string, entries: readonly string[], namespaces: string): void {
427
- const urlset = (part: readonly string[]): string =>
428
- `<?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`
429
- if (entries.length <= SITEMAP_MAX_URLS) {
430
- ctx.emitPublic('sitemap.xml', urlset(entries))
431
- return
432
- }
433
- const index: string[] = []
434
- for (let start = 0; start < entries.length; start += SITEMAP_MAX_URLS) {
435
- const file = `sitemap-${index.length + 1}.xml`
436
- ctx.emitPublic(file, urlset(entries.slice(start, start + SITEMAP_MAX_URLS)))
437
- index.push(` <sitemap><loc>${escXml(`${site}/${file}`)}</loc></sitemap>`)
438
- }
439
- 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`)
440
- }
441
-
442
276
  function registerRedirects(
443
277
  api: ServerPluginAPI,
444
278
  redirects: Record<string, RedirectTarget>,
@@ -456,28 +290,19 @@ function registerRedirects(
456
290
  }, { scope: source })
457
291
  continue
458
292
  }
459
- api.route('GET', from, (ctx) => {
293
+ const handler = (ctx: RequestContext): Response => {
460
294
  if (i18nCfg === undefined)
461
295
  return ctx.redirect(to, status, { external: true })
462
296
  const locale = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string'
463
297
  ? ctx.locals.locale
464
298
  : i18nCfg.defaultLocale
465
299
  return ctx.redirect(localizeRedirectTarget(to, locale, i18nCfg), status, { external: true })
466
- })
300
+ }
301
+ api.route('GET', from, handler)
302
+ api.route('HEAD', from, handler)
467
303
  }
468
304
  }
469
305
 
470
- // 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.
471
- function emitRedirectsFile(ctx: FinalizeBuildContext, redirects: Record<string, RedirectTarget>, i18nCfg: ActiveI18nConfig | undefined): void {
472
- const lines = Object.entries(redirects).map(([from, target]) => {
473
- const to = typeof target === 'string' ? target : target.to
474
- const status = typeof target === 'string' ? 301 : (target.status ?? 301)
475
- return `${from} ${i18nCfg === undefined ? to : localizeRedirectTarget(to, i18nCfg.defaultLocale, i18nCfg)} ${status}`
476
- })
477
- if (lines.length > 0)
478
- ctx.emitPublic('_redirects', `${lines.join('\n')}\n`)
479
- }
480
-
481
306
  function resolveFallbackDescription(
482
307
  description: SeoPluginOptions['description'],
483
308
  ctx: RequestContext,
@@ -492,12 +317,50 @@ function resolveFallbackDescription(
492
317
  return (loc && description[loc]) ?? (fallbackLoc && description[fallbackLoc]) ?? Object.values(description)[0]
493
318
  }
494
319
 
320
+ function toOgLocale(tag: string): string {
321
+ try {
322
+ const loc = new Intl.Locale(tag.replaceAll('_', '-'))
323
+ const max = loc.region !== undefined ? loc : loc.maximize()
324
+ return max.region !== undefined ? `${max.language}_${max.region}` : max.language
325
+ }
326
+ catch {
327
+ return tag.replaceAll('-', '_')
328
+ }
329
+ }
330
+
331
+ function matchesLanguageWithoutRegion(tag: string, configured: string): boolean {
332
+ if (tag.includes('-') || tag.includes('_'))
333
+ return false
334
+ const cfgLang = configured.split(/[-_]/, 1)[0]
335
+ return cfgLang !== undefined && cfgLang.toLowerCase() === tag.toLowerCase()
336
+ }
337
+
338
+ function resolveOgLocale(
339
+ localeOpt: SeoPluginOptions['locale'],
340
+ reqLocale: string | undefined,
341
+ i18nCfg: ActiveI18nConfig | undefined,
342
+ ): string | undefined {
343
+ if (typeof localeOpt === 'object') {
344
+ if (reqLocale !== undefined)
345
+ return localeOpt[reqLocale] ?? toOgLocale(reqLocale)
346
+ if (i18nCfg !== undefined)
347
+ return localeOpt[i18nCfg.defaultLocale] ?? toOgLocale(i18nCfg.defaultLocale)
348
+ return Object.values(localeOpt)[0]
349
+ }
350
+ if (typeof localeOpt === 'string') {
351
+ if (reqLocale === undefined || matchesLanguageWithoutRegion(reqLocale, localeOpt))
352
+ return localeOpt
353
+ return toOgLocale(reqLocale)
354
+ }
355
+ return reqLocale !== undefined ? toOgLocale(reqLocale) : undefined
356
+ }
357
+
495
358
  function applySeoHead(
496
359
  head: DocumentHeadContext,
497
360
  ctx: RequestContext,
498
361
  options: SeoPluginOptions,
499
- activeSite: string | undefined,
500
- activeI18n: ActiveI18nConfig | undefined,
362
+ site: string | undefined,
363
+ i18nCfg: ActiveI18nConfig | undefined,
501
364
  errorRequests: WeakSet<Request>,
502
365
  seoCanonicalRequests: WeakSet<Request>,
503
366
  ): void {
@@ -515,7 +378,27 @@ function applySeoHead(
515
378
  }
516
379
  }
517
380
 
518
- const fallbackDesc = resolveFallbackDescription(options.description, ctx, activeI18n)
381
+ const reqLocale = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string' ? ctx.locals.locale : undefined
382
+ const ogLocale = resolveOgLocale(options.locale, reqLocale, i18nCfg)
383
+ if (ogLocale !== undefined && !head.headHtml.includes('property="og:locale"'))
384
+ head.add(`<meta property="og:locale" content="${escAttr(ogLocale)}">`)
385
+ if (i18nCfg !== undefined && i18nCfg.locales.length > 1 && !head.headHtml.includes('property="og:locale:alternate"')) {
386
+ const currentLoc = reqLocale ?? i18nCfg.defaultLocale
387
+ const emitted = new Set<string>()
388
+ if (ogLocale !== undefined)
389
+ emitted.add(ogLocale)
390
+ for (const loc of i18nCfg.locales) {
391
+ if (loc === currentLoc)
392
+ continue
393
+ const altOg = resolveOgLocale(options.locale, loc, i18nCfg)
394
+ if (altOg !== undefined && !emitted.has(altOg)) {
395
+ emitted.add(altOg)
396
+ head.add(`<meta property="og:locale:alternate" content="${escAttr(altOg)}">`)
397
+ }
398
+ }
399
+ }
400
+
401
+ const fallbackDesc = resolveFallbackDescription(options.description, ctx, i18nCfg)
519
402
  if (fallbackDesc && !head.headHtml.includes('name="description"')) {
520
403
  const content = escAttr(fallbackDesc)
521
404
  head.add(`<meta name="description" content="${content}">`)
@@ -524,9 +407,9 @@ function applySeoHead(
524
407
  }
525
408
 
526
409
  if (options.image && !head.headHtml.includes('property="og:image"')) {
527
- const imgUrl = ABSOLUTE_URL_RE.test(options.image) || !activeSite
410
+ const imgUrl = ABSOLUTE_URL_RE.test(options.image) || !site
528
411
  ? options.image
529
- : `${activeSite}${options.image.startsWith('/') ? '' : '/'}${options.image}`
412
+ : `${site}${options.image.startsWith('/') ? '' : '/'}${options.image}`
530
413
  head.add(`<meta property="og:image" content="${escAttr(imgUrl)}">`)
531
414
  if (!head.headHtml.includes('name="twitter:card"'))
532
415
  head.add('<meta name="twitter:card" content="summary_large_image">')
@@ -534,37 +417,33 @@ function applySeoHead(
534
417
  head.add(`<meta property="og:image:alt" content="${escAttr(options.imageAlt)}">`)
535
418
  }
536
419
 
537
- if (activeSite && !head.headHtml.includes('rel="canonical"') && !errorRequests.has(ctx.request) && !isErrorLikePath(ctx.url.pathname, activeI18n)) {
420
+ if (site && !head.headHtml.includes('rel="canonical"') && !errorRequests.has(ctx.request) && !isErrorLikePath(ctx.url.pathname, i18nCfg)) {
538
421
  const page = ctx.url.searchParams.get('page')
539
422
  const pageQuery = page !== null && LIST_PAGE_RE.test(page) ? `?page=${page}` : ''
540
- const canonical = escAttr(`${activeSite}${normalizePathname(ctx.url.pathname)}${pageQuery}`)
423
+ const canonical = escAttr(`${site}${normalizePathname(ctx.url.pathname)}${pageQuery}`)
541
424
  head.add(`<link rel="canonical" href="${canonical}">`)
542
425
  seoCanonicalRequests.add(ctx.request)
543
426
  }
544
427
  }
545
428
 
546
429
  export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
547
- let activeSite = options.site?.replace(/\/$/, '')
548
- let activeI18n: ActiveI18nConfig | undefined
430
+ const configuredSite = normalizeSite(options.site)
549
431
  const errorRequests = new WeakSet<Request>()
550
432
  const seoCanonicalRequests = new WeakSet<Request>()
551
433
 
552
- const resolveSite = (ctxSite?: string): string | undefined =>
553
- options.site?.replace(/\/$/, '') ?? ctxSite?.replace(/\/$/, '') ?? activeSite
554
-
555
434
  return definePlugin({
556
435
  name: '@prunellejs/seo',
557
436
  after: ['@prunellejs/i18n'],
558
437
  readsLocals: ['locale'],
559
438
 
560
439
  requires(ctx) {
561
- return resolveSite(ctx.site) === undefined
440
+ return (configuredSite ?? normalizeSite(ctx.site)) === undefined
562
441
  ? ['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()`).']
563
442
  : []
564
443
  },
565
444
 
566
445
  check(ctx) {
567
- checkSeo(ctx, options, activeSite)
446
+ checkSeo(ctx, options, configuredSite ?? normalizeSite(ctx.site))
568
447
  const manifestInfo = buildManifestInfo(options, options.manifest?.icons ? [] : deriveFaviconIconsForCheck(ctx.root, options.favicon))
569
448
  if (manifestInfo !== undefined)
570
449
  ctx.provide?.(WEB_MANIFEST_SERVICE, manifestInfo)
@@ -575,10 +454,9 @@ export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
575
454
  },
576
455
 
577
456
  server(api) {
578
- activeSite = resolveSite(api.site)
579
- activeI18n = api.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
457
+ const i18nCfg = api.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
580
458
  if (options.redirects !== undefined)
581
- registerRedirects(api, options.redirects, activeI18n)
459
+ registerRedirects(api, options.redirects, i18nCfg)
582
460
 
583
461
  // Strip auto-injected canonical tag on 4xx/5xx fallback pages (e.g. _404.tsx / load() -> notFound()).
584
462
  api.use(async (ctx, next) => {
@@ -597,13 +475,8 @@ export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
597
475
  },
598
476
 
599
477
  build(ctx) {
600
- activeSite = resolveSite(ctx.site)
601
- activeI18n = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
602
-
603
478
  if (options.name)
604
479
  ctx.addHead(`<meta property="og:site_name" content="${escAttr(options.name)}">`)
605
- if (options.locale)
606
- ctx.addHead(`<meta property="og:locale" content="${escAttr(options.locale)}">`)
607
480
  if (options.jsonLd) {
608
481
  for (const schema of options.jsonLd)
609
482
  ctx.addHead(serializeJsonLd(schema))
@@ -615,16 +488,19 @@ export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
615
488
  },
616
489
 
617
490
  afterPrerender(ctx) {
618
- const site = resolveSite(ctx.site)
619
- const i18nCfg = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE) ?? activeI18n
620
- if (site && options.sitemap !== false)
621
- emitSitemap(ctx, site, options, i18nCfg)
491
+ const site = configuredSite ?? normalizeSite(ctx.site)
492
+ const i18nCfg = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
622
493
  if (ctx.isStatic && options.redirects !== undefined)
623
494
  emitRedirectsFile(ctx, options.redirects, i18nCfg)
495
+ if (site && options.sitemap !== false)
496
+ return emitSitemap(ctx, site, options, i18nCfg)
624
497
  },
625
498
 
626
499
  head(head, ctx) {
627
- applySeoHead(head, ctx, options, activeSite, activeI18n, errorRequests, seoCanonicalRequests)
500
+ const appCtx = getAppContext()
501
+ const site = configuredSite ?? normalizeSite(appCtx?.site)
502
+ const i18nCfg = appCtx?.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE)
503
+ applySeoHead(head, ctx, options, site, i18nCfg, errorRequests, seoCanonicalRequests)
628
504
  },
629
505
  })
630
506
  }
package/src/sitemap.ts ADDED
@@ -0,0 +1,262 @@
1
+ // Sitemap XML generation and static `_redirects` emission for `@prunellejs/seo`.
2
+
3
+ import type { ActiveI18nConfig, FinalizeBuildContext } from 'prunelle/config'
4
+ import type { RedirectTarget, SeoPluginOptions } from './index'
5
+ import { existsSync, readFileSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { escXml } from 'prunelle/server'
8
+
9
+ const JS_SCANNER = new Bun.Transpiler({ loader: 'js' })
10
+ const META_TAG_RE = /<meta\b[^>]*>/gi
11
+ const ROBOTS_NAME_RE = /\bname\s*=\s*(?:"robots"|'robots'|robots(?:\s|>|\/|$))/i
12
+ const CONTENT_ATTR_RE = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i
13
+ const NOINDEX_TOKEN_RE = /(?:^|[\s,])noindex(?:$|[\s,])/i
14
+ const SAFE_SITEMAP_PATH_RE = /^\/[A-Za-z0-9\-._~/]*$/
15
+ const XML_FORBIDDEN_RE = /[\0-\x08\v\f\x0E-\x1F\uFFFE\uFFFF\uD800-\uDFFF]/gu
16
+ const DYNAMIC_PATH_RE = /[*:]/
17
+
18
+ // The most URLs one sitemap file may hold (sitemaps.org).
19
+ const SITEMAP_MAX_URLS = 50_000
20
+
21
+ export function normalizePathname(pathname: string): string {
22
+ const withSlash = pathname.startsWith('/') ? pathname : `/${pathname}`
23
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, '') || '/' : withSlash
24
+ }
25
+
26
+ export function stripLocaleFromPath(pathname: string, i18n: ActiveI18nConfig): { locale: string, hasPrefix: boolean, basePath: string } {
27
+ const normalized = normalizePathname(pathname)
28
+ const parts = normalized.split('/')
29
+ const first = parts[1]
30
+ if (first !== undefined && i18n.locales.includes(first)) {
31
+ const rest = normalizePathname(`/${parts.slice(2).join('/')}`)
32
+ return { locale: first, hasPrefix: true, basePath: rest }
33
+ }
34
+ return { locale: i18n.defaultLocale, hasPrefix: false, basePath: normalized }
35
+ }
36
+
37
+ export function localizeSitemapPath(basePath: string, locale: string, i18n: ActiveI18nConfig): string {
38
+ const clean = normalizePathname(basePath)
39
+ if (locale === i18n.defaultLocale && !i18n.prefixDefault)
40
+ return clean
41
+ return clean === '/' ? `/${locale}` : `/${locale}${clean}`
42
+ }
43
+
44
+ export function localizeRedirectTarget(to: string, locale: string, i18n: ActiveI18nConfig): string {
45
+ if (!to.startsWith('/') || to.startsWith('//'))
46
+ return to
47
+ const cut = to.search(/[?#]/)
48
+ const pathname = cut === -1 ? to : to.slice(0, cut)
49
+ const suffix = cut === -1 ? '' : to.slice(cut)
50
+ const stripped = stripLocaleFromPath(pathname, i18n)
51
+ if (stripped.hasPrefix)
52
+ return to
53
+ return `${localizeSitemapPath(stripped.basePath, locale, i18n)}${suffix}`
54
+ }
55
+
56
+ export function isErrorLikePath(pathname: string, i18n: ActiveI18nConfig | undefined): boolean {
57
+ const base = i18n !== undefined ? stripLocaleFromPath(pathname, i18n).basePath : normalizePathname(pathname)
58
+ return base === '/404' || base === '/500' || base === '/__pru_404__'
59
+ }
60
+
61
+ function isApiPath(pathname: string): boolean {
62
+ const norm = normalizePathname(pathname)
63
+ return norm === '/api' || norm.startsWith('/api/')
64
+ }
65
+
66
+ function isApiRouteFile(outDir: string, relFile: string): boolean {
67
+ const abs = join(outDir, relFile)
68
+ if (!existsSync(abs))
69
+ return false
70
+ try {
71
+ const { exports } = JS_SCANNER.scan(readFileSync(abs, 'utf8'))
72
+ return !exports.includes('default') || exports.includes('GET')
73
+ }
74
+ catch {
75
+ return false
76
+ }
77
+ }
78
+
79
+ function hasNoindexMeta(html: string): boolean {
80
+ const headEnd = html.toLowerCase().indexOf('</head>')
81
+ const slice = headEnd === -1 ? html : html.slice(0, headEnd)
82
+ META_TAG_RE.lastIndex = 0
83
+ let match = META_TAG_RE.exec(slice)
84
+ while (match !== null) {
85
+ const tag = match[0]
86
+ if (ROBOTS_NAME_RE.test(tag)) {
87
+ const contentMatch = CONTENT_ATTR_RE.exec(tag)
88
+ const content = contentMatch?.[1] ?? contentMatch?.[2] ?? contentMatch?.[3]
89
+ if (content !== undefined && NOINDEX_TOKEN_RE.test(content))
90
+ return true
91
+ }
92
+ match = META_TAG_RE.exec(slice)
93
+ }
94
+ return false
95
+ }
96
+
97
+ function isPrerenderedNoindex(baseDir: string, relHtml: string): boolean {
98
+ const abs = join(baseDir, relHtml)
99
+ if (!existsSync(abs))
100
+ return false
101
+ try {
102
+ return hasNoindexMeta(readFileSync(abs, 'utf8'))
103
+ }
104
+ catch {
105
+ return false
106
+ }
107
+ }
108
+
109
+ function encodeSitemapPath(urlPath: string): string {
110
+ if (SAFE_SITEMAP_PATH_RE.test(urlPath))
111
+ return urlPath
112
+ const cut = urlPath.search(/[?#]/)
113
+ const rawPath = (cut === -1 ? urlPath : urlPath.slice(0, cut)).replace(XML_FORBIDDEN_RE, '')
114
+ const suffix = cut === -1 ? '' : urlPath.slice(cut)
115
+ const encoded = rawPath.split('/').map(encodeURIComponent).join('/')
116
+ return `${encoded}${suffix}`
117
+ }
118
+
119
+ // One `sitemap.xml`, or past SITEMAP_MAX_URLS, numbered files under a `sitemap.xml` index so robots.txt keeps its link.
120
+ function writeSitemaps(ctx: FinalizeBuildContext, site: string, entries: readonly string[], namespaces: string): void {
121
+ const urlset = (part: readonly string[]): string =>
122
+ `<?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`
123
+ if (entries.length <= SITEMAP_MAX_URLS) {
124
+ ctx.emitPublic('sitemap.xml', urlset(entries))
125
+ return
126
+ }
127
+ const index: string[] = []
128
+ for (let start = 0; start < entries.length; start += SITEMAP_MAX_URLS) {
129
+ const file = `sitemap-${index.length + 1}.xml`
130
+ ctx.emitPublic(file, urlset(entries.slice(start, start + SITEMAP_MAX_URLS)))
131
+ index.push(` <sitemap><loc>${escXml(`${site}/${file}`)}</loc></sitemap>`)
132
+ }
133
+ 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`)
134
+ }
135
+
136
+ function finalizeSitemap(
137
+ ctx: FinalizeBuildContext,
138
+ site: string,
139
+ urls: Set<string>,
140
+ extra: readonly string[] | undefined,
141
+ excluded: ReadonlySet<string>,
142
+ i18nCfg: ActiveI18nConfig | undefined,
143
+ ): void {
144
+ if (extra !== undefined) {
145
+ for (const u of extra) {
146
+ if (!excluded.has(u) && !isErrorLikePath(u, i18nCfg))
147
+ urls.add(u)
148
+ }
149
+ }
150
+ const sortedUrls = [...urls].sort()
151
+ if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
152
+ const localeOrder = new Map(i18nCfg.locales.map((l, idx) => [l, idx]))
153
+ const byBase = new Map<string, Array<{ locale: string, path: string }>>()
154
+ for (const u of sortedUrls) {
155
+ const { locale, basePath } = stripLocaleFromPath(u, i18nCfg)
156
+ let group = byBase.get(basePath)
157
+ if (group === undefined) {
158
+ group = []
159
+ byBase.set(basePath, group)
160
+ }
161
+ if (!group.some(item => item.locale === locale))
162
+ group.push({ locale, path: u })
163
+ }
164
+ for (const group of byBase.values())
165
+ group.sort((a, b) => (localeOrder.get(a.locale) ?? 999) - (localeOrder.get(b.locale) ?? 999))
166
+
167
+ const entries = sortedUrls.map((u) => {
168
+ const { basePath } = stripLocaleFromPath(u, i18nCfg)
169
+ const group = byBase.get(basePath) ?? []
170
+ const alts = group
171
+ .map(a => `<xhtml:link rel="alternate" hreflang="${escXml(a.locale)}" href="${escXml(`${site}${encodeSitemapPath(a.path)}`)}"/>`)
172
+ .join('')
173
+ const defaultAlt = group.find(a => a.locale === i18nCfg.defaultLocale)
174
+ const xDefault = defaultAlt !== undefined
175
+ ? `<xhtml:link rel="alternate" hreflang="x-default" href="${escXml(`${site}${encodeSitemapPath(defaultAlt.path)}`)}"/>`
176
+ : ''
177
+ return ` <url><loc>${escXml(`${site}${encodeSitemapPath(u)}`)}</loc>${alts}${xDefault}</url>`
178
+ })
179
+ writeSitemaps(ctx, site, entries, ' xmlns:xhtml="http://www.w3.org/1999/xhtml"')
180
+ }
181
+ else {
182
+ writeSitemaps(ctx, site, sortedUrls.map(u => ` <url><loc>${escXml(`${site}${encodeSitemapPath(u)}`)}</loc></url>`), '')
183
+ }
184
+ }
185
+
186
+ function isPromiseLike<T>(value: T | PromiseLike<T>): value is PromiseLike<T> {
187
+ return typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function'
188
+ }
189
+
190
+ export function emitSitemap(
191
+ ctx: FinalizeBuildContext,
192
+ site: string,
193
+ options: SeoPluginOptions,
194
+ i18nCfg: ActiveI18nConfig | undefined,
195
+ ): void | Promise<void> {
196
+ const excluded = new Set(options.sitemapExclude ?? [])
197
+ const prerenderBaseDir = ctx.prerenderDir ?? ctx.outDir
198
+ const urls = new Set<string>()
199
+ for (const r of ctx.routes) {
200
+ if (r.isApi === true || isApiPath(r.path) || isErrorLikePath(r.path, i18nCfg) || isApiRouteFile(ctx.outDir, r.file))
201
+ continue
202
+ if (r.prerendered) {
203
+ for (const [u, relHtml] of Object.entries(r.prerendered)) {
204
+ if (!excluded.has(u) && !isApiPath(u) && !isErrorLikePath(u, i18nCfg) && !isPrerenderedNoindex(prerenderBaseDir, relHtml))
205
+ urls.add(u)
206
+ }
207
+ }
208
+ else if (!r.path.includes(':') && !r.path.includes('*')) {
209
+ if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
210
+ for (const loc of i18nCfg.locales) {
211
+ const localized = localizeSitemapPath(r.path, loc, i18nCfg)
212
+ if (!excluded.has(localized) && !excluded.has(r.path))
213
+ urls.add(localized)
214
+ }
215
+ }
216
+ else if (!excluded.has(r.path)) {
217
+ urls.add(r.path)
218
+ }
219
+ }
220
+ }
221
+ const extraResult = typeof options.extraUrls === 'function' ? options.extraUrls() : options.extraUrls
222
+ if (extraResult !== undefined && isPromiseLike(extraResult)) {
223
+ return extraResult.then((extra) => {
224
+ finalizeSitemap(ctx, site, urls, extra, excluded, i18nCfg)
225
+ })
226
+ }
227
+ finalizeSitemap(ctx, site, urls, extraResult, excluded, i18nCfg)
228
+ }
229
+
230
+ // A static export has no server to run the redirect routes, so `prunelle build --static` writes exact rules to `_redirects` (Netlify and Cloudflare Pages read it too) and states them in its Caddy and nginx snippets. Sources holding a route pattern (`:` or `*`) are left out, and unprefixed rules expand across all configured locales.
231
+ export function emitRedirectsFile(ctx: FinalizeBuildContext, redirects: Record<string, RedirectTarget>, i18nCfg: ActiveI18nConfig | undefined): void {
232
+ const explicitPrefixed = new Set<string>()
233
+ if (i18nCfg !== undefined && i18nCfg.locales.length > 0) {
234
+ for (const from of Object.keys(redirects)) {
235
+ if (!DYNAMIC_PATH_RE.test(from) && stripLocaleFromPath(from, i18nCfg).hasPrefix)
236
+ explicitPrefixed.add(normalizePathname(from))
237
+ }
238
+ }
239
+ const lines: string[] = []
240
+ for (const [from, target] of Object.entries(redirects)) {
241
+ if (DYNAMIC_PATH_RE.test(from))
242
+ continue
243
+ const to = typeof target === 'string' ? target : target.to
244
+ const status = typeof target === 'string' ? 301 : (target.status ?? 301)
245
+ if (i18nCfg === undefined || i18nCfg.locales.length === 0) {
246
+ lines.push(`${from} ${to} ${status}`)
247
+ continue
248
+ }
249
+ if (stripLocaleFromPath(from, i18nCfg).hasPrefix) {
250
+ lines.push(`${normalizePathname(from)} ${to} ${status}`)
251
+ continue
252
+ }
253
+ for (const loc of i18nCfg.locales) {
254
+ const locFrom = localizeSitemapPath(from, loc, i18nCfg)
255
+ if (explicitPrefixed.has(locFrom))
256
+ continue
257
+ lines.push(`${locFrom} ${localizeRedirectTarget(to, loc, i18nCfg)} ${status}`)
258
+ }
259
+ }
260
+ if (lines.length > 0)
261
+ ctx.emitPublic('_redirects', `${lines.join('\n')}\n`)
262
+ }