Branchwell

Graphley / website / tools / indexnow.mjs

1#!/usr/bin/env node
2// Tells IndexNow which pages changed in this deploy, so Bing (and the assistants that
3// search through it, such as Copilot and ChatGPT) re-read them within minutes instead of days.
4//
5// It runs at the end of a Cloudflare Pages build. For every URL in the built sitemap it compares the
6// page's words (title, description, structured data and visible text) with the page that is
7// live right now, and submits only the pages that differ, plus pages that were added or removed.
8// With --lastmod it also writes <lastmod> into the built sitemap: today for a changed page,
9// otherwise the date the live sitemap (or the committed one) already shows.
10//
11// Production deploys submit. Preview deploys only print what they would submit.
12// Local builds do nothing. It never fails a build.
13//
14// Usage: node indexnow.mjs <built sitemap> <built html dir> [more dirs...] [--lastmod]
15// The key below is public by design: IndexNow checks it against /<key>.txt on the site.
16import { existsSync, readFileSync, writeFileSync } from 'node:fs';
17import { join } from 'node:path';
18
19const KEY = '66365049776433ceca35572e03fca658';
20const ENDPOINT = process.env.INDEXNOW_ENDPOINT || 'https://api.indexnow.org/indexnow';
21const mode = process.env.VERCEL_ENV || (process.env.CF_PAGES ? (process.env.CF_PAGES_BRANCH === 'main' ? 'production' : 'preview') : undefined); // production | preview | undefined (local)
22
23const args = process.argv.slice(2);
24const withLastmod = args.includes('--lastmod');
25const [sitemapFile, ...dirs] = args.filter((arg) => arg !== '--lastmod');
26
27const locs = (xml) => [...xml.matchAll(/<url>([\s\S]*?)<\/url>/g)].map(([, entry]) => ({
28 loc: (entry.match(/<loc>\s*([^<\s]+)\s*<\/loc>/) || [])[1],
29 lastmod: (entry.match(/<lastmod>\s*([^<\s]+)\s*<\/lastmod>/) || [])[1],
30})).filter((entry) => entry.loc);
31
32// What a page says, without markup, scripts or asset file names, so a rebuild alone is not a change.
33// The robots tag is left out: preview builds set noindex, and a noindex page is not in the sitemap anyway.
34export const words = (html) => {
35 const title = (html.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || '';
36 const meta = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag)
37 .filter((tag) => /(?:name|property)=["'](?:description|og:title|og:description)["']/i.test(tag))
38 .map((tag) => (tag.match(/content=(?:"([^"]*)"|'([^']*)')/i) || []).slice(1).find(Boolean) || '');
39 const data = [...html.matchAll(/<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)].map(([, json]) => json);
40 const text = html
41 .replace(/<(script|style|noscript|template)\b[\s\S]*?<\/\1>/gi, ' ')
42 .replace(/<!--[\s\S]*?-->/g, ' ')
43 .replace(/<[^>]+>/g, ' ');
44 return [title, ...meta, ...data, text].join(' ').replace(/&nbsp;|&#160;/g, ' ').replace(/\s+/g, ' ').trim();
45};
46
47const builtPage = (url) => {
48 const path = decodeURIComponent(new URL(url).pathname).replace(/\/+$/, '');
49 for (const dir of dirs) {
50 for (const file of path ? [`${path}.html`, `${path}/index.html`] : ['/index.html']) {
51 if (existsSync(join(dir, file))) return readFileSync(join(dir, file), 'utf8');
52 }
53 }
54 return null;
55};
56
57const get = async (url) => {
58 const target = process.env.INDEXNOW_TEST_ORIGIN ? url.replace(/^https?:\/\/[^/]+/, process.env.INDEXNOW_TEST_ORIGIN) : url;
59 const response = await fetch(target, { signal: AbortSignal.timeout(10000), headers: { 'user-agent': 'indexnow-build-check' } });
60 return { status: response.status, body: response.status === 200 ? await response.text() : '' };
61};
62
63async function main() {
64 if (!mode || !sitemapFile || !existsSync(sitemapFile)) return;
65 const xml = readFileSync(sitemapFile, 'utf8');
66 const pages = locs(xml);
67 if (!pages.length) return;
68 const origin = new URL(pages[0].loc).origin;
69
70 const liveSitemap = await get(`${origin}/sitemap.xml`).catch(() => ({ status: 0, body: '' }));
71 const live = new Map(locs(liveSitemap.body).map((entry) => [entry.loc, entry.lastmod]));
72
73 const changed = [];
74 const skipped = [];
75 for (let start = 0; start < pages.length; start += 8) {
76 await Promise.all(pages.slice(start, start + 8).map(async ({ loc }) => {
77 const built = builtPage(loc);
78 if (built === null) return skipped.push(`${loc} (not built as a file)`);
79 const now = await get(loc).catch(() => null);
80 if (now && now.status === 404) return changed.push(loc); // new page
81 if (!now || now.status !== 200) return skipped.push(`${loc} (live page did not load)`);
82 if (words(built) !== words(now.body)) changed.push(loc);
83 }));
84 }
85 // A page that left the sitemap is submitted too, so it drops out of the index.
86 const removed = liveSitemap.status === 200 ? [...live.keys()].filter((loc) => !pages.some((page) => page.loc === loc)) : [];
87
88 if (withLastmod) {
89 const today = new Date().toISOString().slice(0, 10);
90 const dated = xml.replace(/<url>([\s\S]*?)<\/url>/g, (entry, inner) => {
91 const loc = (inner.match(/<loc>\s*([^<\s]+)\s*<\/loc>/) || [])[1];
92 const committed = (inner.match(/<lastmod>\s*([^<\s]+)\s*<\/lastmod>/) || [])[1];
93 const date = changed.includes(loc) ? today : live.get(loc) || committed;
94 const bare = inner.replace(/\s*<lastmod>[\s\S]*?<\/lastmod>/, '');
95 return `<url>${date ? bare.replace(/<\/loc>/, `</loc><lastmod>${date}</lastmod>`) : bare}</url>`;
96 });
97 writeFileSync(sitemapFile, dated);
98 }
99
100 const urlList = [...changed, ...removed];
101 for (const note of skipped) console.log(`IndexNow: skipped ${note}`);
102 if (!urlList.length) return console.log(`IndexNow: no page changed (${pages.length} checked).`);
103 console.log(`IndexNow: ${urlList.length} of ${pages.length} page(s) changed:\n ${urlList.join('\n ')}`);
104 if (mode !== 'production') return console.log('IndexNow: preview build, nothing submitted.');
105
106 const host = new URL(origin).host;
107 const response = await fetch(ENDPOINT, {
108 method: 'POST',
109 signal: AbortSignal.timeout(10000),
110 headers: { 'content-type': 'application/json; charset=utf-8' },
111 body: JSON.stringify({ host, key: KEY, keyLocation: `${origin}/${KEY}.txt`, urlList }),
112 });
113 console.log(`IndexNow: submitted, HTTP ${response.status}.`);
114}
115
116main().catch((error) => console.log(`IndexNow: skipped (${error.message}).`));