aboutsummaryrefslogtreecommitdiffhomepage
path: root/scripts/indexnow.mjs
blob: 25bc7681ace34616345d83947de512e4092d9a97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// IndexNow: URL を検索エンジン(Bing・Yandex・Seznam・Naver 等)へ即時通知する。
//
// 使い方(デプロイしてキーファイルが公開された状態で実行する):
//   1) サイトマップの全URLを送る:   npm run indexnow
//   2) 特定URLだけ送る:             node scripts/indexnow.mjs https://yasutakeyohei.com/foo/ ...
//
// 仕様: https://www.indexnow.org/documentation
// キーは public/<key>.txt(名前=中身)として公開する。
import { readFileSync, readdirSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const HOST = "yasutakeyohei.com";
const KEY_RE = /^[A-Za-z0-9-]{8,128}$/;

// public/ から IndexNow キーファイル(ファイル名=中身の .txt)を探す。
function findKey() {
  if (process.env.INDEXNOW_KEY) return process.env.INDEXNOW_KEY;
  for (const name of readdirSync(join(root, "public"))) {
    if (!name.endsWith(".txt")) continue;
    const stem = name.slice(0, -4);
    if (!KEY_RE.test(stem)) continue;
    if (readFileSync(join(root, "public", name), "utf-8").trim() === stem) {
      return stem;
    }
  }
  throw new Error("IndexNow キーファイル(public/<key>.txt)が見つかりません");
}

// 送るURLを集める(引数があればそれ、無ければ dist のサイトマップ)。
function collectUrls() {
  const args = process.argv.slice(2).filter((a) => a.startsWith("http"));
  if (args.length) return args;
  const dir = join(root, "dist");
  const urls = [];
  for (const name of readdirSync(dir)) {
    if (!/^sitemap.*\.xml$/.test(name) || name === "sitemap-index.xml") continue;
    const xml = readFileSync(join(dir, name), "utf-8");
    for (const m of xml.matchAll(/<loc>([^<]+)<\/loc>/g)) urls.push(m[1].trim());
  }
  return urls;
}

async function submit(endpoint, key, urls) {
  const res = await fetch(endpoint, {
    method: "POST",
    headers: { "Content-Type": "application/json; charset=utf-8" },
    body: JSON.stringify({
      host: HOST,
      key,
      keyLocation: `https://${HOST}/${key}.txt`,
      urlList: urls,
    }),
  });
  return `${endpoint} -> ${res.status} ${res.statusText}`;
}

const key = findKey();
const urls = collectUrls();
console.log(`IndexNow: key=${key} / urls=${urls.length}`);
for (const ep of [
  "https://api.indexnow.org/indexnow",
  "https://www.bing.com/indexnow",
]) {
  try {
    console.log(" ", await submit(ep, key, urls));
  } catch (e) {
    console.error(` ${ep} FAILED:`, e.message);
  }
}