|
| 1 | +/** |
| 2 | + * hreflang alternate resolution for translated content (#1690). |
| 3 | + * |
| 4 | + * Mirrors the sitemap route's semantics so the render path and the |
| 5 | + * sitemap always agree: |
| 6 | + * |
| 7 | + * - Alternates are emitted per published locale variant of a |
| 8 | + * translation group, including a self-referencing entry (Google |
| 9 | + * recommends the page annotate itself). |
| 10 | + * - `x-default` points at the default-locale variant, falling back to |
| 11 | + * the first routable variant when the default locale has no |
| 12 | + * translation. |
| 13 | + * - Variants whose locale isn't in the configured `i18n.locales` list |
| 14 | + * are dropped: linking to a route the site can't serve is worse than |
| 15 | + * no link at all. |
| 16 | + * - Variants flagged `noindex` in the SEO panel are excluded — the |
| 17 | + * sitemap doesn't list them, and pointing search engines at a page |
| 18 | + * that asks not to be indexed is a contradictory signal. When the |
| 19 | + * entry itself is noindex the result is empty: a page opting out of |
| 20 | + * indexing shouldn't announce an hreflang set at all. |
| 21 | + * - When i18n is disabled (or no absolute site URL can be resolved, |
| 22 | + * which hreflang requires) the result is empty and no queries run. |
| 23 | + */ |
| 24 | + |
| 25 | +import type { Kysely } from "kysely"; |
| 26 | + |
| 27 | +import { ContentRepository } from "../database/repositories/content.js"; |
| 28 | +import type { Database } from "../database/types.js"; |
| 29 | +import { getI18nConfig, isI18nEnabled } from "../i18n/config.js"; |
| 30 | +import { interpolateUrlPattern, localizePath } from "../i18n/resolve.js"; |
| 31 | +import { requestCached } from "../request-cache.js"; |
| 32 | +import { getCollectionInfoWithDb } from "../schema/query.js"; |
| 33 | +import { getSiteSettingsWithDb } from "../settings/index.js"; |
| 34 | + |
| 35 | +const TRAILING_SLASH_RE = /\/$/; |
| 36 | +const ABSOLUTE_URL_RE = /^https?:\/\//i; |
| 37 | + |
| 38 | +/** |
| 39 | + * IDs of variants flagged `noindex` in the SEO panel. Entries without |
| 40 | + * an `_emdash_seo` row are indexable by default (same as the sitemap). |
| 41 | + * The id list is bounded by the number of configured locales, so no |
| 42 | + * chunking is needed. |
| 43 | + */ |
| 44 | +async function findNoindexIds( |
| 45 | + db: Kysely<Database>, |
| 46 | + collection: string, |
| 47 | + ids: string[], |
| 48 | +): Promise<Set<string>> { |
| 49 | + if (ids.length === 0) return new Set(); |
| 50 | + const rows = await db |
| 51 | + .selectFrom("_emdash_seo") |
| 52 | + .select("content_id") |
| 53 | + .where("collection", "=", collection) |
| 54 | + .where("content_id", "in", ids) |
| 55 | + .where("seo_no_index", "=", 1) |
| 56 | + .execute(); |
| 57 | + return new Set(rows.map((r) => r.content_id)); |
| 58 | +} |
| 59 | + |
| 60 | +/** A single alternate link, ready to render as `<link rel="alternate">`. */ |
| 61 | +export interface HreflangAlternate { |
| 62 | + /** Locale code, or `"x-default"` for the default variant */ |
| 63 | + hreflang: string; |
| 64 | + /** Absolute URL of the variant */ |
| 65 | + href: string; |
| 66 | +} |
| 67 | + |
| 68 | +export interface HreflangOptions { |
| 69 | + /** |
| 70 | + * Absolute site origin (e.g. `https://example.com`) used to build |
| 71 | + * the alternate URLs. Falls back to the site settings URL; when |
| 72 | + * neither is available the result is empty, since hreflang |
| 73 | + * requires fully-qualified URLs. |
| 74 | + */ |
| 75 | + siteUrl?: string; |
| 76 | +} |
| 77 | + |
| 78 | +/** |
| 79 | + * Resolve hreflang alternates for a content entry. |
| 80 | + * |
| 81 | + * @example |
| 82 | + * ```astro |
| 83 | + * --- |
| 84 | + * import { getHreflangAlternates } from "emdash"; |
| 85 | + * |
| 86 | + * const alternates = await getHreflangAlternates("posts", entry.data.id, { |
| 87 | + * siteUrl: Astro.url.origin, |
| 88 | + * }); |
| 89 | + * --- |
| 90 | + * <head> |
| 91 | + * {alternates.map((a) => <link rel="alternate" hreflang={a.hreflang} href={a.href} />)} |
| 92 | + * </head> |
| 93 | + * ``` |
| 94 | + */ |
| 95 | +export async function getHreflangAlternates( |
| 96 | + collection: string, |
| 97 | + entryId: string, |
| 98 | + options: HreflangOptions = {}, |
| 99 | +): Promise<HreflangAlternate[]> { |
| 100 | + if (!isI18nEnabled()) return []; |
| 101 | + const key = `hreflang:${collection}:${entryId}:${options.siteUrl ?? ""}`; |
| 102 | + return requestCached(key, async () => { |
| 103 | + const { getDb } = await import("../loader.js"); |
| 104 | + const db = await getDb(); |
| 105 | + return getHreflangAlternatesWithDb(db, collection, entryId, options); |
| 106 | + }); |
| 107 | +} |
| 108 | + |
| 109 | +/** |
| 110 | + * Resolve hreflang alternates with an explicit db handle. |
| 111 | + * |
| 112 | + * @internal Use `getHreflangAlternates()` in templates. This variant is |
| 113 | + * for routes/components that already have a database handle. |
| 114 | + */ |
| 115 | +export async function getHreflangAlternatesWithDb( |
| 116 | + db: Kysely<Database>, |
| 117 | + collection: string, |
| 118 | + entryId: string, |
| 119 | + options: HreflangOptions = {}, |
| 120 | +): Promise<HreflangAlternate[]> { |
| 121 | + if (!isI18nEnabled()) return []; |
| 122 | + |
| 123 | + let siteUrl = options.siteUrl; |
| 124 | + if (!siteUrl) { |
| 125 | + const settings = await getSiteSettingsWithDb(db); |
| 126 | + siteUrl = settings.url; |
| 127 | + } |
| 128 | + // hreflang requires fully-qualified URLs; a relative site URL would |
| 129 | + // produce invalid output (and EmDashHead's isSafeHref would drop it). |
| 130 | + if (!siteUrl || !ABSOLUTE_URL_RE.test(siteUrl)) return []; |
| 131 | + siteUrl = siteUrl.replace(TRAILING_SLASH_RE, ""); |
| 132 | + |
| 133 | + const repo = new ContentRepository(db); |
| 134 | + const item = await repo.findByIdOrSlug(collection, entryId); |
| 135 | + if (!item) return []; |
| 136 | + |
| 137 | + // Legacy rows imported before i18n may have no translation_group; |
| 138 | + // treat them as a single-variant group. |
| 139 | + const group = item.translationGroup || item.id; |
| 140 | + let variants = await repo.findTranslations(collection, group); |
| 141 | + if (variants.length === 0) variants = [item]; |
| 142 | + |
| 143 | + let published = variants.filter((v) => v.status === "published"); |
| 144 | + if (published.length === 0) return []; |
| 145 | + |
| 146 | + // Exclude noindex variants, matching the sitemap's `_emdash_seo` |
| 147 | + // filter so head and sitemap agree on which variants are |
| 148 | + // discoverable. When the requested entry itself is noindex, emit |
| 149 | + // nothing: a page opting out of indexing shouldn't announce an |
| 150 | + // hreflang set. |
| 151 | + const noindexIds = await findNoindexIds( |
| 152 | + db, |
| 153 | + collection, |
| 154 | + published.map((v) => v.id), |
| 155 | + ); |
| 156 | + if (noindexIds.has(item.id)) return []; |
| 157 | + published = published.filter((v) => !noindexIds.has(v.id)); |
| 158 | + |
| 159 | + const info = await getCollectionInfoWithDb(db, collection); |
| 160 | + const urlPattern = info?.urlPattern ?? null; |
| 161 | + |
| 162 | + const resolved: Array<{ locale: string; href: string }> = []; |
| 163 | + for (const variant of published) { |
| 164 | + const locale = variant.locale || "en"; |
| 165 | + const path = interpolateUrlPattern({ |
| 166 | + pattern: urlPattern, |
| 167 | + collection, |
| 168 | + slug: variant.slug || variant.id, |
| 169 | + id: variant.id, |
| 170 | + }); |
| 171 | + const localized = await localizePath(path, locale); |
| 172 | + if (localized === null) continue; |
| 173 | + resolved.push({ locale, href: `${siteUrl}${localized}` }); |
| 174 | + } |
| 175 | + if (resolved.length === 0) return []; |
| 176 | + |
| 177 | + resolved.sort((a, b) => a.locale.localeCompare(b.locale)); |
| 178 | + const alternates: HreflangAlternate[] = resolved.map((r) => ({ |
| 179 | + hreflang: r.locale, |
| 180 | + href: r.href, |
| 181 | + })); |
| 182 | + |
| 183 | + // x-default: default-locale variant, else the first routable one. |
| 184 | + // Same fallback the sitemap route uses. |
| 185 | + const defaultLocale = getI18nConfig()?.defaultLocale; |
| 186 | + const xDefault = resolved.find((r) => r.locale === defaultLocale) ?? resolved[0]; |
| 187 | + if (xDefault) { |
| 188 | + alternates.push({ hreflang: "x-default", href: xDefault.href }); |
| 189 | + } |
| 190 | + |
| 191 | + return alternates; |
| 192 | +} |
0 commit comments