|
| 1 | +import type {AstroIntegration} from 'astro'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Validates that for every page under pathA there is a corresponding page under pathB and vice versa. |
| 5 | + */ |
| 6 | +export default function equalPageNameValidator(pathA: string, pathB: string): AstroIntegration { |
| 7 | + if (!pathA || !pathB) { |
| 8 | + throw new Error('Both paths must be provided'); |
| 9 | + } |
| 10 | + if (pathA === pathB) { |
| 11 | + throw new Error('The two paths must be different'); |
| 12 | + } |
| 13 | + |
| 14 | + // Canonicalize paths to always end with a slash |
| 15 | + if (!pathA.endsWith('/')) { |
| 16 | + pathA += '/'; |
| 17 | + } |
| 18 | + if (!pathB.endsWith('/')) { |
| 19 | + pathB += '/'; |
| 20 | + } |
| 21 | + |
| 22 | + return { |
| 23 | + name: 'equal-page-name-validator', |
| 24 | + hooks: { |
| 25 | + 'astro:build:done': ({logger, dir, pages}) => { |
| 26 | + logger.info(`Validating equal page names between ${pathA} and ${pathB}…`); |
| 27 | + |
| 28 | + const aPages = new Set<string>(); |
| 29 | + const bPages = new Set<string>(); |
| 30 | + |
| 31 | + for (const page of pages) { |
| 32 | + if (page.pathname.startsWith(pathA)) { |
| 33 | + aPages.add(page.pathname.substring(pathA.length)); |
| 34 | + } else if (page.pathname.startsWith(pathB)) { |
| 35 | + bPages.add(page.pathname.substring(pathB.length)); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + if (aPages.size === 0) { |
| 40 | + logger.warn(`No pages found for path A: ${pathA}`); |
| 41 | + } |
| 42 | + if (bPages.size === 0) { |
| 43 | + logger.warn(`No pages found for path B: ${pathB}`); |
| 44 | + } |
| 45 | + |
| 46 | + const difference = aPages.difference(bPages); |
| 47 | + const reverseDifference = bPages.difference(aPages); |
| 48 | + const totalDifferences = difference.size + reverseDifference.size; |
| 49 | + if (totalDifferences > 0) { |
| 50 | + logger.error(`Found ${totalDifferences} page(s) that do not have a counterpart:`); |
| 51 | + for (const page of difference) { |
| 52 | + logger.error(` - ${pathA}${page}`); |
| 53 | + } |
| 54 | + for (const page of reverseDifference) { |
| 55 | + logger.error(` - ${pathB}${page}`); |
| 56 | + } |
| 57 | + throw new Error(`Validation failed: ${totalDifferences} page(s) do not have a counterpart.`); |
| 58 | + } |
| 59 | + |
| 60 | + logger.info(`All ${aPages.size} page(s) in ${pathA} have a counterpart in ${pathB} and vice versa.`); |
| 61 | + }, |
| 62 | + }, |
| 63 | + }; |
| 64 | +} |
0 commit comments