mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-25 01:33:41 +00:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a9f9ba6269 | |||
| eb6d3f85bb | |||
| 6d056cdd76 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Split llms.txt into per-section and per-page indexes when it exceeds 100,000 characters, and point pages to their llms.txt with a `describedby` link header.
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@/app/utils';
|
||||
import { serveLLMsTxt } from '@/routes/llms';
|
||||
|
||||
export const dynamic = 'force-static';
|
||||
|
||||
export async function GET(_request: NextRequest, { params }: { params: Promise<RouteParams> }) {
|
||||
const { context } = await getStaticSiteContext(await params);
|
||||
const pathname = getPagePathFromParams(await params);
|
||||
|
||||
return serveLLMsTxt(context, pathname);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
import { type LLMsIndexFile, type LLMsIndexNode, renderLLMsIndex } from './llms-index';
|
||||
|
||||
const ROOT = 'https://docs.example.com/llms.txt';
|
||||
|
||||
function page(path: string, children: LLMsIndexNode[] = []): LLMsIndexNode {
|
||||
return {
|
||||
kind: 'page',
|
||||
title: `Page ${path}`,
|
||||
description: `About ${path}`,
|
||||
url: `https://docs.example.com/${path}.md`,
|
||||
indexURL: `https://docs.example.com/${path}/llms.txt`,
|
||||
children,
|
||||
};
|
||||
}
|
||||
|
||||
function section(path: string, children: LLMsIndexNode[], indexURL?: string): LLMsIndexNode {
|
||||
return {
|
||||
kind: 'structure',
|
||||
title: `Section ${path}`,
|
||||
indexURL: indexURL ?? `https://docs.example.com/${path}/llms.txt`,
|
||||
children,
|
||||
};
|
||||
}
|
||||
|
||||
function pages(prefix: string, count: number): LLMsIndexNode[] {
|
||||
return Array.from({ length: count }, (_, index) => page(`${prefix}/page-${index}`));
|
||||
}
|
||||
|
||||
function file(nodes: LLMsIndexNode[], footer?: string): LLMsIndexFile {
|
||||
return { title: 'Docs', url: ROOT, nodes, footer };
|
||||
}
|
||||
|
||||
describe('renderLLMsIndex', () => {
|
||||
it('renders everything inline when it fits', () => {
|
||||
const output = renderLLMsIndex(
|
||||
file([section('guides', [page('guides/start', [page('guides/start/install')])])])
|
||||
);
|
||||
|
||||
expect(output).toBe(
|
||||
[
|
||||
'# Docs',
|
||||
'',
|
||||
'## Section guides',
|
||||
'',
|
||||
'- [Page guides/start](https://docs.example.com/guides/start.md): About guides/start',
|
||||
' - [Page guides/start/install](https://docs.example.com/guides/start/install.md): About guides/start/install',
|
||||
'',
|
||||
].join('\n')
|
||||
);
|
||||
});
|
||||
|
||||
it('splits out the largest sections first', () => {
|
||||
const output = renderLLMsIndex(
|
||||
file([section('small', pages('small', 2)), section('large', pages('large', 50))]),
|
||||
3_000
|
||||
);
|
||||
|
||||
expect(output.length).toBeLessThanOrEqual(3_000);
|
||||
expect(output).toContain('## Section small');
|
||||
expect(output).toContain('Page small/page-1');
|
||||
expect(output).toContain(
|
||||
'## Section large\n\n- [Section large](https://docs.example.com/large/llms.txt)'
|
||||
);
|
||||
expect(output).not.toContain('Page large/page-1');
|
||||
});
|
||||
|
||||
it('never links a node to the file it is rendered in', () => {
|
||||
const output = renderLLMsIndex(
|
||||
file([section('default', [page('a', pages('a', 30)), page('b', pages('b', 5))], ROOT)]),
|
||||
2_000
|
||||
);
|
||||
|
||||
expect(output.length).toBeLessThanOrEqual(2_000);
|
||||
expect(output).toContain('## Section default');
|
||||
expect(output).toContain('- [Page a](https://docs.example.com/a.md): About a');
|
||||
expect(output).toContain(' - [Pages under Page a](https://docs.example.com/a/llms.txt)');
|
||||
expect(output).not.toContain(ROOT);
|
||||
});
|
||||
|
||||
it('serves an oversized index when nothing can be split out', () => {
|
||||
const output = renderLLMsIndex(file(pages('flat', 50)), 1_000);
|
||||
|
||||
expect(output.length).toBeGreaterThan(1_000);
|
||||
expect(output).toContain('Page flat/page-49');
|
||||
});
|
||||
|
||||
it('counts the footer in the size', () => {
|
||||
const nodes = [section('a', pages('a', 10)), section('b', pages('b', 10))];
|
||||
const withoutFooter = renderLLMsIndex(file(nodes), 2_000);
|
||||
const withFooter = renderLLMsIndex(file(nodes, 'x'.repeat(1_000)), 2_000);
|
||||
|
||||
expect(withoutFooter).toContain('Page a/page-1');
|
||||
expect(withFooter.length).toBeLessThanOrEqual(2_000);
|
||||
expect(withFooter).toContain('- [Section a](https://docs.example.com/a/llms.txt)');
|
||||
});
|
||||
|
||||
it('fits large sites within the default limit', () => {
|
||||
const nodes = Array.from({ length: 20 }, (_, sectionIndex) =>
|
||||
section(
|
||||
`s${sectionIndex}`,
|
||||
Array.from({ length: 20 }, (_, groupIndex) =>
|
||||
page(
|
||||
`s${sectionIndex}/g${groupIndex}`,
|
||||
pages(`s${sectionIndex}/g${groupIndex}`, 10)
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const output = renderLLMsIndex(file(nodes));
|
||||
expect(output.length).toBeLessThanOrEqual(100_000);
|
||||
});
|
||||
|
||||
it('keeps an index that fits just under the limit whole', () => {
|
||||
const nodes = [
|
||||
section(
|
||||
's',
|
||||
Array.from({ length: 700 }, (_, index) =>
|
||||
page(`s/g${index}`, [page(`s/g${index}/a`)])
|
||||
)
|
||||
),
|
||||
];
|
||||
const full = renderLLMsIndex(file(nodes), Number.POSITIVE_INFINITY);
|
||||
|
||||
expect(full.length).toBeGreaterThan(95_000);
|
||||
expect(full.length).toBeLessThanOrEqual(100_000);
|
||||
expect(renderLLMsIndex(file(nodes))).toBe(full);
|
||||
});
|
||||
|
||||
it('writes every list line as a link, as llms.txt parsers expect', () => {
|
||||
const group: LLMsIndexNode = {
|
||||
kind: 'page',
|
||||
title: 'Get started',
|
||||
indexURL: 'https://docs.example.com/get-started/llms.txt',
|
||||
children: [page('get-started/install')],
|
||||
};
|
||||
const output = renderLLMsIndex(
|
||||
file([
|
||||
{ ...section('guides', [group]), description: 'Guides for everyone' },
|
||||
section('large', pages('large', 50)),
|
||||
]),
|
||||
3_000
|
||||
);
|
||||
|
||||
expect(output).toContain('- [Get started](https://docs.example.com/get-started/llms.txt)');
|
||||
// Same rule as the reference parser: every non-empty line under a `##` heading is a link.
|
||||
const sections = output.split(/^##\s*.*$/m).slice(1);
|
||||
for (const line of sections.flatMap((text) => text.split('\n'))) {
|
||||
if (line.trim() && !line.startsWith('#')) {
|
||||
expect(line).toMatch(/-\s*\[[^\]]+\]\([^)]+\)/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('splits sites with many sibling groups in linear time', () => {
|
||||
const nodes = Array.from({ length: 8_000 }, (_, index) =>
|
||||
page(`g${index}`, [page(`g${index}/a`), page(`g${index}/b`)])
|
||||
);
|
||||
|
||||
const started = performance.now();
|
||||
const output = renderLLMsIndex(file(nodes));
|
||||
|
||||
// Too many groups to ever fit, so every group ends up split out.
|
||||
expect(output).toContain(
|
||||
'- [Pages under Page g7999](https://docs.example.com/g7999/llms.txt)'
|
||||
);
|
||||
// About 0.4s locally; the quadratic version took several seconds.
|
||||
expect(performance.now() - started).toBeLessThan(3_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,374 @@
|
||||
import type { Heading, List, ListItem, Paragraph, Root, RootContent } from 'mdast';
|
||||
import { toMarkdown } from 'mdast-util-to-markdown';
|
||||
|
||||
/**
|
||||
* Agents truncate or skip llms.txt files past this size, so larger indexes are split into
|
||||
* scoped child files (see https://llmstxt.org/ on files at subpaths).
|
||||
*/
|
||||
export const LLMS_TXT_MAX_CHARACTERS = 100_000;
|
||||
|
||||
export type LLMsIndexNode = {
|
||||
/** A navigation level (section group, section, site space) rendered as a heading, or a page rendered as a list item. */
|
||||
kind: 'structure' | 'page';
|
||||
title: string;
|
||||
description?: string;
|
||||
/** Markdown URL of the page itself. */
|
||||
url?: string;
|
||||
/** URL of the llms.txt scoped to this node, when it can be split out. */
|
||||
indexURL?: string;
|
||||
children: LLMsIndexNode[];
|
||||
};
|
||||
|
||||
export type LLMsIndexFile = {
|
||||
title: string;
|
||||
/** Rendered as the summary blockquote below the title. */
|
||||
summary?: string;
|
||||
/** URL this file is served at, so nodes sharing it are never collapsed into a link to itself. */
|
||||
url: string;
|
||||
nodes: LLMsIndexNode[];
|
||||
/** Appended after the index, and counted in its size. */
|
||||
footer?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Render an llms.txt index, collapsing the nodes that save the most space into links to
|
||||
* their own llms.txt until the file fits within the limit.
|
||||
*/
|
||||
export function renderLLMsIndex(
|
||||
file: LLMsIndexFile,
|
||||
limit: number = LLMS_TXT_MAX_CHARACTERS
|
||||
): string {
|
||||
const collapsed = new Set<LLMsIndexNode>();
|
||||
let output = renderFile(file, collapsed);
|
||||
if (output.length <= limit) {
|
||||
return output;
|
||||
}
|
||||
|
||||
const parents = new Map<LLMsIndexNode, LLMsIndexNode>();
|
||||
const sizes = new Map<LLMsIndexNode, number>();
|
||||
const collapsedSizes = new Map<LLMsIndexNode, number>();
|
||||
const versions = new Map<LLMsIndexNode, number>();
|
||||
const orders = new Map<LLMsIndexNode, number>();
|
||||
// Ties go to the node that comes first in the file.
|
||||
const queue = new MaxHeap<QueueEntry>((a, b) => a.saving - b.saving || b.order - a.order);
|
||||
|
||||
const enqueue = (node: LLMsIndexNode) => {
|
||||
if (!collapsedSizes.has(node)) {
|
||||
return;
|
||||
}
|
||||
queue.push({
|
||||
node,
|
||||
order: orders.get(node)!,
|
||||
version: versions.get(node) ?? 0,
|
||||
saving: sizes.get(node)! - collapsedSizes.get(node)!,
|
||||
});
|
||||
};
|
||||
|
||||
const measure = (node: LLMsIndexNode, position: Position): number => {
|
||||
const childPosition: Position =
|
||||
node.kind === 'structure'
|
||||
? { headingDepth: position.headingDepth + 1, listDepth: 0 }
|
||||
: { headingDepth: position.headingDepth, listDepth: position.listDepth + 1 };
|
||||
orders.set(node, orders.size);
|
||||
let size = measureNode(node, position, false);
|
||||
for (const child of node.children) {
|
||||
parents.set(child, node);
|
||||
size += measure(child, childPosition);
|
||||
}
|
||||
sizes.set(node, size);
|
||||
// A node sharing this file's URL would collapse into a link to the file itself.
|
||||
if (node.indexURL && node.indexURL !== file.url && node.children.length > 0) {
|
||||
collapsedSizes.set(node, measureNode(node, position, true));
|
||||
enqueue(node);
|
||||
}
|
||||
return size;
|
||||
};
|
||||
for (const node of file.nodes) {
|
||||
measure(node, { headingDepth: 2, listDepth: 0 });
|
||||
}
|
||||
|
||||
// Savings are estimates; the total starts from the exact render and is corrected by each
|
||||
// render that turns out larger than estimated.
|
||||
let total = output.length;
|
||||
while (true) {
|
||||
const entry = queue.pop();
|
||||
if (!entry) {
|
||||
// Nothing left to split out: serve the smallest index we can build.
|
||||
return renderFile(file, collapsed);
|
||||
}
|
||||
const { node } = entry;
|
||||
if (
|
||||
entry.saving <= 0 ||
|
||||
collapsed.has(node) ||
|
||||
entry.version !== (versions.get(node) ?? 0) ||
|
||||
hasCollapsedAncestor(node, parents, collapsed)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
collapsed.add(node);
|
||||
total -= entry.saving;
|
||||
for (let parent = parents.get(node); parent; parent = parents.get(parent)) {
|
||||
sizes.set(parent, sizes.get(parent)! - entry.saving);
|
||||
versions.set(parent, (versions.get(parent) ?? 0) + 1);
|
||||
enqueue(parent);
|
||||
}
|
||||
|
||||
if (total <= limit) {
|
||||
output = renderFile(file, collapsed);
|
||||
if (output.length <= limit) {
|
||||
return output;
|
||||
}
|
||||
total = output.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Position = { headingDepth: number; listDepth: number };
|
||||
|
||||
type QueueEntry = { node: LLMsIndexNode; order: number; version: number; saving: number };
|
||||
|
||||
function hasCollapsedAncestor(
|
||||
node: LLMsIndexNode,
|
||||
parents: Map<LLMsIndexNode, LLMsIndexNode>,
|
||||
collapsed: Set<LLMsIndexNode>
|
||||
): boolean {
|
||||
for (let parent = parents.get(node); parent; parent = parents.get(parent)) {
|
||||
if (collapsed.has(parent)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Approximate the characters a node adds on its own, excluding its children.
|
||||
*/
|
||||
function measureNode(node: LLMsIndexNode, position: Position, asCollapsed: boolean): number {
|
||||
const blocks =
|
||||
node.kind === 'structure'
|
||||
? asCollapsed
|
||||
? toCollapsedStructureBlocks(node, position.headingDepth)
|
||||
: toStructureBlocks(node, position.headingDepth, new Set(), false)
|
||||
: [toList([asCollapsed ? toCollapsedItem(node) : toPageItem(node, new Set(), false)])];
|
||||
const markdown = toMarkdown({ type: 'root', children: blocks }, { bullet: '-' });
|
||||
// In the file, blocks are separated by a blank line and nested list items are indented.
|
||||
const lines = markdown.split('\n').length - 1;
|
||||
return (
|
||||
markdown.length +
|
||||
(node.kind === 'structure' ? blocks.length : lines * 2 * position.listDepth)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Binary heap returning the largest entry first.
|
||||
*/
|
||||
class MaxHeap<T> {
|
||||
private items: T[] = [];
|
||||
|
||||
constructor(private compare: (a: T, b: T) => number) {}
|
||||
|
||||
push(item: T) {
|
||||
const items = this.items;
|
||||
items.push(item);
|
||||
let index = items.length - 1;
|
||||
while (index > 0) {
|
||||
const parent = (index - 1) >> 1;
|
||||
if (this.compare(items[index]!, items[parent]!) <= 0) {
|
||||
break;
|
||||
}
|
||||
[items[index], items[parent]] = [items[parent]!, items[index]!];
|
||||
index = parent;
|
||||
}
|
||||
}
|
||||
|
||||
pop(): T | undefined {
|
||||
const items = this.items;
|
||||
const top = items[0];
|
||||
const last = items.pop();
|
||||
if (items.length > 0 && last !== undefined) {
|
||||
items[0] = last;
|
||||
let index = 0;
|
||||
while (true) {
|
||||
const left = index * 2 + 1;
|
||||
const right = left + 1;
|
||||
let largest = index;
|
||||
if (left < items.length && this.compare(items[left]!, items[largest]!) > 0) {
|
||||
largest = left;
|
||||
}
|
||||
if (right < items.length && this.compare(items[right]!, items[largest]!) > 0) {
|
||||
largest = right;
|
||||
}
|
||||
if (largest === index) {
|
||||
break;
|
||||
}
|
||||
[items[index], items[largest]] = [items[largest]!, items[index]!];
|
||||
index = largest;
|
||||
}
|
||||
}
|
||||
return top;
|
||||
}
|
||||
}
|
||||
|
||||
function renderFile(file: LLMsIndexFile, collapsed: Set<LLMsIndexNode>): string {
|
||||
const tree: Root = {
|
||||
type: 'root',
|
||||
children: [
|
||||
{ type: 'heading', depth: 1, children: [{ type: 'text', value: file.title }] },
|
||||
...(file.summary
|
||||
? [
|
||||
{
|
||||
type: 'blockquote' as const,
|
||||
children: [toParagraph(file.summary)],
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...toBlocks(file.nodes, 2, collapsed),
|
||||
],
|
||||
};
|
||||
|
||||
let output = toMarkdown(tree, { bullet: '-' });
|
||||
if (file.footer) {
|
||||
output += `\n\n---\n\n${file.footer}`;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render sibling nodes, grouping consecutive list items into a single list.
|
||||
*/
|
||||
function toBlocks(
|
||||
nodes: LLMsIndexNode[],
|
||||
depth: number,
|
||||
collapsed: Set<LLMsIndexNode>
|
||||
): RootContent[] {
|
||||
const blocks: RootContent[] = [];
|
||||
let items: ListItem[] = [];
|
||||
const flush = () => {
|
||||
if (items.length > 0) {
|
||||
blocks.push(toList(items));
|
||||
items = [];
|
||||
}
|
||||
};
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.kind === 'structure') {
|
||||
flush();
|
||||
blocks.push(
|
||||
...(collapsed.has(node)
|
||||
? toCollapsedStructureBlocks(node, depth)
|
||||
: toStructureBlocks(node, depth, collapsed, true))
|
||||
);
|
||||
} else if (collapsed.has(node)) {
|
||||
items.push(toCollapsedItem(node));
|
||||
} else {
|
||||
items.push(toPageItem(node, collapsed, true));
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function toStructureBlocks(
|
||||
node: LLMsIndexNode,
|
||||
depth: number,
|
||||
collapsed: Set<LLMsIndexNode>,
|
||||
withChildren: boolean
|
||||
): RootContent[] {
|
||||
return [
|
||||
{
|
||||
type: 'heading',
|
||||
depth: Math.min(depth, 6) as Heading['depth'],
|
||||
children: [{ type: 'text', value: node.title }],
|
||||
},
|
||||
...(withChildren ? toBlocks(node.children, depth + 1, collapsed) : []),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the heading so the link isn't read as part of the previous section's list.
|
||||
*/
|
||||
function toCollapsedStructureBlocks(node: LLMsIndexNode, depth: number): RootContent[] {
|
||||
return [
|
||||
{
|
||||
type: 'heading',
|
||||
depth: Math.min(depth, 6) as Heading['depth'],
|
||||
children: [{ type: 'text', value: node.title }],
|
||||
},
|
||||
toList([toCollapsedItem(node)]),
|
||||
];
|
||||
}
|
||||
|
||||
function toPageItem(
|
||||
node: LLMsIndexNode,
|
||||
collapsed: Set<LLMsIndexNode>,
|
||||
withChildren: boolean
|
||||
): ListItem {
|
||||
// Parsers expect every list line to be a link, so groups link to their own index.
|
||||
const children: ListItem['children'] = [toLinkParagraph(node, node.url ?? node.indexURL)];
|
||||
if (withChildren && node.children.length > 0) {
|
||||
children.push(
|
||||
toList(
|
||||
node.children.map((child) =>
|
||||
collapsed.has(child)
|
||||
? toCollapsedItem(child)
|
||||
: toPageItem(child, collapsed, true)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
return { type: 'listItem', spread: false, children };
|
||||
}
|
||||
|
||||
/**
|
||||
* A page that is also a document keeps its own link, with its subtree moved to its index.
|
||||
*/
|
||||
function toCollapsedItem(node: LLMsIndexNode): ListItem {
|
||||
if (node.kind === 'page' && node.url) {
|
||||
return {
|
||||
type: 'listItem',
|
||||
spread: false,
|
||||
children: [
|
||||
toLinkParagraph(node, node.url),
|
||||
toList([
|
||||
{
|
||||
type: 'listItem',
|
||||
spread: false,
|
||||
children: [
|
||||
toLinkParagraph({ title: `Pages under ${node.title}` }, node.indexURL),
|
||||
],
|
||||
},
|
||||
]),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'listItem',
|
||||
spread: false,
|
||||
children: [toLinkParagraph(node, node.indexURL)],
|
||||
};
|
||||
}
|
||||
|
||||
function toLinkParagraph(
|
||||
node: Pick<LLMsIndexNode, 'title' | 'description'>,
|
||||
url: string | undefined
|
||||
): Paragraph {
|
||||
const children: Paragraph['children'] = [
|
||||
url
|
||||
? { type: 'link', url, children: [{ type: 'text', value: node.title }] }
|
||||
: { type: 'text', value: node.title },
|
||||
];
|
||||
if (node.description) {
|
||||
children.push({ type: 'text', value: `: ${node.description}` });
|
||||
}
|
||||
return { type: 'paragraph', children };
|
||||
}
|
||||
|
||||
function toParagraph(value: string): Paragraph {
|
||||
return { type: 'paragraph', children: [{ type: 'text', value }] };
|
||||
}
|
||||
|
||||
function toList(children: ListItem[]): List {
|
||||
return { type: 'list', spread: false, children };
|
||||
}
|
||||
@@ -47,3 +47,30 @@ function flattenPages(
|
||||
export function getIndexablePages(rootPages: RevisionPage[]) {
|
||||
return flattenPages(rootPages, (page, ancestors) => isPageIndexable(ancestors, page));
|
||||
}
|
||||
|
||||
export type PageTreeEntry = {
|
||||
page: RevisionPageDocument | RevisionPageGroup;
|
||||
children: PageTreeEntry[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Get all indexable pages from a revision as a tree, keeping groups that contain indexable pages.
|
||||
*/
|
||||
export function getIndexablePageTree(
|
||||
rootPages: RevisionPage[],
|
||||
ancestors: (RevisionPageDocument | RevisionPageGroup)[] = []
|
||||
): PageTreeEntry[] {
|
||||
return rootPages.flatMap((page): PageTreeEntry[] => {
|
||||
if (page.type !== 'document' && page.type !== 'group') {
|
||||
return [];
|
||||
}
|
||||
if (!isPageIndexable(ancestors, page)) {
|
||||
return [];
|
||||
}
|
||||
const children = getIndexablePageTree(page.pages, [...ancestors, page]);
|
||||
if (page.type === 'group' && children.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return [{ page, children }];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ import {
|
||||
isOAuthProtectedResourceMetadataRequestForAuthEndpoint,
|
||||
isOAuthProtectedResourceRequest,
|
||||
} from '@/lib/oauth-protected';
|
||||
import { removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
|
||||
import { removeLeadingSlash, removeTrailingSlash, withTrailingSlash } from '@/lib/paths';
|
||||
import {
|
||||
getPreviewCookieResponse,
|
||||
getPreviewRequestIdentifier,
|
||||
@@ -496,6 +496,7 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
events,
|
||||
isAiAgent,
|
||||
askVisitorAgent,
|
||||
isPage,
|
||||
} = encodePathInSiteContent(siteURLData, request);
|
||||
routeType = routeTypeFromPathname ?? routeType;
|
||||
// Only set for markdown routes, so it becomes part of their static cache key.
|
||||
@@ -609,6 +610,14 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
|
||||
}
|
||||
|
||||
// AI related headers
|
||||
if (isPage) {
|
||||
// Point agents to the most specific llms.txt that is always served for this page.
|
||||
const llmsTxtURL = new URL(
|
||||
'llms.txt',
|
||||
`${siteCanonicalURL.origin}${withTrailingSlash(siteURLData.basePath)}`
|
||||
);
|
||||
response.headers.append('link', `<${llmsTxtURL.toString()}>; rel="describedby"`);
|
||||
}
|
||||
// This one is technically useless, but is used by a bunch of scoring systems
|
||||
response.headers.set(
|
||||
'vary',
|
||||
@@ -802,6 +811,7 @@ function getSiteURLFromRequest(request: NextRequest): URLWithMode | null {
|
||||
const RSS_PATH_REGEX = /^((\S+)\/)?rss\.xml$/;
|
||||
const MARKDOWN_PATH_REGEX = /\.md$/;
|
||||
const LLMS_FULL_PATH_REGEX = /^llms-full\.txt\/\d+$/;
|
||||
const PAGE_LLMS_PATH_REGEX = /^(\S+)\/llms\.txt$/;
|
||||
const EMBED_PAGE_PATH_REGEX = /^~gitbook\/embed\/page(\/(\S*))?$/;
|
||||
const PATH_ALIASES: Record<string, string> = {
|
||||
'sitemap.md': 'llms.txt',
|
||||
@@ -847,6 +857,8 @@ function encodePathInSiteContent(
|
||||
isAiAgent?: boolean;
|
||||
/** Only set for the ask route, where the API classifies the asker from these headers. */
|
||||
askVisitorAgent?: AskVisitorAgent;
|
||||
/** Set for pages, which are listed in the llms.txt of their site space. */
|
||||
isPage?: boolean;
|
||||
} {
|
||||
let pathname = removeLeadingSlash(removeTrailingSlash(siteURLData.pathname));
|
||||
|
||||
@@ -901,6 +913,22 @@ function encodePathInSiteContent(
|
||||
};
|
||||
}
|
||||
|
||||
// The llms.txt of a page lists the pages under it (llms.txt at the space root is handled below).
|
||||
const pageLLMsMatch = pathname.match(PAGE_LLMS_PATH_REGEX);
|
||||
if (pageLLMsMatch) {
|
||||
return {
|
||||
pathname: `~gitbook/llms/${encodePagePath(pageLLMsMatch[1])}`,
|
||||
routeType: 'static',
|
||||
events: [
|
||||
{
|
||||
type: 'llms_request',
|
||||
llmsVariant: SiteInsightsLLMSVariant.Standard,
|
||||
location: eventLocation,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// If the pathname is an embedded page
|
||||
const embedPage = pathname.match(EMBED_PAGE_PATH_REGEX);
|
||||
if (embedPage) {
|
||||
@@ -983,6 +1011,7 @@ function encodePathInSiteContent(
|
||||
}`
|
||||
: `~gitbook/markdown/${encodePagePath(pagePathWithoutMD)}`,
|
||||
routeType: 'static',
|
||||
isPage: typeof ask !== 'string',
|
||||
// Left undefined for non-agents to avoid splitting the static cache for them.
|
||||
isAiAgent: isAiAgent || undefined,
|
||||
askVisitorAgent:
|
||||
@@ -1011,7 +1040,7 @@ function encodePathInSiteContent(
|
||||
],
|
||||
};
|
||||
}
|
||||
return { pathname: encodePagePath(pathname) };
|
||||
return { pathname: encodePagePath(pathname), isPage: true };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import type { RevisionPage, SiteSection, SiteSpace, SiteStructure } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { createLinker } from '@/lib/links';
|
||||
|
||||
mock.module('server-only', () => ({}));
|
||||
|
||||
const { serveLLMsTxt } = await import('./llms');
|
||||
|
||||
function pages(prefix: string, count: number): RevisionPage[] {
|
||||
return Array.from(
|
||||
{ length: count },
|
||||
(_, index) =>
|
||||
({
|
||||
id: `${prefix}-${index}`,
|
||||
type: 'document',
|
||||
title: `${prefix} page ${index}`,
|
||||
description: 'x'.repeat(200),
|
||||
path: `${prefix}-page-${index}`,
|
||||
pages: [],
|
||||
}) as unknown as RevisionPage
|
||||
);
|
||||
}
|
||||
|
||||
function siteSpace(
|
||||
id: string,
|
||||
options: { path: string; language?: string; default?: boolean }
|
||||
): SiteSpace {
|
||||
return {
|
||||
object: 'site-space',
|
||||
id,
|
||||
title: id,
|
||||
path: options.path,
|
||||
default: options.default ?? false,
|
||||
draft: false,
|
||||
urls: { published: `https://docs.example.com/docs/${id}/` },
|
||||
space: { id: `space-${id}`, revision: `revision-${id}`, language: options.language },
|
||||
} as unknown as SiteSpace;
|
||||
}
|
||||
|
||||
function section(
|
||||
id: string,
|
||||
options: { path: string; default?: boolean; siteSpaces: SiteSpace[] }
|
||||
): SiteSection {
|
||||
return {
|
||||
object: 'site-section',
|
||||
id,
|
||||
title: id,
|
||||
path: options.path,
|
||||
default: options.default ?? false,
|
||||
draft: false,
|
||||
siteSpaces: options.siteSpaces,
|
||||
urls: {},
|
||||
} as unknown as SiteSection;
|
||||
}
|
||||
|
||||
function createRootContext(sections: SiteSection[], revisions: Record<string, RevisionPage[]>) {
|
||||
const rootSection = sections[0]!;
|
||||
const rootSiteSpace = rootSection.siteSpaces[0]!;
|
||||
const structure = { type: 'sections', structure: sections } as SiteStructure;
|
||||
|
||||
return {
|
||||
site: { id: 'site-1', title: 'Docs' },
|
||||
locale: 'en',
|
||||
structure,
|
||||
sections: { list: sections, current: rootSection },
|
||||
siteSpace: rootSiteSpace,
|
||||
siteSpaces: rootSection.siteSpaces,
|
||||
revision: { pages: revisions[rootSiteSpace.id] },
|
||||
customization: { ai: { mode: undefined } },
|
||||
linker: createLinker({
|
||||
host: 'docs.example.com',
|
||||
siteBasePath: '/docs/',
|
||||
spaceBasePath: '/docs/',
|
||||
}),
|
||||
dataFetcher: {
|
||||
getRevision: async ({ spaceId }: { spaceId: string }) => ({
|
||||
data: { pages: revisions[spaceId.replace('space-', '')] },
|
||||
}),
|
||||
},
|
||||
} as unknown as GitBookSiteContext;
|
||||
}
|
||||
|
||||
describe('serveLLMsTxt', () => {
|
||||
it('links a split-out section to the variant in the listed language', async () => {
|
||||
const context = createRootContext(
|
||||
[
|
||||
section('guides', {
|
||||
path: 'guides',
|
||||
default: true,
|
||||
siteSpaces: [siteSpace('guides-en', { path: 'en', default: true })],
|
||||
}),
|
||||
section('reference', {
|
||||
path: 'reference',
|
||||
siteSpaces: [
|
||||
siteSpace('reference-fr', { path: 'fr', language: 'fr', default: true }),
|
||||
siteSpace('reference-en', { path: 'en' }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
{
|
||||
'guides-en': pages('guides', 5),
|
||||
'reference-fr': pages('reference-fr', 5),
|
||||
'reference-en': pages('reference-en', 600),
|
||||
}
|
||||
);
|
||||
|
||||
const output = await (await serveLLMsTxt(context)).text();
|
||||
|
||||
expect(output.length).toBeLessThanOrEqual(100_000);
|
||||
expect(output).toContain('(https://docs.example.com/docs/reference/en/llms.txt)');
|
||||
expect(output).not.toContain('(https://docs.example.com/docs/reference/llms.txt)');
|
||||
});
|
||||
|
||||
it('keeps a section inline when several variants are listed without its default', async () => {
|
||||
const context = createRootContext(
|
||||
[
|
||||
section('guides', {
|
||||
path: 'guides',
|
||||
default: true,
|
||||
siteSpaces: [siteSpace('guides-en', { path: 'en', default: true })],
|
||||
}),
|
||||
section('reference', {
|
||||
path: 'reference',
|
||||
siteSpaces: [
|
||||
siteSpace('reference-fr', { path: 'fr', language: 'fr', default: true }),
|
||||
siteSpace('reference-v1', { path: 'v1' }),
|
||||
siteSpace('reference-v2', { path: 'v2' }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
{
|
||||
'guides-en': pages('guides', 5),
|
||||
'reference-fr': pages('reference-fr', 5),
|
||||
'reference-v1': pages('reference-v1', 300),
|
||||
'reference-v2': pages('reference-v2', 300),
|
||||
}
|
||||
);
|
||||
|
||||
const output = await (await serveLLMsTxt(context)).text();
|
||||
|
||||
expect(output.length).toBeLessThanOrEqual(100_000);
|
||||
expect(output).toContain('## reference');
|
||||
expect(output).toContain('/docs/reference/v1/llms.txt)');
|
||||
expect(output).not.toContain('(https://docs.example.com/docs/reference/llms.txt)');
|
||||
});
|
||||
});
|
||||
+215
-115
@@ -1,56 +1,51 @@
|
||||
import assertNever from 'assert-never';
|
||||
import type { ListItem, Paragraph, Root, RootContent } from 'mdast';
|
||||
import { toMarkdown } from 'mdast-util-to-markdown';
|
||||
import type { ListItem, Paragraph, RootContent } from 'mdast';
|
||||
|
||||
import type { SiteSection, SiteSpace } from '@gitbook/api';
|
||||
import type { RevisionPageDocument, RevisionPageGroup, SiteSection, SiteSpace } from '@gitbook/api';
|
||||
|
||||
import { renderSiteAgentInstructions } from '@/lib/ask-prompt';
|
||||
import { type GitBookSiteContext, checkIsRootSiteContext } from '@/lib/context';
|
||||
import {
|
||||
type GitBookSiteContext,
|
||||
type SiteStructureNode,
|
||||
checkIsRootSiteContext,
|
||||
} from '@/lib/context';
|
||||
import { throwIfDataError } from '@/lib/data';
|
||||
import { type GitBookLinker, linkerWithMarkdownPages } from '@/lib/links';
|
||||
import { type FlatPageEntry, getIndexablePages } from '@/lib/sitemap';
|
||||
import { type LLMsIndexNode, renderLLMsIndex } from '@/lib/llms-index';
|
||||
import { joinPath } from '@/lib/paths';
|
||||
import { type FlatPageEntry, type PageTreeEntry, getIndexablePageTree } from '@/lib/sitemap';
|
||||
import {
|
||||
filterSiteSpacesByLocale,
|
||||
getFallbackSiteSpacePath,
|
||||
getLocalizedDescription,
|
||||
getLocalizedTitle,
|
||||
getSiteStructureSections,
|
||||
resolveSiteSpacePagePathDocumentOrGroup,
|
||||
} from '@/lib/sites';
|
||||
|
||||
/**
|
||||
* Generate a llms.txt file for the site.
|
||||
* Generate the llms.txt index for the part of the site it is served under: the whole site at
|
||||
* the root, a section, a site space, or the pages under `pagePath`.
|
||||
*/
|
||||
export async function serveLLMsTxt(baseContext: GitBookSiteContext) {
|
||||
const { site } = baseContext;
|
||||
|
||||
if (!checkIsRootSiteContext(baseContext)) {
|
||||
return new Response('llms.txt is only served from the root of the site', { status: 404 });
|
||||
export async function serveLLMsTxt(context: GitBookSiteContext, pagePath?: string) {
|
||||
const index = await getLLMsIndex(context, pagePath);
|
||||
if (!index) {
|
||||
return new Response('No llms.txt for this path', { status: 404 });
|
||||
}
|
||||
|
||||
const context = {
|
||||
...baseContext,
|
||||
linker: linkerWithMarkdownPages(baseContext.linker),
|
||||
};
|
||||
|
||||
const tree: Root = {
|
||||
type: 'root',
|
||||
children: [
|
||||
{
|
||||
type: 'heading',
|
||||
depth: 1,
|
||||
children: [{ type: 'text', value: site.title }],
|
||||
},
|
||||
...(await getNodesFromSiteStructure(context)),
|
||||
],
|
||||
};
|
||||
|
||||
let output = toMarkdown(tree, {
|
||||
bullet: '-',
|
||||
});
|
||||
|
||||
const rootURL = getLLMsTxtURLForPath(context, '');
|
||||
const agentInstructions = renderSiteAgentInstructions(context);
|
||||
if (agentInstructions) {
|
||||
output += `\n\n---\n\n${agentInstructions}`;
|
||||
}
|
||||
|
||||
const output = renderLLMsIndex({
|
||||
title: index.title,
|
||||
summary:
|
||||
index.url === rootURL
|
||||
? undefined
|
||||
: `This index lists part of the site. The index for the whole site is at ${rootURL}.`,
|
||||
url: index.url,
|
||||
nodes: index.nodes,
|
||||
footer: agentInstructions,
|
||||
});
|
||||
|
||||
return new Response(output, {
|
||||
headers: {
|
||||
@@ -59,113 +54,218 @@ export async function serveLLMsTxt(baseContext: GitBookSiteContext) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get MDAST nodes from site structure.
|
||||
*/
|
||||
async function getNodesFromSiteStructure(context: GitBookSiteContext): Promise<RootContent[]> {
|
||||
async function getLLMsIndex(
|
||||
context: GitBookSiteContext,
|
||||
pagePath: string | undefined
|
||||
): Promise<{ title: string; url: string; nodes: LLMsIndexNode[] } | null> {
|
||||
const { site, siteSpace, linker } = context;
|
||||
|
||||
if (pagePath !== undefined) {
|
||||
const resolved = resolveSiteSpacePagePathDocumentOrGroup(
|
||||
siteSpace,
|
||||
context.revision.pages,
|
||||
pagePath
|
||||
);
|
||||
const entry = resolved
|
||||
? findPageTreeEntry(getIndexablePageTree(context.revision.pages), resolved.page.id)
|
||||
: null;
|
||||
if (!entry || entry.children.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const nodes = getNodesFromPageTree(entry.children, linker);
|
||||
return { title: entry.page.title, url: getPageLLMsTxtURL(linker, entry.page), nodes };
|
||||
}
|
||||
|
||||
if (checkIsRootSiteContext(context)) {
|
||||
return {
|
||||
title: site.title,
|
||||
url: getLLMsTxtURLForPath(context, ''),
|
||||
nodes: await getNodesFromSiteStructure(context),
|
||||
};
|
||||
}
|
||||
|
||||
const currentSection = context.sections?.current;
|
||||
// A section's default site space is served at the section's own path.
|
||||
if (currentSection && siteSpace.default) {
|
||||
const node = await getNodeFromSection(context, currentSection);
|
||||
return node?.indexURL
|
||||
? { title: node.title, url: node.indexURL, nodes: node.children }
|
||||
: null;
|
||||
}
|
||||
|
||||
const node = await getNodeFromSiteSpace(context, siteSpace);
|
||||
if (!node?.indexURL) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
title: currentSection
|
||||
? `${getLocalizedTitle(currentSection, context.locale)}: ${node.title}`
|
||||
: node.title,
|
||||
url: node.indexURL,
|
||||
nodes: node.children,
|
||||
};
|
||||
}
|
||||
|
||||
async function getNodesFromSiteStructure(context: GitBookSiteContext): Promise<LLMsIndexNode[]> {
|
||||
switch (context.structure.type) {
|
||||
case 'sections':
|
||||
return getNodesFromSections(
|
||||
return getNodesFromSectionNodes(
|
||||
context,
|
||||
getSiteStructureSections(context.structure, { ignoreGroups: true })
|
||||
getSiteStructureSections(context.structure, { ignoreGroups: false })
|
||||
);
|
||||
case 'siteSpaces':
|
||||
return getNodesFromSiteSpaces(context, context.structure.structure, {
|
||||
heading: true,
|
||||
});
|
||||
return getNodesFromSiteSpaces(context, context.structure.structure);
|
||||
default:
|
||||
assertNever(context.structure);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get MDAST nodes from site sections.
|
||||
*/
|
||||
async function getNodesFromSections(
|
||||
async function getNodesFromSectionNodes(
|
||||
context: GitBookSiteContext,
|
||||
siteSections: SiteSection[]
|
||||
): Promise<RootContent[]> {
|
||||
const currentLanguage = context.locale;
|
||||
const all = await Promise.all(
|
||||
siteSections.map(async (siteSection): Promise<RootContent[]> => {
|
||||
const siteSpaceNodes = await getNodesFromSiteSpaces(context, siteSection.siteSpaces, {
|
||||
heading: false,
|
||||
});
|
||||
return [
|
||||
{
|
||||
type: 'heading',
|
||||
depth: 2,
|
||||
children: [
|
||||
{ type: 'text', value: getLocalizedTitle(siteSection, currentLanguage) },
|
||||
],
|
||||
},
|
||||
...siteSpaceNodes,
|
||||
];
|
||||
sectionNodes: SiteStructureNode[]
|
||||
): Promise<LLMsIndexNode[]> {
|
||||
const nodes = await Promise.all(
|
||||
sectionNodes.map(async (sectionNode): Promise<LLMsIndexNode | null> => {
|
||||
switch (sectionNode.object) {
|
||||
case 'site-section':
|
||||
return getNodeFromSection(context, sectionNode);
|
||||
case 'site-section-group': {
|
||||
const children = await getNodesFromSectionNodes(context, sectionNode.children);
|
||||
return children.length > 0
|
||||
? {
|
||||
kind: 'structure',
|
||||
title: getLocalizedTitle(sectionNode, context.locale),
|
||||
children,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
case 'site-external-link':
|
||||
return null;
|
||||
default:
|
||||
assertNever(sectionNode);
|
||||
}
|
||||
})
|
||||
);
|
||||
return all.flat();
|
||||
return nodes.filter((node) => node !== null);
|
||||
}
|
||||
|
||||
async function getNodeFromSection(
|
||||
context: GitBookSiteContext,
|
||||
section: SiteSection
|
||||
): Promise<LLMsIndexNode | null> {
|
||||
const children = await getNodesFromSiteSpaces(context, section.siteSpaces);
|
||||
if (children.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'structure',
|
||||
title: getLocalizedTitle(section, context.locale),
|
||||
description: getLocalizedDescription(section, context.locale),
|
||||
indexURL: getSectionLLMsTxtURL(context, section),
|
||||
children,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get MDAST nodes from site spaces.
|
||||
* The section's llms.txt lists its default variant's language, so it only stands in for the
|
||||
* listed variants when they include the default one; otherwise link the single listed variant.
|
||||
*/
|
||||
function getSectionLLMsTxtURL(context: GitBookSiteContext, section: SiteSection) {
|
||||
const listed = filterSiteSpacesByLocale(section.siteSpaces, context.locale);
|
||||
const target =
|
||||
listed.find((siteSpace) => siteSpace.default) ??
|
||||
(listed.length === 1 ? listed[0] : undefined);
|
||||
return target
|
||||
? getLLMsTxtURLForPath(context, getFallbackSiteSpacePath(context, target))
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* A single site space is listed directly, without a heading of its own.
|
||||
*/
|
||||
async function getNodesFromSiteSpaces(
|
||||
context: GitBookSiteContext,
|
||||
siteSpaces: SiteSpace[],
|
||||
options: {
|
||||
/**
|
||||
* Includes a heading for each site space.
|
||||
*/
|
||||
heading?: boolean;
|
||||
siteSpaces: SiteSpace[]
|
||||
): Promise<LLMsIndexNode[]> {
|
||||
const filtered = filterSiteSpacesByLocale(siteSpaces, context.locale);
|
||||
const nodes = (
|
||||
await Promise.all(filtered.map((siteSpace) => getNodeFromSiteSpace(context, siteSpace)))
|
||||
).filter((node) => node !== null);
|
||||
|
||||
return nodes.length === 1 ? nodes[0]!.children : nodes;
|
||||
}
|
||||
|
||||
async function getNodeFromSiteSpace(
|
||||
context: GitBookSiteContext,
|
||||
siteSpace: SiteSpace
|
||||
): Promise<LLMsIndexNode | null> {
|
||||
if (!siteSpace.urls.published) {
|
||||
return null;
|
||||
}
|
||||
): Promise<RootContent[]> {
|
||||
const { dataFetcher, linker } = context;
|
||||
|
||||
const filteredSiteSpaces = filterSiteSpacesByLocale(siteSpaces, context.locale);
|
||||
const revision =
|
||||
siteSpace.id === context.siteSpace.id
|
||||
? context.revision
|
||||
: await throwIfDataError(
|
||||
context.dataFetcher.getRevision({
|
||||
spaceId: siteSpace.space.id,
|
||||
revisionId: siteSpace.space.revision,
|
||||
})
|
||||
);
|
||||
const siteSpacePath = getFallbackSiteSpacePath(context, siteSpace);
|
||||
const linker = context.linker.withOtherSiteSpace({ spaceBasePath: siteSpacePath });
|
||||
|
||||
const all = await Promise.all(
|
||||
filteredSiteSpaces.map(async (siteSpace): Promise<RootContent[]> => {
|
||||
const siteSpaceUrl = siteSpace.urls.published;
|
||||
if (!siteSpaceUrl) {
|
||||
return [];
|
||||
}
|
||||
const revision = await throwIfDataError(
|
||||
dataFetcher.getRevision({
|
||||
spaceId: siteSpace.space.id,
|
||||
revisionId: siteSpace.space.revision,
|
||||
})
|
||||
);
|
||||
const pages = getIndexablePages(revision.pages);
|
||||
return {
|
||||
kind: 'structure',
|
||||
title: getLocalizedTitle(siteSpace, context.locale),
|
||||
indexURL: getLLMsTxtURLForPath(context, siteSpacePath),
|
||||
children: getNodesFromPageTree(getIndexablePageTree(revision.pages), linker),
|
||||
};
|
||||
}
|
||||
|
||||
const nodes: RootContent[] = [];
|
||||
function getNodesFromPageTree(entries: PageTreeEntry[], linker: GitBookLinker): LLMsIndexNode[] {
|
||||
const markdownLinker = linkerWithMarkdownPages(linker);
|
||||
const toNode = ({ page, children }: PageTreeEntry): LLMsIndexNode => ({
|
||||
kind: 'page',
|
||||
title: page.title,
|
||||
description: (page.type === 'document' && page.description) || undefined,
|
||||
url:
|
||||
page.type === 'document'
|
||||
? markdownLinker.toAbsoluteURL(
|
||||
markdownLinker.toPathForPagePath({ path: page.path })
|
||||
)
|
||||
: undefined,
|
||||
indexURL: children.length > 0 ? getPageLLMsTxtURL(linker, page) : undefined,
|
||||
children: children.map(toNode),
|
||||
});
|
||||
return entries.map(toNode);
|
||||
}
|
||||
|
||||
// Add the space title as a heading
|
||||
if (options.heading) {
|
||||
nodes.push({
|
||||
type: 'heading',
|
||||
depth: 2,
|
||||
children: [
|
||||
{
|
||||
type: 'text',
|
||||
value: getLocalizedTitle(siteSpace, context.locale),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
function findPageTreeEntry(entries: PageTreeEntry[], pageId: string): PageTreeEntry | null {
|
||||
for (const entry of entries) {
|
||||
if (entry.page.id === pageId) {
|
||||
return entry;
|
||||
}
|
||||
const found = findPageTreeEntry(entry.children, pageId);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const siteSpaceLinker = linkerWithMarkdownPages(
|
||||
linker.withOtherSiteSpace({
|
||||
spaceBasePath: getFallbackSiteSpacePath(context, siteSpace),
|
||||
})
|
||||
);
|
||||
function getPageLLMsTxtURL(
|
||||
linker: GitBookLinker,
|
||||
page: RevisionPageDocument | RevisionPageGroup
|
||||
): string {
|
||||
return linker.toAbsoluteURL(linker.toPathInSpace(joinPath(page.path, 'llms.txt')));
|
||||
}
|
||||
|
||||
// Add the pages as a list
|
||||
nodes.push(...(await getMarkdownForPagesTree(pages, siteSpaceLinker)));
|
||||
|
||||
return nodes;
|
||||
})
|
||||
function getLLMsTxtURLForPath(context: GitBookSiteContext, pathInSite: string): string {
|
||||
return context.linker.toAbsoluteURL(
|
||||
context.linker.toPathInSite(joinPath(pathInSite, 'llms.txt'))
|
||||
);
|
||||
return all.flat();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user