feat: CMS head and one JSON-LD graph on every server-rendered page (tracer)
- Nitro middleware resolves page requests once and hands the answer to the render (event.context.seo); the route middleware reuses it - useCmsSeo: html lang, hreflang links, og:locale and exactly one JSON-LD script with one @graph (CMS nodes plus useSchemaNode nodes, merged by @id) - local module (configKey seo): cms (alias of public.seo.enabled), breadcrumbs, links.newTabHint, rootFiles, resolveFiles - GET /api/__seo__/resolve for client navigation through the Nuxt server - smoke harness: count=, exact header=, noheader=, reqheader=, repeated options, resolves/apicalls/noreport lines, --no-site; v0.1.1 suite runs unchanged against a backend without /site
This commit is contained in:
50
app/utils/graph.ts
Normal file
50
app/utils/graph.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
// The one JSON-LD @graph of a page: the CMS's nodes (the resolve answer's
|
||||
// jsonld) plus the nodes layers and pages add through useSchemaNode, merged
|
||||
// by @id. Pure, so `node --test` drives it directly.
|
||||
|
||||
import type { SeoJsonLd, SeoSchemaNode } from './types.ts'
|
||||
|
||||
const SCHEMA_CONTEXT = 'https://schema.org'
|
||||
|
||||
function isNode(value: unknown): value is SeoSchemaNode {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/** The nodes of a jsonld value: its @graph, or the value itself when it is a single node. */
|
||||
function nodesOf(jsonld: unknown): SeoSchemaNode[] {
|
||||
if (!isNode(jsonld)) return []
|
||||
const graph = (jsonld as SeoJsonLd)['@graph']
|
||||
if (Array.isArray(graph)) return graph.filter(isNode)
|
||||
const { '@context': _context, ...node } = jsonld as Record<string, unknown>
|
||||
return Object.keys(node).length > 0 ? [node as SeoSchemaNode] : []
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges the CMS graph and the layer nodes into one {"@context", "@graph"}
|
||||
* object, or null when there is no node at all (then the page gets no
|
||||
* JSON-LD script). A layer node whose @id matches a node already in the
|
||||
* graph is merged into it, the values already there first (the CMS is the
|
||||
* editor's source of truth; the layer fills in what it lacks); a node
|
||||
* without @id or with a new @id is appended. The order of first appearance
|
||||
* is kept, so the output is stable between renders.
|
||||
*/
|
||||
export function mergeGraph(cmsJsonld: unknown, nodes: readonly unknown[] = []): { '@context': string; '@graph': SeoSchemaNode[] } | null {
|
||||
const graph: SeoSchemaNode[] = []
|
||||
const byId = new Map<string, number>()
|
||||
const add = (node: SeoSchemaNode) => {
|
||||
const id = typeof node['@id'] === 'string' && node['@id'] !== '' ? node['@id'] : null
|
||||
const { '@context': _context, ...clean } = node as Record<string, unknown>
|
||||
if (id !== null && byId.has(id)) {
|
||||
const at = byId.get(id) as number
|
||||
graph[at] = { ...clean, ...graph[at] } as SeoSchemaNode
|
||||
return
|
||||
}
|
||||
if (id !== null) byId.set(id, graph.length)
|
||||
graph.push({ ...clean } as SeoSchemaNode)
|
||||
}
|
||||
for (const node of nodesOf(cmsJsonld)) add(node)
|
||||
for (const node of nodes) if (isNode(node)) add(node)
|
||||
if (graph.length === 0) return null
|
||||
const context = isNode(cmsJsonld) && typeof (cmsJsonld as SeoJsonLd)['@context'] === 'string' ? ((cmsJsonld as SeoJsonLd)['@context'] as string) : SCHEMA_CONTEXT
|
||||
return { '@context': context, '@graph': graph }
|
||||
}
|
||||
39
app/utils/pagePath.ts
Normal file
39
app/utils/pagePath.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
// Which requests the Nitro SEO middleware resolves. Pure, so `node --test`
|
||||
// drives it directly; the name starts with `is` like Nuxt's own helpers and
|
||||
// is unique enough for the auto-import into the consuming app.
|
||||
|
||||
/**
|
||||
* File extensions that are never pages: build assets, images, fonts, data
|
||||
* and the root files (robots.txt, sitemap.xml, verification files), which
|
||||
* server/middleware/seo-root.ts handles.
|
||||
*/
|
||||
const ASSET_EXTENSIONS = new Set([
|
||||
'js', 'mjs', 'cjs', 'css', 'map', 'json', 'xml', 'txt', 'html', 'htm', 'xsl', 'webmanifest',
|
||||
'ico', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'svg', 'bmp', 'tif', 'tiff',
|
||||
'woff', 'woff2', 'ttf', 'otf', 'eot',
|
||||
'mp3', 'mp4', 'webm', 'ogg', 'wav', 'mov',
|
||||
'pdf', 'zip', 'gz', 'br', 'wasm',
|
||||
])
|
||||
|
||||
/**
|
||||
* True when `path` (path and query, as h3's event.path) is a page the SEO
|
||||
* middleware resolves: not Nuxt's or the layers' internal paths (/_nuxt,
|
||||
* /__nuxt_error, /_journal, /_seo …), not /api, and not a file with one of
|
||||
* the asset extensions, unless the extension is listed in `resolveFiles`
|
||||
* (module option seo.resolveFiles, default ['pdf'], so an old PDF address
|
||||
* can still redirect). Pages a Nuxt route renders under a dotted path (an
|
||||
* author slug with ".com") are still resolved by the route middleware.
|
||||
*/
|
||||
export function isPagePath(path: string, resolveFiles: readonly string[] = []): boolean {
|
||||
if (typeof path !== 'string' || !path.startsWith('/') || path.startsWith('//')) return false
|
||||
const pathname = (path.split('?')[0] ?? '').split('#')[0] ?? ''
|
||||
if (pathname.startsWith('/_')) return false
|
||||
if (pathname === '/api' || pathname.startsWith('/api/')) return false
|
||||
const last = pathname.slice(pathname.lastIndexOf('/') + 1)
|
||||
const dot = last.lastIndexOf('.')
|
||||
if (dot > 0) {
|
||||
const ext = last.slice(dot + 1).toLowerCase()
|
||||
if (ASSET_EXTENSIONS.has(ext) && !resolveFiles.map((e) => e.toLowerCase()).includes(ext)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -79,8 +79,22 @@ export function seoXRobotsTag(answer: SeoResolveAnswer | null): string {
|
||||
interface SeoHeadInput {
|
||||
title?: string
|
||||
titleTemplate?: string
|
||||
meta: Array<{ name?: string; property?: string; content: string }>
|
||||
link: Array<{ rel: string; href: string }>
|
||||
htmlAttrs?: { lang: string }
|
||||
meta: Array<{ name?: string; property?: string; content: string; key?: string }>
|
||||
link: Array<{ rel: string; href: string; hreflang?: string; key?: string }>
|
||||
}
|
||||
|
||||
/**
|
||||
* False when the layer is switched off: the runtime config
|
||||
* public.seo.enabled (NUXT_PUBLIC_SEO_ENABLED, since v0.1.0) or its alias
|
||||
* public.seo.cms (module option seo.cms, NUXT_PUBLIC_SEO_CMS) is false or
|
||||
* "false". Either one turns every CMS call off.
|
||||
*/
|
||||
export function seoEnabled(publicSeo: unknown): boolean {
|
||||
if (!publicSeo || typeof publicSeo !== 'object') return true
|
||||
const p = publicSeo as { enabled?: unknown; cms?: unknown }
|
||||
const off = (v: unknown) => v === false || v === 'false'
|
||||
return !off(p.enabled) && !off(p.cms)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,6 +145,19 @@ export function seoHeadInput(answer: SeoResolveAnswer | null, origin?: string):
|
||||
}
|
||||
}
|
||||
if (seo.canonical) head.link.push({ rel: 'canonical', href: seoAbsolute(seo.canonical, origin) })
|
||||
|
||||
// SEO plugin v0.2.0 keys; an older backend leaves them out and adds no tag.
|
||||
if (answer && typeof answer.html_lang === 'string' && answer.html_lang) head.htmlAttrs = { lang: answer.html_lang }
|
||||
property('og:locale', seo.og?.locale)
|
||||
const alternateLocales = Array.isArray(seo.og?.locale_alternates) ? seo.og.locale_alternates : []
|
||||
alternateLocales.forEach((locale, i) => {
|
||||
if (typeof locale === 'string' && locale) head.meta.push({ property: 'og:locale:alternate', content: locale, key: `og-locale-alt-${i}` })
|
||||
})
|
||||
for (const alt of Array.isArray(answer?.alternates) ? answer.alternates : []) {
|
||||
if (alt && typeof alt.hreflang === 'string' && alt.hreflang && typeof alt.url === 'string' && alt.url) {
|
||||
head.link.push({ rel: 'alternate', hreflang: alt.hreflang, href: seoAbsolute(alt.url, origin), key: `alt-${alt.hreflang}` })
|
||||
}
|
||||
}
|
||||
return head
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,16 @@ export interface SeoHead {
|
||||
canonical: string
|
||||
robots: string
|
||||
x_robots_tag: string
|
||||
og: { title: string; description: string; image: string; url: string }
|
||||
og: {
|
||||
title: string
|
||||
description: string
|
||||
image: string
|
||||
url: string
|
||||
/** og:locale of the page (pl_PL); absent from backends before SEO v0.2.0. */
|
||||
locale?: string
|
||||
/** og:locale:alternate values, one per other translated locale. */
|
||||
locale_alternates?: string[]
|
||||
}
|
||||
twitter: { card: string; site: string }
|
||||
verification: SeoMetaTag[]
|
||||
}
|
||||
@@ -35,4 +44,68 @@ export interface SeoResolveAnswer {
|
||||
staging: boolean
|
||||
/** Set on ok answers only. */
|
||||
seo: SeoHead | null
|
||||
// The keys below are additive (SEO plugin v0.2.0); an older backend leaves
|
||||
// them out and every consumer treats an absent key as empty.
|
||||
/** The <html lang> value (pl, pl-PL), set on ok answers. */
|
||||
html_lang?: string
|
||||
/** hreflang alternates including the page itself and x-default; absolute URLs. */
|
||||
alternates?: SeoAlternate[]
|
||||
/** One {"@context", "@graph"} object, or null. */
|
||||
jsonld?: SeoJsonLd | null
|
||||
breadcrumbs?: SeoBreadcrumb[]
|
||||
/** Present only when the request carries a page number. */
|
||||
pagination?: SeoPaginationAnswer
|
||||
outbound?: SeoOutbound
|
||||
autolinks?: Array<{ phrase: string; url: string }>
|
||||
autolink_max?: number
|
||||
}
|
||||
|
||||
export interface SeoAlternate {
|
||||
hreflang: string
|
||||
url: string
|
||||
}
|
||||
|
||||
/** A schema.org node; @id links nodes across the graph. */
|
||||
export type SeoSchemaNode = Record<string, unknown> & { '@id'?: string; '@type'?: string | string[] }
|
||||
|
||||
export interface SeoJsonLd {
|
||||
'@context'?: string
|
||||
'@graph'?: SeoSchemaNode[]
|
||||
}
|
||||
|
||||
export interface SeoBreadcrumb {
|
||||
name: string
|
||||
url: string
|
||||
path: string
|
||||
}
|
||||
|
||||
export interface SeoPaginationAnswer {
|
||||
form?: 'query' | 'path'
|
||||
param?: string
|
||||
segment?: string
|
||||
page?: number
|
||||
/** A page value that is not a page number (?page=abc): the layer answers 404. */
|
||||
invalid?: boolean
|
||||
}
|
||||
|
||||
export interface SeoOutbound {
|
||||
new_tab?: boolean
|
||||
nofollow_domains?: string[]
|
||||
sponsored_domains?: string[]
|
||||
}
|
||||
|
||||
/** GET /_seo/api/v1/site. Every key may be absent on an older backend. */
|
||||
export interface SeoSiteAnswer {
|
||||
site_url?: string
|
||||
default_locale?: string
|
||||
locales?: string[]
|
||||
unprefixed_locale?: string
|
||||
links?: { new_tab?: boolean }
|
||||
html_sitemap?: { enabled?: boolean; paths?: Record<string, string>; page_size?: number }
|
||||
routes?: Array<{ type: string; pattern: string }>
|
||||
/** Root file names the backend serves (verification files, the IndexNow key file). */
|
||||
root_files?: string[]
|
||||
llms?: boolean
|
||||
pagination?: { form?: 'query' | 'path'; param?: string; segments?: Record<string, string> }
|
||||
home_crumb?: { name?: string; url?: string } | null
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user