69 lines
2.3 KiB
TypeScript
69 lines
2.3 KiB
TypeScript
import { send } from 'h3'
|
|
import { sitemapRoutes } from '~/data/sitemap-routes'
|
|
import { getSiteUrlFromEvent } from '~/server/utils/site-url'
|
|
import { toLocalePath } from '~/utils/locale-path'
|
|
import { toAbsoluteUrl } from '~/utils/seo'
|
|
import { LOCALE_HREFLANG, SITE_LOCALES, type SiteLocale } from '~/types/locale'
|
|
|
|
function escapeXml(value: string): string {
|
|
return value
|
|
.replaceAll('&', '&')
|
|
.replaceAll('<', '<')
|
|
.replaceAll('>', '>')
|
|
.replaceAll('"', '"')
|
|
.replaceAll("'", ''')
|
|
}
|
|
|
|
function buildAlternateLinks(siteUrl: string, basePath: string): string {
|
|
const enUrl = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(basePath, 'en')))
|
|
|
|
return [
|
|
...SITE_LOCALES.map((locale) => {
|
|
const href = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(basePath, locale)))
|
|
return ` <xhtml:link rel="alternate" hreflang="${LOCALE_HREFLANG[locale]}" href="${href}" />`
|
|
}),
|
|
` <xhtml:link rel="alternate" hreflang="x-default" href="${enUrl}" />`
|
|
].join('\n')
|
|
}
|
|
|
|
export default defineEventHandler((event) => {
|
|
const config = useRuntimeConfig()
|
|
const siteUrl = getSiteUrlFromEvent(event, String(config.public.siteUrl))
|
|
const lastmod = new Date().toISOString().slice(0, 10)
|
|
const locales: SiteLocale[] = [...SITE_LOCALES]
|
|
|
|
const urls = sitemapRoutes
|
|
.flatMap((route) =>
|
|
locales.map((locale) => {
|
|
const loc = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(route.path, locale)))
|
|
return [
|
|
' <url>',
|
|
` <loc>${loc}</loc>`,
|
|
buildAlternateLinks(siteUrl, route.path),
|
|
` <lastmod>${lastmod}</lastmod>`,
|
|
` <changefreq>${route.changefreq}</changefreq>`,
|
|
` <priority>${route.priority.toFixed(1)}</priority>`,
|
|
' </url>'
|
|
].join('\n')
|
|
})
|
|
)
|
|
.join('\n')
|
|
|
|
const body = [
|
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
'<?xml-stylesheet type="text/xsl" href="/sitemap.xsl"?>',
|
|
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">',
|
|
urls,
|
|
'</urlset>',
|
|
''
|
|
].join('\n')
|
|
|
|
setResponseHeaders(event, {
|
|
'content-type': 'application/xml; charset=utf-8',
|
|
'x-content-type-options': 'nosniff',
|
|
'cache-control': 'public, max-age=3600'
|
|
})
|
|
|
|
return send(event, body)
|
|
})
|