astro-aeo
v1.6.1
Published
Answer Engine Optimization for Astro: .md companion pages, llms.txt, llms-full.txt, robots.txt AI-bot policies, domain-profile.json, sitemap auto-wiring, JSON-LD components, a validator CLI, and one-line EmDash CMS support.
Downloads
1,727
Maintainers
Readme
Astro-AEO
Answer Engine Optimization and semantic publishing for Astro. One integration, zero config, no client JavaScript.
Astro-AEO makes your Astro site easy for AI search engines, assistants, and LLMs to discover, parse,
and cite. It generates clean Markdown copies, llms.txt indexes, deterministic Schema.org graphs,
crawler policies, and domain identity metadata with no external services or client JavaScript.
It is the Astro sibling of Jekyll-AEO.
New in 1.5: EmDash CMS support. Running a site on EmDash? Add
emdashAeo()and every published post, page, and project gets a Markdown copy and a place inllms.txt, updated within seconds of publishing. It works with the Blog, Marketing, Portfolio, and Starter templates, on Node and Cloudflare.
What is AEO
Answer engines (ChatGPT, Claude, Perplexity, Google AI Overviews, and others) read your pages to answer questions and cite sources. They do better with clean, structured text than with a page of HTML, scripts, and styles. AEO is the practice of publishing machine-readable companions to your site so those systems can find and quote your content accurately.
A Markdown copy of a page is roughly 20 to 30 percent smaller in tokens than its HTML. An llms.txt index of your whole site is a fraction of the size of crawling every page. Smaller, cleaner inputs mean cheaper, more accurate answers that are more likely to cite you.
Features
- EmDash CMS:
emdashAeo()lists every published EmDash entry at its public URL and keepsllms.txtcurrent as editors publish, on Node and Cloudflare. See EmDash CMS. - Starlight:
starlightAeo()adds Astro-AEO to a Starlight docs site as a plugin. See Starlight. - .md companion pages: a clean Markdown copy of every page, preserving authored Markdown when available and otherwise extracting from rendered HTML.
- llms.txt and llms-full.txt: a site index and a full-content file following the llmstxt.org spec.
- Alternate link tags:
<link rel="alternate" type="text/markdown">injected into every page so crawlers can find the Markdown. - JSON-LD components: FAQ, how-to, breadcrumb, organization, speakable, article, product, software application, review, item list, dataset, profile page, service, and local business.
- Semantic graph: one deterministic, XSS-safe managed Schema.org graph on every eligible page, with typed builders and integrity validation.
- Complete head metadata:
AeoHeadowns canonical, robots, Open Graph, Twitter/X, locale, alternate, feed, pagination, author, and graph output without replacing unrelated authored tags. - robots.txt: allow search and retrieval bots, block training crawlers, with automatic
Sitemap:andllms.txthints. - Sitemap: auto-wires the official
@astrojs/sitemap, verifies its build output before adding therobots.txthint, and mirrors the index to a conventional/sitemap.xmlwhen that target is free. - domain-profile.json: a
/.well-known/domain-profile.jsonidentity file for authoritative answers about your site. - Validator CLI:
npx astro-aeo validatechecks your build for common AEO mistakes. - Dev-server preview:
llms.txt,robots.txt, and.mdcompanions are served live inastro dev. - Git last-modified: freshness dates from git history or
article:modified_time, with zero config.
Installation
# with Astro's installer (adds the integration to your config)
npx astro add astro-aeo
# or install manually
bun add astro-aeo
# npm install astro-aeoAstro-AEO requires Astro 5 or newer and Node 20.19.5+. It ships as plain ESM with no build step, so it also works as a git dependency:
// package.json
"dependencies": {
"astro-aeo": "github:ZAAI-com/Astro-AEO"
}Prefer an AI-assisted install? Paste docs/SETUP_PROMPT.md into Claude Code, Cursor, or a similar assistant pointed at your Astro project and it will install and configure Astro-AEO for you. It detects Starlight and EmDash sites and sets them up with starlightAeo() or emdashAeo().
Quick Start
Zero config. Add the integration and build:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import aeo from 'astro-aeo';
export default defineConfig({
site: 'https://yoursite.com',
integrations: [aeo()],
});astro buildOut of the box you get: a .md companion beside every page, llms.txt and llms-full.txt at the
site root, an alternate link tag, a managed Schema.org graph on each eligible page with a stable
canonical URL, and a sitemap (via the auto-wired @astrojs/sitemap). Enable discovery.robots,
site.profile, corpus.urlMap, and the experimental schema.corpus outputs when you want them.
Using EmDash or Starlight? Use emdashAeo() or starlightAeo()
instead of aeo(); each registers Astro-AEO with the right defaults for that framework.
EmDash CMS
New in 1.5. EmDash is a full-stack CMS built on Astro: content lives
in a database, editors publish in an admin at /_emdash/admin, and every page renders on demand.
Astro-AEO supports it with one line. emdashAeo() finds every published post, page, and project,
serves a Markdown copy of each, lists them in llms.txt and llms-full.txt, and picks up new
entries within seconds of publishing, with no rebuild. It works with every EmDash template (Blog,
Marketing, Portfolio, and Starter), with sites that mix them, and on Node and Cloudflare.
Install it in your EmDash project, then add emdashAeo() next to emdash() instead of aeo():
npm install astro-aeo # not `astro add`, which would insert a plain aeo()// astro.config.mjs
import emdash, { local } from 'emdash/astro';
import { sqlite } from 'emdash/db';
import emdashAeo from 'astro-aeo/emdash';
export default defineConfig({
site: 'https://example.com',
output: 'server',
adapter: node({ mode: 'standalone' }),
integrations: [
react(),
emdash({ database: sqlite({ url: 'file:./data.db' }), storage: local({ /* ... */ }) }),
emdashAeo(),
],
});Publish a post in the admin, and a few seconds later your site answers with it:
$ curl https://example.com/llms.txt
# My Blog
- [The Case for Static](/posts/the-case-for-static.md): Static sites aren't a step backwards.
- [About](/pages/about.md)
- [Development](/category/development.md): All posts in the Development category.
$ curl https://example.com/posts/the-case-for-static.md
# The Case for Static
...It registers Astro-AEO for you with these defaults. Anything you pass as emdashAeo({ aeo: { ... } })
wins, and your own pages.exclude and pages.catalogs entries come first:
| Setting | Default | Why |
|---|---|---|
| pages.exclude | adds /_emdash/** and /404 | the admin, API, and 404 page are not content |
| pages.catalogs | adds the EmDash catalog, revalidate: 10 | EmDash pages exist only at request time |
| markdown.negotiation | 'response' | every EmDash page renders on demand |
| discovery.robots.enabled | false | EmDash serves its own robots.txt |
| discovery.sitemap.mode | 'disabled' | EmDash serves its own sitemaps |
The catalog lists every published entry of every collection that has a URL pattern, at the URL
EmDash itself builds from that pattern ({slug}, {id}, and the date tokens {year} to {second}).
It follows EmDash's sitemap rules: collections with SEO turned off, drafts, deleted entries, entries
without a slug, and entries marked noindex in the SEO panel are left out. A collection without a
URL pattern, such as the Marketing template's pages, is skipped because fixed routes (/,
/pricing) render it, and Astro-AEO already knows those. The catalog reads EmDash through its
public read API from your own emdash install, so it works with any EmDash database and never
opens one itself. Entries you publish appear within
revalidate seconds without a restart.
Options
emdashAeo({
collections: {
posts: { section: 'Blog' }, // an llms.txt heading; URLs from the seed urlPattern
pages: { section: { title: 'Pages', match: ['/about', '/team'] } },
legal: false, // keep a collection out of the corpora
},
taxonomies: { category: '/category/{slug}', tag: '/tag/{slug}' }, // archive routes to list
revalidate: 10, // seconds; 0 = every request, false = once per process
maxEntries: 50000, // matches EmDash's sitemap limit
aeo: { pages: { exclude: ['/search'] } }, // any Astro-AEO option
})A string section takes its URLs from the collection's urlPattern in the seed file named by
package.json (/posts/{slug} matches /posts/**). A pattern that starts at the site root, such as
/{slug}, needs an explicit match. EmDash stores no URL for a taxonomy, so archive pages are listed
only when taxonomies names their route, and only for terms that have published entries.
What each template gets
| EmDash template | Listed automatically | Options worth setting |
|---|---|---|
| Blog | /posts/*, /pages/* | taxonomies for /category/* and /tag/*; exclude /search |
| Marketing | /, /pricing, /contact (fixed routes) | none |
| Portfolio | /work/*, /about | none |
| Starter | /posts/*, root pages such as /about | taxonomies |
| Your own mix | every collection with a URL pattern | collections for llms.txt sections or to leave one out |
Each row has a complete, tested project under recipes/: emdash-blog,
emdash-marketing, emdash-portfolio, emdash-starter, the mixed emdash site, and
emdash-cloudflare.
Things to know
emdashAeo()throws ifaeo()is also registered, or ifemdash()is missing. It accepts the current option names only, and it cannot enable IndexNow: the build has no page inventory for an EmDash site, so IndexNow would read every page as removed.- With i18n enabled, the catalog lists the default locale only and warns once. Describe translated entries in a catalog of your own.
- Aggregate files are origin-scoped in production: a deployed server answers
llms.txtfor the configuredsiteorigin, not for arbitraryHostheaders. - Request-time corpora need Astro 6.3 or newer, and EmDash needs Node 22.16 or newer.
- On Cloudflare the catalog reads D1 through EmDash's own per-request session, so the options are
the same as on Node.
emdash-cloudflareruns the mixed site in workerd on a local D1 database.
Configuration
All options are optional. Defaults are shown.
aeo({
site: {
name: '', // llms.txt heading; falls back to profile, <title>, hostname
description: '',
defaultLocale: undefined, // BCP 47 locale used when a page supplies none
organization: undefined, // explicit Schema.org entity or { '@id': ... } reference
profile: { // /.well-known/domain-profile.json
enabled: false,
name: '', // e.g. 'Your Site'
description: '', // e.g. 'What your site is about.'
website: '', // defaults to the Astro `site`
email: '', // '@' -> email, http(s) -> contactPoint, else telephone
logo: '',
sameAs: [],
entityType: 'Organization', // Organization | Person | Blog | ...
origins: {}, // origin-keyed overrides of profile fields (not enabled)
},
},
pages: {
include: ['**'], // path globs to include
exclude: [], // path globs to exclude, e.g. ['/drafts/**']
respectNoindex: true, // skip pages with <meta name="robots" content="noindex">
stripTitleSuffix: false, // strip " | Your Brand" from titles: string | string[] | RegExp
devDynamicDiscovery: 'startup', // 'startup' | 'hot' (experimental) | false
catalogs: [], // request-time inventory and exact descriptor modules; { module, revalidate? }
},
markdown: { // the .md companions
enabled: true,
strategy: 'auto',
renderers: [], // importable modules; inline functions are prerender-only
alternateLink: 'auto', // 'auto' | 'always' | 'never'
includeLastModified: true,
frontmatter: false, // prepend YAML frontmatter to .md files
negotiation: 'off', // 'off' | 'response' | 'redirect', on-demand routes only
extraction: {
selectors: ['article', 'main'], // tried in order, first with a match wins
removeSelectors: ['nav', 'footer'], // dropped before conversion
keepSelectors: [], // preserved as minimized HTML in the Markdown
},
},
corpus: {
index: { // llms.txt
enabled: true,
sections: [{ title: 'Home', match: '/' }], // ordered, first match wins
defaultSection: 'Pages', // section for unmatched pages, or false to drop them
includeDescriptions: true,
showLastModified: false,
includeHtmlOnly: false, // list no-dotmd pages (linking to HTML) instead of omitting them
},
full: { // llms-full.txt
enabled: true,
mode: 'all', // 'all' | 'index' | 'first-page-only'
},
small: { enabled: false, maxTokens: 20_000 },
chunks: { enabled: false, maxTokensPerFile: 100_000, by: 'section' },
manifest: { enabled: false }, // /llms/manifest.json
versions: undefined, // { current: 'v2', order: ['v1'] }; opt-in partitions
rag: { enabled: false, maxTokens: 512, publish: false }, // private locale/version JSONL
tokenizer: undefined, // { module, options? }; local importable module only
compression: { gzip: false }, // deterministic static .gz siblings
urlMap: {
enabled: false,
outputFilepath: 'docs/Url-Map.md', // replaced on each enabled, successful build
},
runtime: {
maxPages: 50, // positive integer | 'unlimited'; refuses larger live corpora
},
},
i18n: {
indexes: 'auto', // 'auto' | 'global' | 'locale' | 'both'
unresolvedLanguage: 'default', // 'default' | 'error' | 'exclude'
},
cache: { enabled: true },
discovery: {
sitemap: {
mode: 'auto', // 'auto' | 'external' | 'disabled'
options: {}, // forwarded when auto-wired; filenameBase also hints user-owned output
alias: {
enabled: true, // mirror the generated index when /sitemap.xml is free
sourceFilename: 'sitemap-index.xml', // defaults to the @astrojs/sitemap filenameBase output
outputFilename: 'sitemap.xml', // conventional filename written at the build root
},
},
robots: {
enabled: false,
policy: 'custom', // custom | open | search-open-training-closed | retrieval-only | closed
universalAllow: true, // lead with "User-agent: * / Allow: /" (suppressed if '*' is named below)
allow: [], // e.g. ['Googlebot', 'OAI-SearchBot', 'Claude-SearchBot']
disallow: [], // e.g. ['GPTBot', 'ClaudeBot', 'Google-Extended']
includeSitemap: undefined, // omitted = auto-detect; true = force; false = omit
sitemapPath: '/sitemap-index.xml', // defaults to the @astrojs/sitemap output name (tracks filenameBase)
includeLlmsTxt: true,
extraLines: [],
// contentSignals: { search: true, aiInput: true, aiTrain: false },
},
indexNow: {
enabled: false,
submit: 'changed', // 'changed' | 'all'
state: 'public', // 'public' | 'private' | 'stateless'
strict: false,
key: { source: 'env', name: 'ASTRO_AEO_INDEXNOW_KEY' },
// keyLocation: '/indexnow-key.txt',
origins: [],
},
},
artifacts: {
replace: [], // exact served pathnames only; no globs
},
metadata: {
fillMissing: false, // never replaces authored metadata
defaults: {}, // explicit fallback values only
},
schema: {
autoInject: true,
infer: ['website', 'webpage', 'breadcrumbs'],
strictReferences: true,
corpus: {
enabled: false,
graphPath: '/schema/graph.jsonld',
mapPath: '/schema/schema-map.xml',
},
},
validation: {
onBuild: 'artifacts', // 'artifacts' | 'recommended' | 'off'
failOn: 'error', // 'error' | 'warning'
},
plugins: [],
});All 1.3 corpus, i18n, cache, crawler, and IndexNow outputs shown above are implemented. New corpus
families, gzip, crawler presets, Content Signals, and IndexNow remain disabled until configured.
The 1.4 audit command and its SARIF, JUnit, HTML, Markdown, and GitHub report formats are implemented
(see Audit), and so are static edge negotiation and the
doctor and fix deployment commands.
validation.onBuild decides what can fail a build, at the severity chosen by validation.failOn:
'artifacts'(default): diagnostics raised while generating and writing artifacts.'recommended': the above, plus each page's own diagnostics (extraction, renderer, metadata), plus the audit rules a build can answer from its page model:markdown-empty,markdown-thin,markdown-no-h1,markdown-html-residue,description-missing, and thetitle-duplicate,description-duplicateandcanonical-duplicatechecks. Onlymarkdown-emptyis an error, so with the defaultfailOn: 'error'a page whose companion has no text is what newly stops a build. Link, anchor and hreflang rules need the rendered site and run only inastro-aeo audit.'off': nothing optional. Artifact integrity errors that would corrupt output still stop the build.
Migrating to 1.4
1.4 adds features and changes no configuration key. A project that uses none of them emits the same public files as 1.3.2. Four behaviors are worth knowing before you upgrade:
validation.onBuild: 'recommended'also gates on the audit rules a build can answer from its page model. With the defaultfailOn: 'error', the one new blocking rule ismarkdown-empty: a Markdown companion with no text, such as a page whose content is only an image.'artifacts'and'off'are unchanged.- A catch-all page rendered on demand (
src/pages/[...slug].astro, or an integration's equivalent) no longer owns every.mdcompanion and text artifact path. Those requests answered a bodyless404before and are served now./[...slug].jsonand dynamic endpoints still own their paths. - On a site with more than one Astro i18n locale, the inferred site-wide
WebSiteentity no longer carriesinLanguage. Each page would otherwise claim its own language for the one shared entity, and the merged site graph failed the build withschema.scalar-conflict. EveryWebPagekeeps its language, and single-language sites are unchanged. - Repeated
<meta name="generator">tags no longer reportmetadata-conflict.
Every build also writes a private .astro/aeo-cache/deployment-v1.json beside the existing manifests. It
holds names and modes only and is never published.
Migrating to 1.3
Ordinary projects with one implicit locale keep the 1.2 root llms.txt, llms-full.txt,
Markdown, profile, and custom robots.txt bytes. Multilingual projects can choose a topology with
i18n.indexes. In auto, one active locale remains at the root while multiple locales receive
canonical families under /<locale>/ and a root language directory. locale emits no root
corpus, global groups languages at the root, and both adds locale families plus flat byte-copy
aliases such as /llms-en.txt.
Astro string locale values are the directory identity. Locale objects use path as the directory
and codes[0] as the primary BCP 47 language. Page language resolves after semantic enrichment.
Invalid explicit declarations are errors; unresolved pages follow i18n.unresolvedLanguage.
External public HTTPS hreflang links are allowed but never fetched. Plain http: alternates are
accepted only on localhost, 127.0.0.1 and [::1], and only while the page is served from one of
those hosts or astro dev or astro preview is running, so a production build still rejects a
stray local link.
The private .astro/aeo-cache directory can contain normalized derived page content and IndexNow
notification state. Keep .astro uncommitted, transfer the indexnow pending and acknowledgment
directory between separate CI prepare/submit jobs, and protect it as sensitive build data. Cache
files use restrictive permissions where supported, and the extraction cache resets itself when the
extractor changes (see Incremental processing cache).
cache.enabled: false disables payload reuse, not artifact ownership or IndexNow safety ledgers.
Migrating to 1.2
Version 1.2 deliberately changes three defaults or public contracts:
schema.autoInjectdefaults totrue. Upgrading adds one Astro-AEO-managed JSON-LD graph to eligible HTML pages that have a stable canonical URL. Setschema: { autoInject: false }to retain 1.1 HTML byte behavior. An explicitly renderedAeoHeadstill works when global injection is disabled.AeoPageRecordis now the shared rich page model. It adds route identity, nested metadata, source and representation records, dates, authors, entities, directives, extraction details, and diagnostics. The existing flaturl,mdHref,title,description,markdown,lastModified, andaeoTokensfields remain as deprecated runtime and type mirrors through 1.x. The smallerAeoPageused by section match predicates is unchanged.- Project routes and
public/files now own their served path by default. Astro-AEO will not overwrite them unless the exact normalized served pathname appears inartifacts.replace. Globs are rejected, and duplicate generated claims emit neither claimant. Version 1.2.0 also preserved existing project-root URL-map files; 1.3 restores the pre-1.2 behavior and regenerates the configured URL map on every successful build when enabled. The served-path ownership flip is the other intentional 1.x compatibility exception.
For example, a project that deliberately replaces its own /docs/llms.txt under an Astro base of
/docs must authorize that exact browser-visible pathname:
aeo({
artifacts: { replace: ['/docs/llms.txt'] },
schema: { autoInject: false },
});Migrating from 1.0
Every 1.0 key still works and produces the same output as its canonical replacement. Using one emits a single deprecation warning per section; the 1.0 keys are removed in 2.0.
| 1.0 | Canonical 1.x |
| --- | --- |
| include, exclude, respectNoindex, stripTitleSuffix | pages.* |
| dotmd.enabled, dotmd.includeLastModified, dotmd.frontmatter | markdown.* |
| dotmd.linkTag | markdown.alternateLink |
| dotmd.dotmdMetadata | markdown.frontmatter |
| llmsTxt.* | corpus.index.* |
| llmsTxt.showLastmod | corpus.index.showLastModified |
| llmsTxt.includeNoDotmd | corpus.index.includeHtmlOnly |
| llmsFullTxt.* | corpus.full.* |
| urlMap.* | corpus.urlMap.* |
| sitemap.enabled: true / false | discovery.sitemap.mode: 'auto' / 'external' |
| sitemap.options | discovery.sitemap.options |
| sitemapAlias.* | discovery.sitemap.alias.* |
| robotsTxt.* | discovery.robots.* |
| domainProfile.* | site.profile.* |
| domainProfile.contact | site.profile.email |
To see the canonical replacement for your own config, build once with the printer on:
AEO_PRINT_MIGRATION=1 astro buildIt prints a paste-ready block derived from the keys you actually set. Dates and regular
expressions retain executable constructors. Functions appear as undefined TODO
placeholders, so copy those callbacks by hand.
Two rules are worth knowing:
- You can mix eras as long as they address different settings. Setting a 1.0 key and
its canonical replacement to different values is a build-stopping error naming both
paths, because silently picking one could publish the wrong
robots.txtpolicy. - Values compare structurally, but callbacks compare by reference. Pasting the same
matchfunction into bothllmsTxt.sectionsandcorpus.index.sectionsis reported as a conflict: delete one.
sitemap.enabled: false maps to mode: 'external', not 'disabled'. It never meant
"no sitemap", only "do not auto-register @astrojs/sitemap"; a sitemap you register
yourself stayed in use. The new disabled mode, which has no 1.0 equivalent, opts out
of sitemap handling entirely.
Sitemap
Astro-AEO does not generate sitemap XML itself; it defers to the official @astrojs/sitemap integration, which handles the hard parts (index splitting past 50k URLs, i18n alternates, lastmod). With discovery.sitemap.mode: 'auto' (the default) and Astro site set, Astro-AEO auto-registers @astrojs/sitemap when you have not added it yourself. After sitemap generation finishes, Astro-AEO verifies the configured file exists before adding the Sitemap: line to robots.txt. If filtering, serialization, or an empty site produces no index, the line is omitted instead of advertising a 404.
- Already using
@astrojs/sitemap? Astro-AEO detects it and stays out of the way (no double registration); your configuration is used as-is. - Want to tune the auto-registered sitemap? Pass options straight through:
aeo({
discovery: {
sitemap: {
options: {
changefreq: 'weekly',
filter: (page) => !page.includes('/drafts/'),
},
},
},
});Set discovery.sitemap.mode: 'external' to disable auto-registration. A user-registered sitemap is still detected and finalized. Use 'disabled' to opt out of sitemap handling entirely, including the alias and the robots.txt Sitemap: line.
For a separately registered sitemap with a custom filenameBase, repeat that value in Astro-AEO as the shared output-name hint. Other discovery.sitemap.options are ignored when the user owns the integration, but filenameBase keeps the alias source and default robots path aligned:
import sitemap from '@astrojs/sitemap';
integrations: [
sitemap({ filenameBase: 'docs' }),
aeo({
discovery: {
sitemap: {
mode: 'external',
options: { filenameBase: 'docs' },
},
},
}),
],By default @astrojs/sitemap names its index sitemap-index.xml (a custom filenameBase makes it ${filenameBase}-index.xml), so a request for the conventional /sitemap.xml returns 404. With discovery.sitemap.alias.enabled (the default), Astro-AEO byte-copies the generated index to /sitemap.xml after generation. The copy is byte-identical, but it is created only when the source exists and the target does not. Any existing build output wins, including a file from public/, a prerendered Astro endpoint, or another integration. Remove that output if you want Astro-AEO to provide the alias instead.
discovery.robots.sitemapPath defaults to the tracked sitemap output name (/sitemap-index.xml, or /${filenameBase}-index.xml). When includeSitemap is omitted, Astro-AEO automatically emits the line only if that path exists in the static build. Set includeSitemap: true to force the line for an SSR or runtime-only sitemap, or false to suppress it. In astro dev, automatic mode recognizes public files and concrete Astro routes but does not advertise the build-only @astrojs/sitemap output.
Giving a page its own source
Astro-AEO reads a page's content out of its rendered HTML. That is a good
approximation, but only an approximation: a heading that was ## in the source is
an <h2> by the time it is served, and the exact wording of a code fence or a
table is gone. When a page is built from Markdown, the page itself still has the
original, and can hand it over:
---
import { defineAeoPage } from 'astro-aeo/page';
import { AeoPage } from 'astro-aeo/components';
import { getEntry, render } from 'astro:content';
const post = await getEntry('blog', Astro.params.slug);
const aeoPage = defineAeoPage({ source: post });
const { Content } = await render(post);
---
<AeoPage {...aeoPage} />
<Content />defineAeoPage reads body, data.title, data.description, image, language, version, and dates from a
content-collection entry, or accepts explicit authored Markdown/MDX, source kind/path, authors,
Schema.org entities, and directive hints. Every field is optional; supplying none is the same as
not using it at all, and extraction runs as usual. The body of an .mdx entry is never used as
Markdown, because it holds imports and JSX: a registered astro-aeo/mdx renderer converts it, and
without one the page's rendered HTML is extracted.
The marker the component emits is internal. It is written only when Astro-AEO is
the one rendering the page (the build's prerender pass, or a request for the .md),
and it is removed from every page before anything is written or served, so it never
reaches a browser and never appears in a .md file.
Standalone .md page routes need no marker: Astro-AEO reads their source directly,
removes only leading YAML frontmatter, and embeds on-demand sources through a Vite
?raw registry in the server bundle. The release bundle-size gate measures this cost.
Dynamic routes and catalogs
Static builds already give Astro-AEO every concrete pathname returned by a prerendered
route's getStaticPaths(). Those pages receive the same .md, llms.txt,
llms-full.txt, schema corpus, and URL-map treatment as file-based pages without a
catalog.
In astro dev, pages.devDynamicDiscovery controls how aggregate live corpora find
prerendered dynamic paths:
'startup'(default) uses Astro's public route hook to remember the dynamic route modules present when the server starts. Astro-AEO imports those modules lazily only when an aggregate corpus is requested, then calls theirgetStaticPaths()functions. Changes to an existing route module or its content dependencies appear on the next corpus request. Adding or deleting an entire dynamic route file requires a restart.'hot'also tracks dynamic route-file additions and deletions. This mode is experimental because it relies on Astro's privatevirtual:astro:routesmodule, whose shape may change between Astro releases. If it becomes incompatible, switch back to'startup'.falsepreserves catalog-only development enumeration. When a project has a dynamic page route and nopages.catalogsmodule, Astro-AEO warns that the development corpus is incomplete.
Enumeration is only half the job: a discovered path still has to render. When two dynamic
route patterns both match a path and the one Astro sorts first does not produce it,
Astro's development server cannot reach the right route through an internal rewrite. A
src/pages/[category]/ route with no entries alongside src/pages/[...slug].astro is the
common shape. Ordinary requests are unaffected, and so is the build.
Astro-AEO recovers in development by re-requesting that one page from the address the
development server reported at startup, so the corpus and .md companions stay complete.
This is the single exception to the request-time rule that no network destination is
derived from a request: the destination is Astro's own bound address, never a header, the
transport exists only in astro dev, and it is reached only after an in-process rewrite
has already failed. If the fallback is unavailable, Astro-AEO names the incomplete corpus
in the terminal and answers the affected .md request with the reason instead of an empty
404. Catalogs do not work around this, because a catalog supplies pathnames and pathnames
were never the missing piece.
Discovery loads only page modules that Astro has resolved as project-owned,
prerendered dynamic routes. Astro-AEO never crawls the site and never parses project
content directories. Props returned with getStaticPaths() entries are discarded
immediately and are never placed in a virtual module or corpus. Keep
getStaticPaths() deterministic and safe to evaluate during an aggregate corpus
request.
Catalogs remain necessary for on-demand or SSR routes, external CMS-only inventory, synthetic pages, and any other request-time path that Astro cannot enumerate. They are also useful when an automatic pathname needs exact authored Markdown or metadata. A catalog descriptor overlays a matching concrete or automatically discovered path, so its authored source and metadata win:
// astro.config.mjs
aeo({ pages: { catalogs: [{ module: './src/aeo-catalog.js' }] } })// src/aeo-catalog.js
export default {
name: 'blog',
async listPages(context) {
const posts = await fetchPostsFromYourCms();
return posts.map((p) => ({
pathname: `/blog/${p.slug}`,
rendering: 'on-demand',
title: p.title,
markdown: p.markdown,
lastModified: p.updatedAt,
sourcePath: `cms:${p.id}`,
}));
},
};Content and CMS helpers
astro-aeo/content removes the boilerplate above. Every helper is plain data in, plain data out, so a
catalog built with them is still loadable by Node before Vite exists (a catalog module cannot import
astro:content; read a JSON export, a file glob, or an index your project builds).
// src/aeo-catalog.js
import { defineCmsAdapter } from 'astro-aeo/content';
export default defineCmsAdapter({
name: 'sanity',
async listPages() {
const posts = await fetchPostsFromYourCms();
return posts.map((p) => ({ id: p.id, pathname: `/blog/${p.slug}`, title: p.title, markdown: p.markdown }));
},
});contentPage(entry, overrides?)returns<AeoPage>props from a content-collection entry. It isdefineAeoPage({ source: entry, ...overrides }).contentDescriptor(entry, { pathname, ...overrides })returns a serializable catalog descriptor from an entry: title, description, image, language, version, dates, Markdown body, and source path. An.mdxbody is carried assource.bodyfor a registered renderer instead of as Markdown.defineContentCatalog({ name?, entries, toPage })builds a catalog.entries(context)loads your entries andtoPage(entry, context)returns{ pathname, ...overrides }, ornullto leave one out.defineCmsAdapter({ name, listPages })builds a catalog whose pages always carrysource.kind: 'cms'and the source pathcms:<name>:<id>, whatever the adapter reported. Fetching, credentials, and caching stay in your adapter; Astro-AEO adds no network access.
These catalogs load through the same failure isolation as a hand-written one: a catalog that throws
warns, records catalog-load-failed, and contributes nothing.
EmDash
EmDash sites use emdashAeo() instead of aeo(), with a catalog that lists every published entry.
See EmDash CMS.
Privacy-first request analytics
Analytics is disabled by default. On an observable on-demand Astro middleware surface:
aeo({ analytics: { enabled: true, scope: 'agents', sampleRate: 1,
adapter: { type: 'console' }, strict: false } })Only public in-base GET/HEAD requests are observed. Collection, prerendering, anonymous
corpus fan-out and development loopback requests are excluded. agents includes AEO
artifact requests and claimed crawler HTML requests; all explicitly includes ordinary
traffic. Events use minute-rounded UTC, configured inclusion rates and the versioned
crawler registry. User-Agent classifications are claims, not verified identities.
Known paths take priority over declared route patterns, then (unlisted); route parameter
values and arbitrary requested paths are never logged. IP, query, referrer, cookies,
authorization, raw request headers and response bodies are not collected. Cache outcomes
are not-modified for HTTP 304 or unknown, never an inferred provider hit/miss.
The astro-aeo/analytics export includes AnalyticsEventV1 (and astro-aeo/analytics-event.schema.json), AnalyticsAdapterModule,
createAnalytics, createConsoleSink, createWebhookSink and createOpenTelemetrySink.
Console events start with astro-aeo:analytics-v1 . Development always uses console,
including when another sink is configured. Disabled and omitted analytics have identical
analytics-free server bundles. No browser script is installed.
Delivery options:
| Adapter | Configuration and constraints |
| --- | --- |
| console | Default; marked one-event JSON lines. |
| jsonl | Node adapter, Node-based development or preview only (not workerd/Deno); default .astro/aeo-analytics/events-v1.jsonl, mode 0600, serialized appends, no symlinks or paths escaping the project. |
| webhook | { type: 'webhook', url: 'https://events.example.test', headers: { Authorization: { env: 'EVENT_TOKEN', prefix: 'Bearer ' } } }; secrets resolved at request time, one-event envelopes, redirects rejected, two-second timeout. |
| opentelemetry | An HTTPS endpoint for OTLP/HTTP JSON, or separately installed optional @opentelemetry/api peer. Counters have bounded attributes, never path attributes. Edge helpers can inject a meter-backed sink. |
| module | { type: 'module', module: './analytics.mjs', options: { ... } }; strict JSON options and a default export { apiVersion: 1, createSink(options) } returning a function (event) => void | Promise<void>. Setup is preflighted. |
Strict preflight failures reject configuration; non-strict failures disable delivery with sanitized advice. Runtime failures are caught and reported once (strict: error; otherwise: warning), never propagated into HTTP. Supported provider request-lifetime callbacks retain pending delivery. Without a callback, delivery is caught fire-and-forget and is best effort. Runtime module loading/setup failures disable delivery without preventing HTTP responses. Module sinks receive only sanitized events and are responsible for their own runtime portability.
A static deployment must explicitly declare an edge plugin and inject the observer into its handler. Integration configuration does not install deployment middleware. For example, with the Cloudflare edge plugin already configured:
import { createCloudflareHandler } from 'astro-aeo/edge/cloudflare';
import { createAnalytics, createWebhookSink } from 'astro-aeo/analytics';
const handlers = new WeakMap();
export default {
fetch(request, env, context) {
if (!handlers.has(env)) {
const analytics = createAnalytics({ enabled: true, base: '/docs',
inventory: ['/docs/guide'], artifacts: ['/docs/guide.md', '/docs/llms.txt'],
sink: createWebhookSink({ url: 'https://events.example.test',
headers: { Authorization: { env: 'EVENT_TOKEN', prefix: 'Bearer ' } },
secret: (name) => env[name] }),
});
handlers.set(env, createCloudflareHandler({ base: '/docs', analytics }));
}
return handlers.get(env).fetch(request, env, context);
},
};Cloudflare Pages/Workers and Netlify use supplied context lifetimes; Vercel accepts
waitUntil alongside its next/rewrite helpers. These observers report only traffic
reaching their declared surface, not whole-host logs or verified visitors. Vercel observations
are routing-middleware responses, not the final origin status. Prerendered HTML served directly
by an asset layer does not pass through Astro middleware. Provider checks are local contracts,
not deployed verification. Analytics with no observable on-demand route and no declared edge
surface is rejected.
Page versions
Version labels remain metadata-only unless corpus.versions is explicitly configured.
Opt in with corpus: { versions: { current: 'v2', order: ['v1'] } }: current is required,
unlabelled pages belong to it, and order lists unique safe version labels.
The additional opt-in configuration contracts are markdown.cacheControl (an HTTP header
value, omitted to inherit), corpus.rag (enabled: false, maxTokens: 512, publish: false),
and analytics (enabled: false, scope: 'agents', sampleRate: 1, strict: false).
Analytics adapters use a type of console, jsonl, webhook, opentelemetry, or module.
IP, query and referrer privacy settings accept only 'omit'. Delivery headers use runtime
environment references such as { Authorization: { env: 'AEO_TOKEN', prefix: 'Bearer ' } },
never build-time secret values. Invalid booleans, enum values and new options report their
configuration path through AeoConfigError.
A page may carry a documentation version label: version: 'v2' on a catalog descriptor, on
defineAeoPage, or as data.version on a content entry. A label is one path segment of letters,
digits, ., _ or - (at most 64 characters); anything else is ignored, and a catalog reports
catalog-invalid-version. The label appears on AeoPageRecord, on plugin page records, and on the
page's corpus manifest entry. Without corpus.versions, labels remain metadata-only and change
no generated artifact; an unversioned site keeps its existing bytes.
With version partitioning enabled, current-version corpus paths stay unchanged. Archives insert one version segment beneath the existing base and locale topology:
| Family | Current | Archived v1 |
| --- | --- | --- |
| Locale index | /docs/fr/llms.txt | /docs/fr/v1/llms.txt |
| Locale full corpus | /docs/fr/llms-full.txt | /docs/fr/v1/llms-full.txt |
| Locale chunk | /docs/fr/llms/guide-0001.txt | /docs/fr/v1/llms/guide-0001.txt |
| Compatibility alias (both) | /docs/llms-fr.txt | /docs/v1/llms-fr.txt |
A global or single-locale root family uses /docs/v1/llms.txt for the archive. Static gzip
siblings append .gz to these same paths. This partitions corpus artifacts, not project routes
or companion URLs. Locale topology is selected from the complete inventory, not independently
per version. Configured order sorts observed archives; other observed versions follow in
code-unit order. A configured archive with no inventory does not invent pages.
/llms/manifest.json joins all versions with versions, scoped locale/artifact records, and page
versionAlternates. Each observed archive also has /v1/llms/manifest.json, restricted to its
own records. Both include only artifacts that win ownership arbitration. An incomplete live
inventory still fails closed, and runtime manifests omit static gzip siblings.
Cross-version page matching removes only the configured base, configured locale prefix and
matching version prefix, each at most once. It matches within a locale, never between languages.
When routes have different names, supply versionGroup on defineAeoPage, a catalog descriptor,
or content-entry data:
defineAeoPage({ source: entry, version: 'v1', versionGroup: 'installation' });Generated alternatives use { kind: 'version', version: 'v1', url: 'https://example.com/v1/install/' }.
Existing { language: 'fr', url: '...' } hreflang alternatives are unchanged and never treated as
version links. Version metadata crosses immutable plugin page boundaries; build hooks and live
corpus hooks see reciprocal alternatives after collection. Ambiguous logical identities and
conflicting declared version alternatives are errors, not guessed links. Audits check reciprocity
and locale/version identity among known records. Authored canonicals and graph identities remain
authoritative.
A catalog that cannot resolve, import, evaluate, or run listPages() warns and
contributes nothing rather than failing the build or server startup. Catalogs run in
configured order in both builds and server bundles; the first descriptor wins when
two catalogs name the same normalized path. context contains the command, site URL,
base path, and trailing-slash policy.
A request-time server lists each catalog once per process. Give a catalog a revalidate window to
list it again once that many seconds have passed since its last listing, so a CMS catalog picks up
published entries without a restart: { module: './src/aeo-catalog.js', revalidate: 30 }. 0 lists
on every use of the inventory, and false (or omitting it) keeps the first listing. If a revalidating
catalog's first listing fails, it is retried on its next use instead of staying empty; if a later
refresh fails, the last listing stays in place and the refresh is retried after another window.
A refresh never holds up a request: the last inventory is served until the fresh one is ready.
Development always lists afresh, and a build lists once.
Catalog entrypoints must be JavaScript that Node's native module loader can execute:
.js, .mjs, or .cjs. This keeps build preflight identical on every supported Node
version. Catalog logic may be authored in TypeScript, but it must be compiled to a
JavaScript entrypoint before Astro loads the integration. Source .ts, .tsx, .mts,
.cts, .jsx, and .astro catalog entrypoints warn and contribute nothing. Node's
built-in TypeScript support is not a portable substitute: it is unavailable on Node 20,
handles only erasable syntax by default, and ignores tsconfig.json behavior. See the
Node TypeScript documentation.
Request-time middleware owns llms.txt and llms-full.txt when at least one project page
route renders on demand, because those pages are outside the build's reach. When every page
route is prerendered the build emits both files even if an adapter is installed, and they
contain every getStaticPaths() result.
In that case the middleware declines those paths, along with the schema corpus, rather than
answering with a second and shorter list: a request-time render cannot expand
getStaticPaths(). Every supported adapter serves static assets before the application, so
the emitted file answers. A deployment that reaches the application first, such as
@astrojs/node in middleware mode mounted ahead of its own static handler, receives 404
instead. Serve your static output before the Astro handler.
Once middleware owns them, both files render each known route through the
application so page markers behave normally. Each route is rendered serially through
Astro's in-process rewrite pipeline: no network destination is derived from the Host
header, the trusted rewrite capability exists only in process, and caller credentials
are not copied into corpus renders. The one exception is the development rewrite
fallback described under "Dynamic routes and catalogs", which re-requests a single page
from the development server's own bound address after an in-process rewrite has failed,
and which is never present in a production or adapter bundle. corpus.runtime.maxPages defaults to 50. A larger
corpus returns 503 with Cache-Control: no-store, without partial output. Raise the
limit or select 'unlimited' only when the deployment can safely absorb that work.
A hybrid inventory containing a prerendered page that Astro cannot rewrite also returns 503,
rather than silently dropping that known page. Its build-time .md companion remains available.
No production loopback fallback bypasses this restriction.
Temporary source failures also return a sanitized, non-cacheable 503, never a successful
shorter text or schema corpus. This includes rendering, transport and body-read failures,
server errors and partial or unusably encoded HTML. GET and HEAD share the
failure status. Anonymous authorization denials, redirects, missing routes, non-HTML routes
and explicit page opt-outs remain valid exclusions; plugin and semantic errors retain 500.
Astro 5 and Astro 6.0-6.2 receive 503 for request-time corpora because those
versions do not expose a disposable request state. Their closure-held client address,
cookies, and session cannot be replaced securely for an anonymous corpus render. The
response reports an unrecognized request state rather than an Astro version, because the
middleware can only observe the shape it was handed.
Build-time corpus artifacts and authenticated direct .md requests are unaffected.
Production and preview also return 503 with Cache-Control: no-store when a known page
cannot be collected: a failed rewrite, upstream server error, or unusable HTML response
must not produce a successful but incomplete corpus. This covers index/full/small corpora,
aliases, chunks, manifests, and schema graph/map. Authentication denials, redirects,
non-content responses, noindex, and opted-out pages remain intentional exclusions.
A mixed static/server site also fails closed if its adapter cannot render a known
prerendered page during collection; its built Markdown companion remains available.
Astro 6.3 and newer use a separate disposable request state for every serialized
corpus render, including streams whose cancellation never settles. This requirement
also applies when a live corpus uses automatic dynamic-route discovery. Ordinary HTML
and direct .md requests remain independent of aggregate discovery.
Content negotiation
markdown.negotiation lets a client ask for Markdown at a page's own URL instead of
its .md path. 'response' returns Markdown at the original URL; 'redirect' sends
a 303 to the .md URL. Default is 'off'.
Markdown has to be asked for explicitly and outrank HTML strictly. A wildcard
(*/*), a tie, a missing header, and a malformed one all resolve to HTML, so
browsers, curl, and crawlers that send */* are unaffected. Media parameters must
match the emitted text/markdown; charset=utf-8 representation. The legacy
text/x-markdown type is distinct and does not opt a client into text/markdown.
Negotiated responses inherit the page's cache policy unless markdown.cacheControl
explicitly overrides it. The override also applies to generated direct companions and
known static companions served through the edge helpers; application HTML, redirects and
unlisted assets keep their own policy. It replaces the policy of successful (2xx) and
304 responses only: Markdown rendered from an error page keeps that page's policy. Omission preserves inherited behavior. Vercel's
helper performs an anonymous, bounded companion HEAD before a rewrite or negotiation
redirect and falls back to HTML if the asset is missing or unavailable. These helpers
are tested locally, not as deployed-provider verification.
Negotiated responses merge Vary: Accept, use a
full SHA-256 ETag, and support HEAD and If-None-Match. A 304 avoids response
bytes but currently still calculates the Markdown representation. A source 304 is
re-evaluated with a sanitized GET only when Markdown is strictly preferred; otherwise
it passes through unchanged. Redirects, API responses, negotiated error pages, and
204/205 responses retain the application's original behavior.
Astro 7.3's memoryCache() skips caching a response that carries Vary: Cookie or
Vary: *. Negotiated responses vary on Accept, so they stay cacheable; a drop in
hit rate comes from cookie-varying responses your own site emits, not from
content negotiation.
An explicit .md request may convert an HTML error body while preserving its status.
Encoded and partial (206) HTML responses are not transformed.
This applies to on-demand routes only. Astro does not expose request headers to
a prerendered route, deliberately: those pages become static files, so honouring a
request header would work in astro dev and then silently stop working once
deployed. A project with no adapter prerenders everything and cannot negotiate
anywhere, and Astro-AEO warns if you configure it there. The .md companions are
unaffected and work on any hosting. A fully static site can still negotiate in its host's
edge layer: see Static edge negotiation.
Extraction
markdown.extraction.selectors decides which part of a rendered page becomes
Markdown. Selectors are tried in order and the first one with any match wins, so the
default prefers a semantic <article> and falls back to <main>. If a page has
several top-level matches they are all converted, in document order; a match nested
inside another match is skipped so its content is not emitted twice. With no match,
extraction falls back to <body>.
Matches that repeat as items of one list are a listing, not the page: a grid of
<article> cards, or a <ul> whose <li> items each hold one. They are set aside, so a
blog index or a pricing page converts from <main> with its heading and intro, and a
post keeps only its own <article> when related-post cards follow it. A card still
counts as an item inside a wrapper that holds nothing else, such as its own grid cell.
If only list items match every selector, extraction falls back to <body>.
script, style, noscript, iframe, and head are always dropped, in addition to
removeSelectors. keepSelectors emits matching elements as minimized raw HTML instead of
converting them, for a widget whose markup carries meaning. It removes presentation
attributes and bare div/span wrappers, including on a selected root. Removal wins over
keeping, and the always-dropped tags can never be reintroduced this way.
Buttons (except disclosure toggles with aria-expanded or aria-controls), svg,
template, [hidden], and [aria-hidden="true"] elements are dropped as interface
chrome, unless they wrap an image with alt text. One exception keeps meaningful glyphs: an inline
aria-hidden="true" element with no child elements, outside links, buttons, summary, label,
pre, and code, is unwrapped to its text when that text is either a separator of at most four
characters (arrows, middle dots and bullets, bars and slashes, dashes, guillemets and angle
quotes, colons) with text on both sides in the same inline run, or a box-drawing tree prefix
(such as ├──) with text after it. A separator is padded with spaces; a tree prefix is kept
verbatim; an arrow directly after a link stays dropped. Emoji, stars, and check marks are never
kept, since they usually repeat visually hidden text.
Inactive role="tabpanel" content survives hidden and aria-hidden="true", including
nested panels and their images. Only the panel's own hiding is ignored: unrelated hidden
chrome and hidden descendants still follow the cleanup rules, and explicit removals win.
Figures keep their shown images followed by the caption in emphasis. Alternate states of one
subject (images hidden from assistive technology, [hidden], Starlight's light:sl-hidden, or a
hidden image shown only in dark mode) are dropped while a shown image remains, so both images of
a before/after comparison survive and adjacent labels are separated by a space. Code blocks become
fences whose language comes from a language-* or lang-* class, a data-language attribute on
the pre or code, or a filename at the start of a figure caption holding one code block; emit
data-language if your highlighter puts the language anywhere else. Image-free charts retain readable text or their accessible label.
Definition lists become a
bold term followed by its description, and tables whose cells are single-span inline
content become GFM pipe tables. time, address, and cite convert to their text.
Tables with colspan, rowspan, or block content in a cell, and audio and video,
stay HTML because Markdown cannot express them; that HTML keeps only meaningful
attributes (href, src, alt, title, scope, colspan, rowspan, headers,
datetime, lang, aria-label, poster, type) and drops bare div and span
wrappers. Empty links and images inherit accessible names from alt, aria-label,
aria-labelledby, then title.
astro-aeo audit reports markdown-html-residue for layout markup or presentation
attributes. It separately reports markdown-raw-html when at least three non-code
Markdown blocks contain HTML and either the companion contains 30 or more HTML tags,
or tag markup exceeds 25% of the non-code Markdown. A single necessary complex table
does not trigger the volume warning.
Selector options must be arrays. A non-array value, invalid selector, or empty selector string is a configuration error, not a silent no-op; an empty array is valid.
markdown: {
extraction: {
selectors: ['[data-content]', 'article', 'main'],
removeSelectors: ['nav', 'footer', '.sidebar', '.cookie-banner'],
keepSelectors: ['.pricing-table'],
},
}Relative links and image sources in the extracted content are rewritten against the
page's own canonical URL, because a .md companion is usually read away from the site
that served it. Fragment links and non-navigational schemes (mailto:, tel:) are
left exactly as authored.
Rendered ARIA tabs become labelled Markdown sections, including inactive panels and Starlight tabs whose source conversion falls back to HTML. Panels retain their document order. Unrelated hidden interface content and explicitly removed elements remain excluded.
The same extractor is available to integrations and tooling without importing Turndown directly:
import { extractHtml } from 'astro-aeo/extract';
const { markdown, diagnostics } = await extractHtml(html, {
selectors: ['article', 'main'],
}, { baseUrl: 'https://example.com/page/' });Markdown renderers and optional adapters
markdown.renderers extends source-aware Markdown generation. Importable modules default-export
{ name, apiVersion: 1, render } and receive immutable page, source, and rendered-HTML input plus
strict JSON options. A renderer can return Markdown, decline, continue with diagnostics, or request
immediate rendered-HTML fallback. Errors diagnose and continue, so a renderer cannot break project
HTML. Inline renderer functions are accepted only for fully prerendered builds.
Astro-AEO also ships two opt-in adapters. Installing an optional peer alone changes nothing:
aeo({
markdown: {
renderers: [
{
module: 'astro-aeo/mdx',
options: {
components: {
Callout: { action: 'element', name: 'aside' },
Wrapper: { action: 'unwrap' },
InteractiveDemo: { action: 'omit' },
},
},
},
{ module: 'astro-aeo/defuddle' },
],
},
});astro-aeo/mdx requires optional peer @mdx-js/mdx. It parses but never evaluates MDX, removes
ESM, and accepts JSON-only component mappings. Expressions or unsupported semantic JSX fall back
to the already-rendered HTML. astro-aeo/defuddle requires optional peer defuddle; it processes
only local rendered HTML, forces synchronous mode, blocks fetching, and returns cleaned HTML to
Astro-AEO's core Turndown converter. Missing optional peers warn and retain normal extraction.
Sections
corpus.index.sections groups pages in llms.txt. Each rule has a title and a match that is a glob string, an array of globs, a RegExp, or a predicate (page) => boolean. Rules are evaluated in order, first match wins. Empty sections are dropped. Pages matching no rule fall into defaultSection.
On a multilingual site, path rules are evaluated against the locale-relative pathname: a page grouped under locale de and served at /de/blog/post is matched as /blog/post, so one rule such as /blog/** applies inside every locale. Write rules without the locale prefix. A predicate still receives the page with its full pathname, plus page.locale: the locale the page is grouped under, or null or absent without i18n.
corpus: {
index: {
sections: [
{ title: 'Home', match: '/' },
{ title: 'Guides', match: '/guides/**' },
{ title: 'Blog', match: /^\/\d{4}\/[^/]+$/ },
],
defaultSection: 'Pages',
},
}Globs are segment-aware: * stays inside one path segment, ** crosses segments and matches the base (/blog/** matches /blog and /blog/post). /error matches /error but not /error-log.
Crawler identity snapshot
Crawler registry version 2 separates observable User-Agent claims from robots control tokens. Default robots policy keeps its existing tokens and ordering. The observable registry adds Applebot and Amazon's Amzn-SearchBot and Amzn-User, checked against first-party operator documentation on 2026-10-03. Google-Extended and Applebot-Extended are policy controls, not observable crawler identities. A User-Agent token is a claim, not operator authentication. Meta's existing entry retains its prior verification date because its first-party page could not be retrieved during this review; no new Meta identity is inferred from third-party descriptions.
Private RAG records
Enable corpus.rag: { enabled: true, maxTokens: 512, publish: false } to write private
page and heading-aware chunk records under .astro/aeo-cache/rag-v1/. The index identifies
locale/version files, their hashes, the shared snapshot/trace build digest, and build-time
incompleteness. Every file uses mode 0600. Unlike sanitized evidence, these exports contain
published Markdown text. Held MDX bodies and rendered HTML never enter the records.
Records need absolute canonical URLs, so RAG requires a configured Astro site. Without one,
the build reports corpus-rag-origin-missing and plans the other corpus families without RAG.
Set publish: true explicitly to generate ownership-managed /llms/rag.jsonl artifacts.
Global, locale, combined and automatic layouts follow the corpus topology, including archive
prefixes below locale prefixes and the Astro base. Enabled static gzip adds deterministic siblings;
runtime uses transport compression. Public JSONL uses application/x-ndjson; charset=utf-8.
On-demand inventories generate complete public exports at request time, subject to the same
live-corpus compatibility and completeness limits. Their private build index declares
buildTimeIncomplete: true, even when it contains no records.
Records expose stable page/chunk IDs, published text, actual tokenizer counts, approximation and
fallback identity, content/page hashes, headings, oversized status and flat metadata. The chunk
budget counts complete candidate text, including non-additive custom counters. Indivisible blocks,
fences and headings attached to their first block remain whole, with rag-chunk-over-budget
when necessary. Page records are complete and not subject to the chunk budget. RAG respects
indexing, corpus and locale-fallback exclusions, but does not inherit full.mode truncation.
rag:record hooks may drop one record or replace it to enrich flat metadata. Identity, URL/locale/
version topology, text, headings, and measurements stay immutable. Use page:transform for text
changes before tokenization. Invalid replacements and isolation withhold the export; only explicitly
recoverable thrown exceptions keep the last valid record. Hooks receive a complete tokenizer plan. A custom counter failure on replacement metadata
restarts every family/version with the fallback counter and revalidates hooks.
Exported schemas are astro-aeo/rag-record.schema.json and astro-aeo/rag-index.schema.json;
root declarations expose RagRecordV1 and RagIndexV1.
See RAG ingestion examples for LangChain and LlamaIndex mappings without adding framework dependencies to Astro-AEO.
Small corpora, chunks, manifests, and gzip
corpus.small builds a strict token-budgeted llms-small.txt from contiguous leading source
blocks. It uses stable round-robin allocation across locales, sections, and pages, counts wrappers
against the limit, and never summarizes or rewrites content. A page cut short by the budget is
reported as small-corpus-truncated with severity info, since that is the budget working; a page
whose first block does not fit (small-corpus-first-block-omitted) is a warning. corpus.chunks
splits full-corpus content at page, heading, paragraph, and fenced-code boundaries. Fences remain
indivisible and an oversized unit is emitted with a diagnostic rather than silently truncated.
Consecutive headings stay with their first content block. A complete heading section moves to
a fresh chunk when it fits there but not in the current chunk; trailing headings never form
an orphan chunk. Small-corpus allocation uses the same indivisible units.
The built-in astro-aeo-approx@1 counter is deterministic and explicitly approximate. A custom
local tokenizer module must default-export API version 1 with stable name, `vers
