Branchwell

AI Resource Pro / website / scripts / 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 Vercel 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 cloudflareBranch = process.env.WORKERS_CI_BRANCH ?? process.env.CF_PAGES_BRANCH;
22const mode = process.env.VERCEL_ENV ?? (cloudflareBranch === 'main' ? 'production' : undefined);
23
24const args = process.argv.slice(2);
25const withLastmod = args.includes('--lastmod');
26const [sitemapFile, ...dirs] = args.filter((arg) => arg !== '--lastmod');
27
28const locs = (xml) => [...xml.matchAll(/<url>([\s\S]*?)<\/url>/g)].map(([, entry]) => ({
29 loc: (entry.match(/<loc>\s*([^<\s]+)\s*<\/loc>/) || [])[1],
30 lastmod: (entry.match(/<lastmod>\s*([^<\s]+)\s*<\/lastmod>/) || [])[1],
31})).filter((entry) => entry.loc);
32
33// What a page says, without markup, scripts or asset file names, so a rebuild alone is not a change.
34// The robots tag is left out: preview builds set noindex, and a noindex page is not in the sitemap anyway.
35export const words = (html) => {
36 const title = (html.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || '';
37 const meta = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag)
38 .filter((tag) => /(?:name|property)=["'](?:description|og:title|og:description)["']/i.test(tag))
39 .map((tag) => (tag.match(/content=(?:"([^"]*)"|'([^']*)')/i) || []).slice(1).find(Boolean) || '');
40 const data = [...html.matchAll(/<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)].map(([, json]) => json);
41 const text = html
42 .replace(/<(script|style|noscript|template)\b[\s\S]*?<\/\1>/gi, ' ')
43 .replace(/<!--[\s\S]*?-->/g, ' ')
44 .replace(/<[^>]+>/g, ' ');
45 return [title, ...meta, ...data, text].join(' ').replace(/&nbsp;|&#160;/g, ' ').replace(/\s+/g, ' ').trim();
46};
47
48const builtPage = (url) => {
49 const path = decodeURIComponent(new URL(url).pathname).replace(/\/+$/, '');
50 for (const dir of dirs) {
51 for (const file of path ? [`${path}.html`, `${path}/index.html`] : ['/index.html']) {
52 if (existsSync(join(dir, file))) return readFileSync(join(dir, file), 'utf8');
53 }
54 }
55 return null;
56};
57
58const get = async (url) => {
59 const target = process.env.INDEXNOW_TEST_ORIGIN ? url.replace(/^https?:\/\/[^/]+/, process.env.INDEXNOW_TEST_ORIGIN) : url;
60 const response = await fetch(target, { signal: AbortSignal.timeout(10000), headers: { 'user-agent': 'indexnow-build-check' } });
61 return { status: response.status, body: response.status === 200 ? await response.text() : '' };
62};
63
64async function main() {
65 if (!mode || !sitemapFile || !existsSync(sitemapFile)) return;
66 const xml = readFileSync(sitemapFile, 'utf8');
67 const pages = locs(xml);
68 if (!pages.length) return;
69 const origin = new URL(pages[0].loc).origin;
70
71 const liveSitemap = await get(`${origin}/sitemap.xml`).catch(() => ({ status: 0, body: '' }));
72 const live = new Map(locs(liveSitemap.body).map((entry) => [entry.loc, entry.lastmod]));
73
74 const changed = [];
75 const skipped = [];
76 for (let start = 0; start < pages.length; start += 8) {
77 await Promise.all(pages.slice(start, start + 8).map(async ({ loc }) => {
78 const built = builtPage(loc);
79 if (built === null) return skipped.push(`${loc} (not built as a file)`);
80 const now = await get(loc).catch(() => null);
81 if (now && now.status === 404) return changed.push(loc); // new page
82 if (!now || now.status !== 200) return skipped.push(`${loc} (live page did not load)`);
83 if (words(built) !== words(now.body)) changed.push(loc);
84 }));
85 }
86 // A page that left the sitemap is submitted too, so it drops out of the index.
87 const removed = liveSitemap.status === 200 ? [...live.keys()].filter((loc) => !pages.some((page) => page.loc === loc)) : [];
88
89 if (withLastmod) {
90 const today = new Date().toISOString().slice(0, 10);
91 const dated = xml.replace(/<url>([\s\S]*?)<\/url>/g, (entry, inner) => {
92 const loc = (inner.match(/<loc>\s*([^<\s]+)\s*<\/loc>/) || [])[1];
93 const committed = (inner.match(/<lastmod>\s*([^<\s]+)\s*<\/lastmod>/) || [])[1];
94 const date = changed.includes(loc) ? today : live.get(loc) || committed;
95 const bare = inner.replace(/\s*<lastmod>[\s\S]*?<\/lastmod>/, '');
96 return `<url>${date ? bare.replace(/<\/loc>/, `</loc><lastmod>${date}</lastmod>`) : bare}</url>`;
97 });
98 writeFileSync(sitemapFile, dated);
99 }
100
101 const urlList = [...changed, ...removed];
102 for (const note of skipped) console.log(`IndexNow: skipped ${note}`);
103 if (!urlList.length) return console.log(`IndexNow: no page changed (${pages.length} checked).`);
104 console.log(`IndexNow: ${urlList.length} of ${pages.length} page(s) changed:\n ${urlList.join('\n ')}`);
105 if (mode !== 'production') return console.log('IndexNow: preview build, nothing submitted.');
106
107 const host = new URL(origin).host;
108 const response = await fetch(ENDPOINT, {
109 method: 'POST',
110 signal: AbortSignal.timeout(10000),
111 headers: { 'content-type': 'application/json; charset=utf-8' },
112 body: JSON.stringify({ host, key: KEY, keyLocation: `${origin}/${KEY}.txt`, urlList }),
113 });
114 console.log(`IndexNow: submitted, HTTP ${response.status}.`);
115}
116
117main().catch((error) => console.log(`IndexNow: skipped (${error.message}).`));