|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * Ensures every documentation page includes the shared site analytics partial. |
| 4 | + * |
| 5 | + * This idempotent pass recursively covers new HTML pages added under web/docs, |
| 6 | + * so authors do not have to copy the analytics block page by page. |
| 7 | + */ |
| 8 | + |
| 9 | +import { readdir, readFile, writeFile } from 'node:fs/promises'; |
| 10 | +import path from 'node:path'; |
| 11 | +import { fileURLToPath } from 'node:url'; |
| 12 | +import { PLAUSIBLE_SCRIPT_URL, withPlausibleAnalytics } from '../web/build/plausible.mjs'; |
| 13 | + |
| 14 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 15 | +const REPO_ROOT = path.resolve(__dirname, '..'); |
| 16 | +const DOCS_DIR = path.join(REPO_ROOT, 'web', 'docs'); |
| 17 | + |
| 18 | +async function listHtmlFiles(dir) { |
| 19 | + const files = []; |
| 20 | + for (const entry of await readdir(dir, { withFileTypes: true })) { |
| 21 | + const fullPath = path.join(dir, entry.name); |
| 22 | + if (entry.isDirectory()) files.push(...await listHtmlFiles(fullPath)); |
| 23 | + else if (entry.isFile() && entry.name.endsWith('.html')) files.push(fullPath); |
| 24 | + } |
| 25 | + return files.sort(); |
| 26 | +} |
| 27 | + |
| 28 | +async function main() { |
| 29 | + const files = await listHtmlFiles(DOCS_DIR); |
| 30 | + for (const file of files) { |
| 31 | + const original = await readFile(file, 'utf8'); |
| 32 | + const generated = withPlausibleAnalytics(original); |
| 33 | + const occurrences = generated.split(PLAUSIBLE_SCRIPT_URL).length - 1; |
| 34 | + if (occurrences !== 1) { |
| 35 | + throw new Error(`${path.relative(REPO_ROOT, file)} contains ${occurrences} Plausible scripts`); |
| 36 | + } |
| 37 | + if (generated !== original) await writeFile(file, generated, 'utf8'); |
| 38 | + console.log(`wrote ${path.relative(process.cwd(), file)}`); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +main().catch((error) => { |
| 43 | + console.error(error); |
| 44 | + process.exit(1); |
| 45 | +}); |
0 commit comments