@prunellejs/seo 0.6.0 → 0.7.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/LICENSE +21 -0
- package/llms.txt +4 -4
- package/package.json +2 -2
- package/src/check.ts +19 -1
- package/src/index.ts +47 -13
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
CHANGED
|
@@ -8,15 +8,15 @@
|
|
|
8
8
|
|
|
9
9
|
## Plugin Setup (`seo(options?)`)
|
|
10
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.
|
|
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
12
|
- `name`: site name (`og:site_name` and fallback `<title>`).
|
|
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
16
|
- `locale`: default `og:locale`.
|
|
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). `sitemapExclude`: `string[]`. `extraUrls`: `() => string[]`.
|
|
19
|
-
- `redirects`: `Record<fromPath, string | { to: string, status?: 301 | 302 | 307 | 308 }>` (mounted as `GET` routes, default `301`).
|
|
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
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
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">`).
|
|
@@ -32,7 +32,7 @@
|
|
|
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
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"
|
|
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
36
|
|
|
37
37
|
## Snippet
|
|
38
38
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/seo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.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.
|
|
24
|
+
"prunelle": "^0.7.0"
|
|
25
25
|
}
|
|
26
26
|
}
|
package/src/check.ts
CHANGED
|
@@ -369,6 +369,18 @@ function checkConfigOptions(options: SeoPluginOptions, siteConfigured: boolean,
|
|
|
369
369
|
}
|
|
370
370
|
}
|
|
371
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
|
+
|
|
372
384
|
function lastOwned(entries: readonly TextEntry[], file: string, code: string, fromLayout: boolean): OwnedEntry | undefined {
|
|
373
385
|
const last = entries[entries.length - 1]
|
|
374
386
|
return last === undefined ? undefined : { value: last.value, file, code, offset: last.offset, fromLayout }
|
|
@@ -545,11 +557,16 @@ function checkPrerenderedHtml(ctx: CheckPluginContext, options: SeoPluginOptions
|
|
|
545
557
|
|
|
546
558
|
const seenTitles = new Map<string, string>()
|
|
547
559
|
const seenDescs = new Map<string, string>()
|
|
560
|
+
const publicDir = ctx.publicDir ?? join(ctx.root, 'public')
|
|
548
561
|
for (const file of collectHtmlFiles(htmlRoot, htmlRoot === outDir)) {
|
|
549
562
|
const url = htmlFileToUrl(htmlRoot, file)
|
|
550
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
|
|
551
568
|
const relFile = relPosix(ctx.root, file)
|
|
552
|
-
const { title, description, noindex } = parsePrerenderedHead(
|
|
569
|
+
const { title, description, noindex } = parsePrerenderedHead(html.toString('utf8'))
|
|
553
570
|
|
|
554
571
|
if (title !== undefined) {
|
|
555
572
|
if (title.length > MAX_TITLE && !state.longTitleUrls.has(url))
|
|
@@ -576,6 +593,7 @@ export function checkSeo(ctx: CheckPluginContext, options: SeoPluginOptions, act
|
|
|
576
593
|
const siteConfigured = hasConfiguredSite(ctx.root, options, activeSite)
|
|
577
594
|
const excluded = new Set((options.sitemapExclude ?? []).map(normalizePath))
|
|
578
595
|
checkConfigOptions(options, siteConfigured, ctx.warn)
|
|
596
|
+
checkImageFile(ctx, options.image)
|
|
579
597
|
const state = checkStaticRoutes(ctx, options, siteConfigured, excluded)
|
|
580
598
|
checkPrerenderedHtml(ctx, options, excluded, state)
|
|
581
599
|
}
|
package/src/index.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { RequestContext } from 'prunelle/server'
|
|
|
7
7
|
import { existsSync, readFileSync } from 'node:fs'
|
|
8
8
|
import { basename, extname, join, resolve } from 'node:path'
|
|
9
9
|
import { definePlugin, I18N_CONFIG_SERVICE, WEB_MANIFEST_SERVICE } from 'prunelle/config'
|
|
10
|
-
import { escAttr, escJson, raw } from 'prunelle/server'
|
|
10
|
+
import { escAttr, escJson, escXml, raw } from 'prunelle/server'
|
|
11
11
|
import { checkSeo } from './check'
|
|
12
12
|
|
|
13
13
|
export interface FontEntry {
|
|
@@ -53,6 +53,8 @@ export interface SeoPluginOptions {
|
|
|
53
53
|
|
|
54
54
|
const JS_SCANNER = new Bun.Transpiler({ loader: 'js' })
|
|
55
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+)$/
|
|
56
58
|
const ABSOLUTE_URL_RE = /^(?:https?:)?\/\//i
|
|
57
59
|
const META_TAG_RE = /<meta\b[^>]*>/gi
|
|
58
60
|
const ROBOTS_NAME_RE = /\bname\s*=\s*(?:"robots"|'robots'|robots(?:\s|>|\/|$))/i
|
|
@@ -393,18 +395,35 @@ function emitSitemap(
|
|
|
393
395
|
const { basePath } = stripLocaleFromPath(u, i18nCfg)
|
|
394
396
|
const group = byBase.get(basePath) ?? []
|
|
395
397
|
const alts = group
|
|
396
|
-
.map(a => `<xhtml:link rel="alternate" hreflang="${
|
|
398
|
+
.map(a => `<xhtml:link rel="alternate" hreflang="${escXml(a.locale)}" href="${escXml(`${site}${a.path === '/' ? '/' : a.path}`)}"/>`)
|
|
397
399
|
.join('')
|
|
398
|
-
return ` <url><loc>${
|
|
399
|
-
})
|
|
400
|
-
|
|
401
|
-
ctx.emitPublic('sitemap.xml', xml)
|
|
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"')
|
|
402
403
|
}
|
|
403
404
|
else {
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
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
|
|
407
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`)
|
|
408
427
|
}
|
|
409
428
|
|
|
410
429
|
function registerRedirects(
|
|
@@ -420,21 +439,32 @@ function registerRedirects(
|
|
|
420
439
|
const source = normalizePathname(from)
|
|
421
440
|
api.use((ctx, next) => {
|
|
422
441
|
const read = ctx.request.method === 'GET' || ctx.request.method === 'HEAD'
|
|
423
|
-
return read && normalizePathname(ctx.url.pathname) === source ? ctx.redirect(to, status) : next()
|
|
442
|
+
return read && normalizePathname(ctx.url.pathname) === source ? ctx.redirect(to, status, { external: true }) : next()
|
|
424
443
|
}, { scope: source })
|
|
425
444
|
continue
|
|
426
445
|
}
|
|
427
446
|
api.route('GET', from, (ctx) => {
|
|
428
447
|
if (i18nCfg === undefined)
|
|
429
|
-
return ctx.redirect(to, status)
|
|
448
|
+
return ctx.redirect(to, status, { external: true })
|
|
430
449
|
const locale = 'locale' in ctx.locals && typeof ctx.locals.locale === 'string'
|
|
431
450
|
? ctx.locals.locale
|
|
432
451
|
: i18nCfg.defaultLocale
|
|
433
|
-
return ctx.redirect(localizeRedirectTarget(to, locale, i18nCfg), status)
|
|
452
|
+
return ctx.redirect(localizeRedirectTarget(to, locale, i18nCfg), status, { external: true })
|
|
434
453
|
})
|
|
435
454
|
}
|
|
436
455
|
}
|
|
437
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
|
+
|
|
438
468
|
function resolveFallbackDescription(
|
|
439
469
|
description: SeoPluginOptions['description'],
|
|
440
470
|
ctx: RequestContext,
|
|
@@ -492,7 +522,9 @@ function applySeoHead(
|
|
|
492
522
|
}
|
|
493
523
|
|
|
494
524
|
if (activeSite && !head.headHtml.includes('rel="canonical"') && !errorRequests.has(ctx.request) && !isErrorLikePath(ctx.url.pathname, activeI18n)) {
|
|
495
|
-
const
|
|
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}`)
|
|
496
528
|
head.add(`<link rel="canonical" href="${canonical}">`)
|
|
497
529
|
seoCanonicalRequests.add(ctx.request)
|
|
498
530
|
}
|
|
@@ -574,6 +606,8 @@ export function seo(options: SeoPluginOptions = {}): PrunellePlugin {
|
|
|
574
606
|
const i18nCfg = ctx.inject<ActiveI18nConfig>(I18N_CONFIG_SERVICE) ?? activeI18n
|
|
575
607
|
if (site && options.sitemap !== false)
|
|
576
608
|
emitSitemap(ctx, site, options, i18nCfg)
|
|
609
|
+
if (ctx.isStatic && options.redirects !== undefined)
|
|
610
|
+
emitRedirectsFile(ctx, options.redirects, i18nCfg)
|
|
577
611
|
},
|
|
578
612
|
|
|
579
613
|
head(head, ctx) {
|