@mannisto/astro-metadata 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -67,7 +67,7 @@ Set `site` in the Astro config. The canonical URL and the social images must be
67
67
  | `twitter` | — | `site`: the Twitter (X) handle of the site. `card`: `"summary"` or `"summary_large_image"` (default) for pages with an image. |
68
68
  | `themeColor` | — | The color of the browser interface. Give one color, or `{ light, dark }`. |
69
69
  | `feeds` | — | The RSS, Atom or JSON feeds: `href`, `title` and `type` (`"rss"` by default). |
70
- | `robots` | — | `index: false` or `follow: false` for all pages, for example on a staging site. `extra`: other directives, for example `"max-image-preview:large"`. |
70
+ | `robots` | — | `index: false` or `follow: false` for all pages, for example on a staging site. `extra`: other directives of the robots meta tag, for example `"max-image-preview:large"`. They do not go into `robots.txt`. `ai`: generates `robots.txt` for the AI crawlers. See [AI crawlers](#ai-crawlers). |
71
71
  | `favicon` | — | Generates the favicons from one image. See [Favicons](#favicons). |
72
72
  | `manifest` | — | Generates the web app manifest, or links your own. See [Web app manifest](#web-app-manifest). |
73
73
  | `schema` | — | The structured data of the site: `publisher` is the organization or the person behind the site. `false` turns it off. See [Structured data](#structured-data). |
@@ -367,6 +367,51 @@ export const GET = () => {
367
367
  }
368
368
  ```
369
369
 
370
+ ## AI crawlers
371
+
372
+ The `robots.ai` option generates `robots.txt`. It tells the AI crawlers what they can do on the site:
373
+
374
+ ```typescript
375
+ metadata({
376
+ robots: {
377
+ ai: {
378
+ search: true,
379
+ training: false,
380
+ },
381
+ },
382
+ })
383
+ ```
384
+
385
+ | Option | Default | Description |
386
+ |---|---|---|
387
+ | `search` | `true` | `false` blocks the crawlers of AI search, for example `OAI-SearchBot` and `Claude-SearchBot`, and the crawlers that load a page for a user, for example `ChatGPT-User`. The site then does not show in their answers. |
388
+ | `training` | `true` | `false` blocks the crawlers of AI training, for example `GPTBot`, `ClaudeBot` and `Google-Extended`. |
389
+
390
+ With `training: false`, the file also blocks all other AI crawlers of the [ai.robots.txt](https://github.com/ai-robots-txt/ai.robots.txt) list. The list has more than 200 crawlers, and the package gets the new names each month. The file never blocks `Applebot` and `facebookexternalhit`, because Apple search and the Facebook link previews use them.
391
+
392
+ With [`@astrojs/sitemap`](https://docs.astro.build/en/guides/integrations-guide/sitemap/), the file also links the sitemap:
393
+
394
+ ```
395
+ User-agent: GPTBot
396
+ User-agent: ClaudeBot
397
+ User-agent: Google-Extended
398
+ ...
399
+ Disallow: /
400
+
401
+ User-agent: *
402
+ Allow: /
403
+
404
+ Sitemap: https://example.com/sitemap-index.xml
405
+ ```
406
+
407
+ Good to know:
408
+
409
+ - **Google.** Google AI Overviews and Google Search use the same crawler, `Googlebot`. You can not block AI Overviews and keep Google Search. `Google-Extended` controls only Gemini and Vertex AI.
410
+ - **A request, not a block.** Some crawlers do not obey `robots.txt`.
411
+ - **`index: false`.** It changes only the robots meta tag, and not `robots.txt`. A crawler that `robots.txt` blocks can not see the `noindex` tag, so the page can still show in search results.
412
+ - **Your own `robots.txt`.** A `public/robots.txt` or a `src/pages/robots.txt.ts` endpoint replaces the generated file. The integration shows a warning.
413
+ - **A `base`.** Crawlers read `robots.txt` only at the root of the domain. With a `base`, the integration shows a warning.
414
+
370
415
  ## Structured data
371
416
 
372
417
  `<Metadata>` renders the structured data (JSON-LD) of each page by itself. You only give the values of the page.
@@ -460,7 +505,7 @@ The dev toolbar app checks the current page. The build checks all prerendered pa
460
505
  | Level | Description | Examples |
461
506
  | --- | --- | --- |
462
507
  | Error | The metadata is broken. | No title, placeholder text such as `undefined`, invalid JSON-LD, an `og:image` that does not load |
463
- | Warning | Fix it for better results. | A long title, the same title on two pages, an `og:image` over 600 KB |
508
+ | Warning | Fix it for better results. | A long title, the same title on two pages, a canonical URL to another page, an `og:image` over 600 KB |
464
509
  | Info | Good to know. | `noindex`, a short description, no `og:image:alt` |
465
510
 
466
511
  To turn off the checks, use `debug`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mannisto/astro-metadata",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Metadata for Astro: page tags, social cards, favicons, the web app manifest, structured data and a dev toolbar app that checks your pages.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -36,7 +36,8 @@
36
36
  "test": "pnpm run test:unit && pnpm run test:e2e",
37
37
  "test:unit": "vitest run",
38
38
  "test:e2e": "pnpm test:fixtures && playwright test",
39
- "test:fixtures": "pnpm --filter \"./tests/e2e/fixtures/**\" exec astro build"
39
+ "test:fixtures": "pnpm --filter \"./tests/e2e/fixtures/**\" exec astro build",
40
+ "bots:update": "node scripts/update-ai-bots.mjs"
40
41
  },
41
42
  "peerDependencies": {
42
43
  "astro": "^6.4.6 || ^7.0.0"
@@ -44,17 +45,17 @@
44
45
  "devDependencies": {
45
46
  "@eslint/js": "^10.0.1",
46
47
  "@ianvs/prettier-plugin-sort-imports": "^4.7.1",
47
- "@playwright/test": "^1.64.1",
48
- "@types/node": "^22.20.5",
49
- "astro": "^7.4.2",
50
- "eslint": "^10.13.0",
48
+ "@playwright/test": "^1.65.1",
49
+ "@types/node": "^22.20.7",
50
+ "astro": "^7.4.13",
51
+ "eslint": "^10.15.0",
51
52
  "eslint-config-prettier": "^10.1.8",
52
- "prettier": "^3.9.10",
53
- "prettier-plugin-astro": "^0.14.1",
53
+ "prettier": "^3.10.1",
54
+ "prettier-plugin-astro": "^1.1.2",
54
55
  "sharp": "^0.35.5",
55
- "typescript": "^5.9.3",
56
- "typescript-eslint": "^8.72.1",
57
- "vitest": "^4.1.12"
56
+ "typescript": "^6.0.3",
57
+ "typescript-eslint": "^8.74.0",
58
+ "vitest": "^5.1.2"
58
59
  },
59
60
  "packageManager": "pnpm@10.32.1",
60
61
  "dependencies": {
@@ -2,8 +2,6 @@
2
2
  import { Favicon } from "../lib/favicon.ts"
3
3
  ---
4
4
 
5
- {
6
- Favicon.links().map((link) => {
7
- return <link rel={link.rel} type={link.type} href={link.href} sizes={link.sizes} />
8
- })
9
- }
5
+ {Favicon.links().map((link) => {
6
+ return <link rel={link.rel} type={link.type} href={link.href} sizes={link.sizes} />
7
+ })}
@@ -15,15 +15,13 @@ const FEED_TYPES = {
15
15
  }
16
16
  ---
17
17
 
18
- {
19
- getConfig().feeds?.map((feed) => {
20
- return (
21
- <link
22
- rel="alternate"
23
- type={FEED_TYPES[feed.type ?? "rss"]}
24
- title={localize(feed.title, locale)}
25
- href={withBase(feed.href)}
26
- />
27
- )
28
- })
29
- }
18
+ {getConfig().feeds?.map((feed) => {
19
+ return (
20
+ <link
21
+ rel="alternate"
22
+ type={FEED_TYPES[feed.type ?? "rss"]}
23
+ title={localize(feed.title, locale)}
24
+ href={withBase(feed.href)}
25
+ />
26
+ )
27
+ })}
@@ -6,8 +6,6 @@ import { pageUrl } from "../lib/url.ts"
6
6
  export type Props = Pick<MetadataProps, "hreflang">
7
7
  ---
8
8
 
9
- {
10
- pageHreflang(Astro, Astro.props).map((link) => {
11
- return <link rel="alternate" hreflang={link.hreflang} href={pageUrl(link.href)} />
12
- })
13
- }
9
+ {pageHreflang(Astro, Astro.props).map((link) => {
10
+ return <link rel="alternate" hreflang={link.hreflang} href={pageUrl(link.href)} />
11
+ })}
@@ -43,28 +43,20 @@ const title = props.title ?? siteName
43
43
  <meta property="og:type" content={props.type ?? "website"} />
44
44
  {siteName && <meta property="og:site_name" content={siteName} />}
45
45
  {locales.locale && <meta property="og:locale" content={locales.locale} />}
46
- {
47
- locales.alternates.map((alternate) => {
48
- return <meta property="og:locale:alternate" content={alternate} />
49
- })
50
- }
51
- {
52
- image && (
53
- <>
54
- <meta property="og:image" content={url(image.url)} />
55
- {image.alt && <meta property="og:image:alt" content={image.alt} />}
56
- {image.width && <meta property="og:image:width" content={String(image.width)} />}
57
- {image.height && <meta property="og:image:height" content={String(image.height)} />}
58
- </>
59
- )
60
- }
61
- {
62
- article && props.published && (
63
- <meta property="article:published_time" content={isoDate(props.published)} />
64
- )
65
- }
66
- {
67
- article && props.modified && (
68
- <meta property="article:modified_time" content={isoDate(props.modified)} />
69
- )
70
- }
46
+ {locales.alternates.map((alternate) => {
47
+ return <meta property="og:locale:alternate" content={alternate} />
48
+ })}
49
+ {image && (
50
+ <>
51
+ <meta property="og:image" content={url(image.url)} />
52
+ {image.alt && <meta property="og:image:alt" content={image.alt} />}
53
+ {image.width && <meta property="og:image:width" content={String(image.width)} />}
54
+ {image.height && <meta property="og:image:height" content={String(image.height)} />}
55
+ </>
56
+ )}
57
+ {article && props.published && (
58
+ <meta property="article:published_time" content={isoDate(props.published)} />
59
+ )}
60
+ {article && props.modified && (
61
+ <meta property="article:modified_time" content={isoDate(props.modified)} />
62
+ )}
@@ -5,11 +5,9 @@ const themeColor = getConfig().themeColor
5
5
  ---
6
6
 
7
7
  {typeof themeColor === "string" && <meta name="theme-color" content={themeColor} />}
8
- {
9
- typeof themeColor === "object" && (
10
- <>
11
- <meta name="theme-color" content={themeColor.light} media="(prefers-color-scheme: light)" />
12
- <meta name="theme-color" content={themeColor.dark} media="(prefers-color-scheme: dark)" />
13
- </>
14
- )
15
- }
8
+ {typeof themeColor === "object" && (
9
+ <>
10
+ <meta name="theme-color" content={themeColor.light} media="(prefers-color-scheme: light)" />
11
+ <meta name="theme-color" content={themeColor.dark} media="(prefers-color-scheme: dark)" />
12
+ </>
13
+ )}
@@ -294,6 +294,53 @@ const MIME_TYPES = {
294
294
  ".webp": "image/webp",
295
295
  }
296
296
 
297
+ /**
298
+ * Returns the path of your own `robots.txt` in the project: a file in `public/`, or an
299
+ * endpoint in `src/pages/`. Returns undefined without one.
300
+ *
301
+ * @param {import("astro").AstroConfig} config
302
+ * @returns {string | undefined} The path relative to the project root, e.g. "src/pages/robots.txt.ts".
303
+ */
304
+ function findOwnRobotsTxt(config) {
305
+ const root = fileURLToPath(config.root)
306
+ const publicFile = fileURLToPath(new URL("./robots.txt", config.publicDir))
307
+ if (fs.existsSync(publicFile)) return path.relative(root, publicFile)
308
+
309
+ const pagesDir = fileURLToPath(new URL("./pages/", config.srcDir))
310
+ if (!fs.existsSync(pagesDir)) return undefined
311
+ const endpoint = fs.readdirSync(pagesDir).find((file) => {
312
+ return /^robots\.txt\.(js|mjs|ts|mts)$/.test(file)
313
+ })
314
+ return endpoint ? path.relative(root, path.join(pagesDir, endpoint)) : undefined
315
+ }
316
+
317
+ /**
318
+ * Returns true when the integration can generate `robots.txt`, and warns when crawlers
319
+ * can not find the file: your own `robots.txt` replaces it, and with a `base`, it is not
320
+ * at the root of the domain.
321
+ *
322
+ * @param {import("astro").AstroConfig} config
323
+ * @param {import("astro").AstroIntegrationLogger} logger
324
+ * @returns {boolean} False with your own `robots.txt`.
325
+ */
326
+ function canGenerateRobotsTxt(config, logger) {
327
+ const own = findOwnRobotsTxt(config)
328
+ if (own) {
329
+ logger.warn(
330
+ `${own} replaces the generated robots.txt. Remove it to use the \`robots.ai\` option.`
331
+ )
332
+ return false
333
+ }
334
+
335
+ const base = config.base.replace(/\/$/, "")
336
+ if (base) {
337
+ logger.warn(
338
+ `The generated robots.txt is at ${base}/robots.txt. Crawlers read robots.txt only at the root of the domain.`
339
+ )
340
+ }
341
+ return true
342
+ }
343
+
297
344
  /**
298
345
  * Returns the debug features: the dev toolbar app (`client`) and the build checks (`build`).
299
346
  *
@@ -406,6 +453,20 @@ function pagePath(file) {
406
453
  return file.replace(/\.html$/, "")
407
454
  }
408
455
 
456
+ /**
457
+ * Returns the URL of a built HTML file, with the site and the base, e.g.
458
+ * "https://example.com/docs/blog/" for "/blog/index.html". Undefined without `site`.
459
+ *
460
+ * @param {string} file - The path of the file in the output directory.
461
+ * @param {import("./integration").BuildContext} context
462
+ * @returns {string | undefined}
463
+ */
464
+ function pageUrl(file, context) {
465
+ if (!context.site) return undefined
466
+ const base = context.base.replace(/\/$/, "")
467
+ return new URL(`${base}${pagePath(file)}`, context.site).href
468
+ }
469
+
409
470
  /**
410
471
  * Checks the metadata of the built pages and logs the errors and the warnings:
411
472
  * the head of each page, its files, and the pages of the site together.
@@ -427,7 +488,7 @@ async function checkPages(context, logger) {
427
488
  const page = `/${path.relative(context.dir, file).split(path.sep).join("/")}`
428
489
  if (isIgnored(pagePath(page), context.pages)) continue
429
490
 
430
- pages.push({ path: page, head: parseHead(html) })
491
+ pages.push({ path: page, head: parseHead(html), url: pageUrl(page, context) })
431
492
  }
432
493
 
433
494
  const siteChecks = checkSite(pages, options)
@@ -558,6 +619,9 @@ export default function metadata(options = {}) {
558
619
  base: config.base,
559
620
  trailingSlash: config.trailingSlash,
560
621
  buildFormat: config.build.format,
622
+ sitemap: config.integrations.some((integration) => {
623
+ return integration.name === "@astrojs/sitemap"
624
+ }),
561
625
  }
562
626
  for (const key of SITE_KEYS) {
563
627
  if (options[key] !== undefined) runtime[key] = options[key]
@@ -592,6 +656,14 @@ export default function metadata(options = {}) {
592
656
  })
593
657
  }
594
658
 
659
+ if (options.robots?.ai && canGenerateRobotsTxt(config, logger)) {
660
+ injectRoute({
661
+ pattern: "/robots.txt",
662
+ entrypoint: new URL("./routes/robots-txt.ts", import.meta.url),
663
+ prerender: true,
664
+ })
665
+ }
666
+
595
667
  if (favicon) {
596
668
  for (const file of favicon.files) {
597
669
  injectRoute({
@@ -0,0 +1,208 @@
1
+ [
2
+ "AddSearchBot",
3
+ "AgentDataBot",
4
+ "AgentTimes",
5
+ "AGI Agent",
6
+ "AI2Bot",
7
+ "AI2Bot-DeepResearchEval",
8
+ "Ai2Bot-Dolma",
9
+ "aiHitBot",
10
+ "AIWebIndex",
11
+ "amazon-kendra",
12
+ "amazon-QBusiness",
13
+ "Amazonbot",
14
+ "AmazonBuyForMe",
15
+ "Amzn-SearchBot",
16
+ "Amzn-User",
17
+ "Andibot",
18
+ "Anomura",
19
+ "anthropic-ai",
20
+ "ApifyBot",
21
+ "ApifyWebsiteContentCrawler",
22
+ "Applebot",
23
+ "Applebot-Extended",
24
+ "Aranet-SearchBot",
25
+ "atlassian-bot",
26
+ "Awario",
27
+ "AzureAI-SearchBot",
28
+ "bedrockbot",
29
+ "bigsur.ai",
30
+ "BixelBot",
31
+ "Bravebot",
32
+ "Brightbot",
33
+ "Brightbot 1.0",
34
+ "BuddyBot",
35
+ "Bytespider",
36
+ "CartAI Agentic Commerce",
37
+ "CCBot",
38
+ "Channel3Bot",
39
+ "ChatGLM-Spider",
40
+ "ChatGPT Agent",
41
+ "ChatGPT-User",
42
+ "Claude-Agent",
43
+ "Claude-Code",
44
+ "Claude-SearchBot",
45
+ "Claude-User",
46
+ "Claude-Web",
47
+ "ClaudeBot",
48
+ "CledaraBot",
49
+ "Cloudflare-AutoRAG",
50
+ "CloudflareBrowserRenderingCrawler",
51
+ "CloudVertexBot",
52
+ "Code",
53
+ "Codex",
54
+ "cohere-ai",
55
+ "cohere-training-data-crawler",
56
+ "Cotoyogi",
57
+ "CragCrawler",
58
+ "Crawl4AI",
59
+ "Crawlspace",
60
+ "Cursor",
61
+ "Datenbank Crawler",
62
+ "DeepSeekBot",
63
+ "Devin",
64
+ "Diffbot",
65
+ "Diffbot-User",
66
+ "Dot",
67
+ "DoubaoBot",
68
+ "DuckAssistBot",
69
+ "Echobot Bot",
70
+ "EchoboxBot",
71
+ "ElevenlabsBot",
72
+ "ElevenlabsCrawler",
73
+ "ERNIEBot",
74
+ "ExaBot",
75
+ "ExaSearchBot",
76
+ "ExaUser",
77
+ "FacebookBot",
78
+ "facebookexternalhit",
79
+ "Factset_spyderbot",
80
+ "FirecrawlAgent",
81
+ "FriendlyCrawler",
82
+ "GeistHaus-PageFetcher",
83
+ "Gemini-Deep-Research",
84
+ "GeneralRetrievalBot",
85
+ "Google-Agent",
86
+ "Google-CloudVertexBot",
87
+ "Google-Extended",
88
+ "Google-Firebase",
89
+ "Google-Gemini-CLI",
90
+ "Google-GeminiNotebook",
91
+ "Google-NotebookLM",
92
+ "GoogleAgent-Mariner",
93
+ "GoogleAgent-URLContext",
94
+ "GoogleOther",
95
+ "GoogleOther-Image",
96
+ "GoogleOther-Video",
97
+ "GPTBot",
98
+ "Grok Bot",
99
+ "GrokAppAndroid",
100
+ "GrokBot",
101
+ "Haiku-SearchBot",
102
+ "HarkBot",
103
+ "HatchFeed",
104
+ "HenkBot",
105
+ "Hunyuan",
106
+ "iAskBot",
107
+ "iaskspider",
108
+ "iaskspider/2.0",
109
+ "ICC-Crawler",
110
+ "ImagesiftBot",
111
+ "imageSpider",
112
+ "img2dataset",
113
+ "Instinct",
114
+ "ISSCyberRiskCrawler",
115
+ "kagi-fetcher",
116
+ "Kangaroo Bot",
117
+ "KeenableBot",
118
+ "Kimi-Agent",
119
+ "Kimi-SearchBot",
120
+ "Kimi-User",
121
+ "KimiBot",
122
+ "KlaviyoAIBot",
123
+ "KunatoCrawler",
124
+ "laion-huggingface-processor",
125
+ "LAIONDownloader",
126
+ "LCC",
127
+ "Lightpanda",
128
+ "Liner-User",
129
+ "LinerBot",
130
+ "Linguee Bot",
131
+ "LinkupBot",
132
+ "Manus-User",
133
+ "meta-externalagent",
134
+ "meta-externalfetcher",
135
+ "meta-webindexer",
136
+ "MiniMaxAgent",
137
+ "MistralAI-Index",
138
+ "MistralAI-Training",
139
+ "MistralAI-User",
140
+ "MistralAI-User/1.0",
141
+ "MoonshotBot",
142
+ "Mozilla-Tabstack",
143
+ "Muse",
144
+ "MyCentralAIScraperBot",
145
+ "NagetBot",
146
+ "nbot",
147
+ "netEstate Imprint Crawler",
148
+ "newsai",
149
+ "NotebookLM",
150
+ "NovaAct",
151
+ "OAI-AdsBot",
152
+ "OAI-SearchBot",
153
+ "omgili",
154
+ "omgilibot",
155
+ "OpenAI",
156
+ "opencode",
157
+ "Operator",
158
+ "PanguBot",
159
+ "Panscient",
160
+ "panscient.com",
161
+ "Payhawk Invoice Fetching Agent",
162
+ "Perplexity-User",
163
+ "PerplexityBot",
164
+ "PetalBot",
165
+ "PhindBot",
166
+ "Poggio-Citations",
167
+ "Poseidon Research Crawler",
168
+ "qodercli",
169
+ "QualifiedBot",
170
+ "Querit-SearchBot",
171
+ "QueritBot",
172
+ "QuillBot",
173
+ "quillbot.com",
174
+ "QwenBot",
175
+ "Reflectionbot",
176
+ "SBIntuitionsBot",
177
+ "Scrapy",
178
+ "ScryBot",
179
+ "SemrushBot-OCOB",
180
+ "SemrushBot-SWA",
181
+ "Shap-User",
182
+ "ShapBot",
183
+ "Sidetrade indexer bot",
184
+ "Spider",
185
+ "TavilyBot",
186
+ "Terra Cotta",
187
+ "TerraCotta",
188
+ "Thinkbot",
189
+ "TikTokSpider",
190
+ "Timpibot",
191
+ "TongyiBot",
192
+ "Trae",
193
+ "TwinAgent",
194
+ "UseAI",
195
+ "VelenPublicWebCrawler",
196
+ "WARDBot",
197
+ "webzio-extended",
198
+ "wpbot",
199
+ "WRTNBot",
200
+ "xAI-Grok",
201
+ "YaK",
202
+ "YandexAdditional",
203
+ "YandexAdditionalBot",
204
+ "YiBot",
205
+ "YiyanBot",
206
+ "YouBot",
207
+ "ZanistaBot"
208
+ ]
package/src/lib/checks.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Plain JavaScript: the integration runs in Node, which does not strip types in node_modules.
2
2
  // The dev toolbar app uses the same functions, so the build and the toolbar give the same results.
3
3
 
4
+ import { trimSlash } from "./head.js"
4
5
  import { ASSET_RULES, RULES, SITE_RULES } from "./rules.js"
5
6
 
6
7
  export { findLink, parseHead } from "./head.js"
@@ -95,21 +96,6 @@ export function isNoindex(head) {
95
96
  return /noindex/i.test(head.meta.robots ?? "")
96
97
  }
97
98
 
98
- /**
99
- * Returns a path without the slash at the end, e.g. "/blog" for "/blog/". The root stays "/".
100
- *
101
- * @param {string} path
102
- * @returns {string}
103
- */
104
- function trimSlash(path) {
105
- if (path.length <= 1) return path
106
-
107
- // A loop and not a regular expression: /\/+$/ is slow for a path with many slashes
108
- let end = path.length
109
- while (end > 0 && path[end - 1] === "/") end--
110
- return path.slice(0, end)
111
- }
112
-
113
99
  /**
114
100
  * Returns true for a page path that matches a pattern of the `ignore` option.
115
101
  * In a pattern, `*` matches one part of the path and `**` matches any number of parts.
package/src/lib/config.ts CHANGED
@@ -65,8 +65,22 @@ export type MetadataConfig = {
65
65
  index?: boolean
66
66
  /** Set to false to tell search engines not to follow the links. */
67
67
  follow?: boolean
68
- /** Other directives for all pages, e.g. "max-image-preview:large". */
68
+ /**
69
+ * Other directives of the robots meta tag for all pages, e.g. "max-image-preview:large".
70
+ * They do not go into `robots.txt`.
71
+ */
69
72
  extra?: string
73
+ /**
74
+ * The AI crawlers. This option generates `robots.txt`. Set `search: false` to keep the
75
+ * site out of AI answers, and `training: false` to keep its content out of AI training.
76
+ * Both default to true.
77
+ *
78
+ * @example { search: true, training: false }
79
+ */
80
+ ai?: {
81
+ search?: boolean
82
+ training?: boolean
83
+ }
70
84
  }
