|
| 1 | +import { readFileSync, writeFileSync } from 'node:fs'; |
| 2 | +import { dirname, join, relative } from 'node:path'; |
| 3 | +import { findHtmlFiles } from './build.utils.mjs'; |
| 4 | + |
| 5 | +const OUTPUT_DIR = join(process.cwd(), 'build'); |
| 6 | +const SITE_ROOT_CANONICAL = 'https://console.juno.build'; |
| 7 | + |
| 8 | +const updateCanonical = (htmlFilePath) => { |
| 9 | + // 1. We determine the route based on the output |
| 10 | + const routePath = dirname(relative(OUTPUT_DIR, htmlFilePath)); |
| 11 | + |
| 12 | + // 2. Build the effective canonical route |
| 13 | + const canonicalPath = `${SITE_ROOT_CANONICAL}/${routePath}/`; |
| 14 | + |
| 15 | + // 2. Read content |
| 16 | + let html = readFileSync(htmlFilePath, 'utf-8'); |
| 17 | + |
| 18 | + // 3. Update canonical |
| 19 | + html = html.replace( |
| 20 | + `<link href="${SITE_ROOT_CANONICAL}" rel="canonical" />`, |
| 21 | + `<link href="${canonicalPath}" rel="canonical" />` |
| 22 | + ); |
| 23 | + |
| 24 | + // 4. Update og:url to reflect the canonical |
| 25 | + html = html.replace( |
| 26 | + `<meta content="${SITE_ROOT_CANONICAL}" property="og:url" />`, |
| 27 | + `<meta content="${canonicalPath}" property="og:url" />` |
| 28 | + ); |
| 29 | + |
| 30 | + // 5. Save the content with the updated canonical URL |
| 31 | + writeFileSync(htmlFilePath, html); |
| 32 | +}; |
| 33 | + |
| 34 | +// Do not replace canonical for root and 404 pages |
| 35 | +const filterSubPages = (htmlFile) => dirname(htmlFile) !== OUTPUT_DIR; |
| 36 | + |
| 37 | +const htmlFiles = findHtmlFiles().filter(filterSubPages); |
| 38 | +htmlFiles.forEach((htmlFile) => updateCanonical(htmlFile)); |
0 commit comments