diff --git a/scripts/postbuild.mjs b/scripts/postbuild.mjs index 22d463a..6fefb38 100644 --- a/scripts/postbuild.mjs +++ b/scripts/postbuild.mjs @@ -1,7 +1,7 @@ // Assembles the site root after "docusaurus build". // Every locale is built into its own build// directory (see i18n.localeConfigs in // docusaurus.config.ts), so files that must live in the site root are placed here. -import {cpSync, copyFileSync, existsSync, readdirSync, readFileSync, writeFileSync} from 'node:fs'; +import {cpSync, copyFileSync, existsSync, readdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'; import {dirname, join} from 'node:path'; import {fileURLToPath} from 'node:url'; @@ -87,10 +87,44 @@ ${locales.map(({prefix, lang}) => `
  • [{prefix, lang, loc}] +for (const {prefix, lang} of locales) { + const sitemapPath = join(buildDir, prefix, 'sitemap.xml'); + if (!existsSync(sitemapPath)) { + continue; + } + + for (const [, loc] of readFileSync(sitemapPath, 'utf8').matchAll(/([^<]+)<\/loc>/g)) { + const path = loc.slice(`${SITE_URL}/${prefix}`.length) || '/'; + pages.set(path, [...(pages.get(path) ?? []), {prefix, lang, loc}]); + } + + rmSync(sitemapPath); +} + +const sitemapUrls = [...pages.values()].flatMap((translations) => translations.map(({loc}) => [ + ' ', + ` ${loc}`, + ...translations.map((alternate) => ` `), + ...translations.filter(({prefix}) => prefix === DEFAULT_PREFIX).map((alternate) => ` `), + ' ', +].join('\n'))); + +// The locale sitemaps are removed after merging, so don't overwrite the result when the script runs again +if (pages.size > 0) { + writeFileSync(join(buildDir, 'sitemap.xml'), ` + +${sitemapUrls.join('\n')} + +`); +} + writeFileSync(join(buildDir, 'robots.txt'), `User-agent: * Allow: / -${locales.filter(({prefix}) => existsSync(join(buildDir, prefix, 'sitemap.xml'))).map(({prefix}) => `Sitemap: ${SITE_URL}/${prefix}/sitemap.xml`).join('\n')} +Sitemap: ${SITE_URL}/sitemap.xml `); console.log(`[postbuild] Site root assembled for locales: ${locales.map(({prefix}) => prefix).join(', ')}`);