71
85
  /** The web app manifest: an object to generate it, or the path of your own manifest. */
72
86
  manifest?: ManifestConfig | string
@@ -91,6 +105,8 @@ export type RuntimeConfig = MetadataConfig & {
91
105
  base?: string
92
106
  /** The `site` of the Astro config. The dev toolbar app loads its files from the dev server. */
93
107
  site?: string
108
+ /** True with `@astrojs/sitemap`: `robots.txt` links its sitemap. */
109
+ sitemap?: boolean
94
110
  }
95
111
 
96
112
  // The integration replaces this name with the config, with Vite's `define`
package/src/lib/head.d.ts CHANGED
@@ -23,3 +23,5 @@ export declare function findLinks(head: HeadData, rel: string): Record<string, s
23
23
  export declare function findLink(head: HeadData, rel: string): string | undefined
24
24
 
25
25
  export declare function isAbsolute(value: string): boolean
26
+
27
+ export declare function trimSlash(path: string): string
package/src/lib/head.js CHANGED
@@ -139,3 +139,18 @@ export function findLink(head, rel) {
139
139
  export function isAbsolute(value) {
140
140
  return /^https?:\/\//i.test(value)
141
141
  }
142
+
143
+ /**
144
+ * Returns a path without the slash at the end, e.g. "/blog" for "/blog/". The root stays "/".
145
+ *
146
+ * @param {string} path
147
+ * @returns {string}
148
+ */
149
+ export function trimSlash(path) {
150
+ if (path.length <= 1) return path
151
+
152
+ // A loop and not a regular expression: /\/+$/ is slow for a path with many slashes
153
+ let end = path.length
154
+ while (end > 0 && path[end - 1] === "/") end--
155
+ return path.slice(0, end)
156
+ }
@@ -0,0 +1,86 @@
1
+ import AI_BOTS from "./ai-bots.json"
2
+ import { getConfig } from "./config.ts"
3
+
4
+ /**
5
+ * The AI crawlers of the search group: they show the site in AI answers, or load a page
6
+ * when a user asks for it. The names come from the documentation of each company.
7
+ */
8
+ const SEARCH_BOTS = [
9
+ "OAI-SearchBot",
10
+ "ChatGPT-User",
11
+ "Claude-SearchBot",
12
+ "Claude-User",
13
+ "PerplexityBot",
14
+ "Perplexity-User",
15
+ ]
16
+
17
+ /**
18
+ * The training crawlers of the large companies. They are also in `ai-bots.json`, but the
19
+ * file must block them even if a new version of the list does not have them.
20
+ */
21
+ const TRAINING_BOTS = ["GPTBot", "ClaudeBot", "Google-Extended", "Applebot-Extended"]
22
+
23
+ /**
24
+ * The crawlers that the file never blocks: Apple search, and the Facebook link previews.
25
+ */
26
+ const KEPT_BOTS = ["Applebot", "facebookexternalhit"]
27
+
28
+ /**
29
+ * Returns the names that are not in a list, without case: robots.txt compares the names
30
+ * without case.
31
+ */
32
+ function without(names: string[], list: string[]): string[] {
33
+ const caseless = new Set(
34
+ list.map((name) => {
35
+ return name.toLowerCase()
36
+ })
37
+ )
38
+ return names.filter((name) => {
39
+ return !caseless.has(name.toLowerCase())
40
+ })
41
+ }
42
+
43
+ /**
44
+ * Returns a group of the file: the crawlers, and the rule for them.
45
+ */
46
+ function group(names: string[], rule: string): string {
47
+ const agents = names.map((name) => {
48
+ return `User-agent: ${name}`
49
+ })
50
+ return [...agents, rule].join("\n")
51
+ }
52
+
53
+ /**
54
+ * The `robots.txt` file of the `robots.ai` option.
55
+ */
56
+ export const RobotsTxt = {
57
+ /**
58
+ * Returns the AI crawlers that the file blocks.
59
+ * Without `search: false` or `training: false`, the file blocks no crawlers.
60
+ */
61
+ blocked(): string[] {
62
+ const ai = getConfig().robots?.ai ?? {}
63
+ const otherBots = without(AI_BOTS, TRAINING_BOTS)
64
+ const training = without([...TRAINING_BOTS, ...otherBots], [...SEARCH_BOTS, ...KEPT_BOTS])
65
+ return [...(ai.search === false ? SEARCH_BOTS : []), ...(ai.training === false ? training : [])]
66
+ },
67
+
68
+ /**
69
+ * Returns the text of the file: the blocked AI crawlers, the rule for all other
70
+ * crawlers, and the sitemap with `@astrojs/sitemap`.
71
+ */
72
+ build(): string {
73
+ const { site, base = "/", sitemap } = getConfig()
74
+ const blocked = RobotsTxt.blocked()
75
+
76
+ const groups = [
77
+ ...(blocked.length > 0 ? [group(blocked, "Disallow: /")] : []),
78
+ group(["*"], "Allow: /"),
79
+ ]
80
+ if (sitemap && site) {
81
+ const url = new URL(`${base.replace(/\/$/, "")}/sitemap-index.xml`, site)
82
+ groups.push(`Sitemap: ${url.href}`)
83
+ }
84
+ return `${groups.join("\n\n")}\n`
85
+ },
86
+ }
@@ -19,10 +19,12 @@ export type Rule = RuleBase & {
19
19
  check(head: HeadData): string | undefined
20
20
  }
21
21
 
22
- /** A built page: its path in the output folder, and its head. */
22
+ /** A built page: its path in the output folder, its head, and its URL. */
23
23
  export type SitePage = {
24
24
  path: string
25
25
  head: HeadData
26
+ /** The URL of the page, e.g. "https://example.com/about/". Undefined without `site`. */
27
+ url?: string
26
28
  }
27
29
 
28
30
  /** A problem of one page, found by a site rule. */
package/src/lib/rules.js CHANGED
@@ -15,7 +15,7 @@
15
15
  //
16
16
  // Text between backticks shows as code in the dev toolbar app.
17
17
 
18
- import { findLink, findLinks, isAbsolute } from "./head.js"
18
+ import { findLink, findLinks, isAbsolute, trimSlash } from "./head.js"
19
19
 
20
20
  /** The approximate lengths that search results show. */
21
21
  export const LIMITS = {
@@ -774,8 +774,26 @@ function duplicates(pages, valueOf, name) {
774
774
  }
775
775
 
776
776
  /**
777
- * The rules that compare the pages of the site. Only the build runs them, because the
778
- * dev toolbar app sees one page at a time. A check returns the problems of the pages.
777
+ * Returns true for two URLs of the same page. The slash at the end does not count,
778
+ * because the server can add or remove it.
779
+ *
780
+ * @param {string} a
781
+ * @param {string} b
782
+ * @returns {boolean}
783
+ */
784
+ function isSamePage(a, b) {
785
+ const first = new URL(a)
786
+ const second = new URL(b)
787
+ return (
788
+ first.origin === second.origin &&
789
+ trimSlash(first.pathname) === trimSlash(second.pathname) &&
790
+ first.search === second.search
791
+ )
792
+ }
793
+
794
+ /**
795
+ * The rules that need the built pages: they compare the pages of the site, or check the
796
+ * URL of a page. Only the build runs them. A check returns the problems of the pages.
779
797
  *
780
798
  * @type {import("./rules").SiteRule[]}
781
799
  */
@@ -808,6 +826,26 @@ export const SITE_RULES = [
808
826
  )
809
827
  },
810
828
  },
829
+ {
830
+ id: "canonical-not-page",
831
+ field: "canonical",
832
+ level: "warning",
833
+ check(pages) {
834
+ return indexedPages(pages).flatMap((page) => {
835
+ const canonical = findLink(page.head, "canonical")
836
+ if (!page.url || !canonical || !isAbsolute(canonical) || !URL.canParse(canonical)) {
837
+ return []
838
+ }
839
+ if (isSamePage(canonical, page.url)) return []
840
+ return [
841
+ {
842
+ path: page.path,
843
+ message: `The canonical URL \`${canonical}\` is not the URL of the page \`${page.url}\`. Search engines can index the other URL.`,
844
+ },
845
+ ]
846
+ })
847
+ },
848
+ },
811
849
  {
812
850
  id: "hreflang-no-return",
813
851
  field: "hreflang",
@@ -0,0 +1,11 @@
1
+ import type { APIRoute } from "astro"
2
+
3
+ import { RobotsTxt } from "../lib/robots-txt.ts"
4
+
5
+ export const prerender = true
6
+
7
+ export const GET: APIRoute = () => {
8
+ return new Response(RobotsTxt.build(), {
9
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
10
+ })
11
+ }