Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion e2e/fixtures/ssg-md/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,17 @@ test('llms should be enabled by default', async () => {
path.join(docBuildDir, 'index.html'),
'utf-8',
);
const head = indexHtml.split('</head>')[0];
expect(head.match(/rel="alternate" type="text\/markdown"/g)).toHaveLength(1);
expect(head).toContain('href="https://example.com/docs/index.md"');
expect(head.match(/rel="describedby"/g)).toHaveLength(1);
expect(head).toContain('href="https://example.com/docs/llms.txt"');
const notFoundHtml = await fs.readFile(
path.join(docBuildDir, '404.html'),
'utf-8',
);
expect(notFoundHtml).not.toContain('type="text/markdown"');
expect(notFoundHtml).not.toContain('rel="describedby"');
const hintHtml = indexHtml.match(
/<div[^>]*class="rp-llms-hint"[\s\S]*?<\/div>/,
)?.[0];
Expand Down Expand Up @@ -242,6 +253,27 @@ for (const { ssg, llms, config } of [
);
expect(html.includes('<div id="__rspress_root"></div>')).toBe(!ssg);
expect(html.includes('Rspress uses')).toBe(ssg);
const componentsHtml = await fs.readFile(
path.join(docBuildDir, 'components.html'),
'utf-8',
);
for (const [pageHtml, markdownFilename] of [
[html, 'index.md'],
[componentsHtml, 'components.md'],
]) {
const head = pageHtml.split('</head>')[0];
if (llms) {
expect(head).toContain(
`<link rel="alternate" type="text/markdown" href="https://example.com/docs/${markdownFilename}">`,
);
expect(head).toContain(
'<link rel="describedby" href="https://example.com/docs/llms.txt">',
);
} else {
expect(head).not.toContain('rel="alternate" type="text/markdown"');
expect(head).not.toContain('rel="describedby"');
}
}

const files = await fs.readdir(docBuildDir);
for (const file of ['index.md', 'llms.txt', 'llms-full.txt']) {
Expand Down Expand Up @@ -293,7 +325,7 @@ for (const { ssg, llms, config } of [
});
}

test('llms directive hint should be configurable', async () => {
test('disabling the llms directive hint keeps the discovery links', async () => {
const appDir = import.meta.dirname;
await runBuildCommand(appDir, 'rspress-no-llms-hint.config.ts');

Expand All @@ -302,4 +334,16 @@ test('llms directive hint should be configurable', async () => {
'utf-8',
);
expect(indexHtml).not.toContain('For AI agents:');
const head = indexHtml.split('</head>')[0];
expect(head).toContain(
'<link rel="alternate" type="text/markdown" href="https://example.com/docs/index.md"',
);
expect(head).toContain(
'<link rel="describedby" href="https://example.com/docs/llms.txt"',
);
const indexMd = await fs.readFile(
path.join(appDir, 'doc_build', 'index.md'),
'utf-8',
);
expect(indexMd).not.toContain('For AI agents:');
});
11 changes: 7 additions & 4 deletions packages/core/src/node/ssg-md/llms/emitLlmsTxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
type UserConfig,
} from '@rspress/shared';
import { matchPath } from 'react-router-dom';
import { getLlmsOutputPrefix } from '../../../ssgMdPaths';
import type { RouteService } from '../../route/RouteService';
import { generateLlmsFullTxt, generateLlmsTxt } from './llmsTxt';

Expand Down Expand Up @@ -128,10 +129,12 @@ export async function emitLlmsTxt(
mdContents,
);

const langPrefix = defaultLang === lang ? '' : `${lang}/`;
const versionPrefix =
isMultiVersion && version !== defaultVersion ? `${version}/` : '';
const prefix = `${versionPrefix}${langPrefix}`;
const prefix = getLlmsOutputPrefix(
lang,
version,
defaultLang,
defaultVersion,
);

emitAsset(`${prefix}llms.txt`, llmsTxtContent);
emitAsset(`${prefix}llms-full.txt`, llmsFullTxtContent);
Expand Down
14 changes: 2 additions & 12 deletions packages/core/src/node/ssg-md/renderPages.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
import { logger } from '@rspress/shared/logger';
import pMap from 'p-map';
import picocolors from 'picocolors';
import { routePathToMdFilename } from '../../ssgMdPaths';
import type { RouteService } from '../route/RouteService';
import { SSGConcurrency } from '../ssg/ssgEnv';
import { renderPage } from './renderPage';

const routePage2MdFilename = (routePath: string) => {
let fileName = routePath;
if (fileName.endsWith('/')) {
fileName = `${routePath}index.md`;
} else {
fileName = `${routePath}.md`;
}

return fileName.replace(/^\/+/, '');
};

export async function renderPages(
routeService: RouteService,
ssrBundlePath: string,
Expand All @@ -30,7 +20,7 @@ export async function renderPages(
routes,
async route => {
const html = await renderPage(route, ssrBundlePath);
const fileName = routePage2MdFilename(route.routePath);
const fileName = routePathToMdFilename(route.routePath);
emitAsset(fileName, html);
result.set(route.routePath, html);
},
Expand Down
22 changes: 22 additions & 0 deletions packages/core/src/node/ssg/headTags/attributes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createError } from '../../utils';

export function escapeHtmlAttribute(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}

export function renderAttrs(attrs: Record<string, string>): string {
return Object.entries(attrs)
.map(([key, value]) => {
if (typeof value === 'boolean') return key;
if (typeof value === 'string' || typeof value === 'number')
return `${key}="${value}"`;
throw createError(
`Invalid value for attribute ${key}:${JSON.stringify(value)}`,
);
})
.join(' ');
}
16 changes: 16 additions & 0 deletions packages/core/src/node/ssg/headTags/configHead.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { RouteMeta, UserConfig } from '@rspress/shared';
import { renderAttrs } from './attributes';

export function renderConfigHead(
head: UserConfig['head'],
route: RouteMeta,
): string {
return (head ?? [])
.map(entry => {
const tag = typeof entry === 'function' ? entry(route) : entry;
if (!tag) return '';
if (typeof tag === 'string') return tag;
return `<${tag[0]} ${renderAttrs(tag[1])}>`;
})
.join('');
}
5 changes: 5 additions & 0 deletions packages/core/src/node/ssg/headTags/generator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { RSPRESS_VERSION } from '../../constants';

export function renderGeneratorMeta(): string {
return `<meta name="generator" content="Rspress v${RSPRESS_VERSION}">`;
}
11 changes: 11 additions & 0 deletions packages/core/src/node/ssg/headTags/hreflang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { AlternateLink } from '../alternateLinks';
import { renderAttrs } from './attributes';

export function renderHreflangLinks(links: AlternateLink[]): string {
return links
.map(
({ href, hrefLang }) =>
`<link ${renderAttrs({ rel: 'alternate', hreflang: hrefLang, href })}>`,
)
.join('');
}
38 changes: 38 additions & 0 deletions packages/core/src/node/ssg/headTags/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { RouteMeta, UserConfig } from '@rspress/shared';
import type { RouteChunkAssetsManifest } from '../../route/routeChunkAssets';
import type { AlternateLink } from '../alternateLinks';
import type { HtmlRenderContext } from '../htmlRenderContext';
import { renderConfigHead } from './configHead';
import { renderHreflangLinks } from './hreflang';
import { renderLlmsTxtLink } from './llmsTxt';
import { renderMarkdownAlternateLink } from './markdownAlternate';
import { renderRoutePreloadLinks } from './routePreload';

export { renderGeneratorMeta } from './generator';

export function renderHeadTags({
head,
route,
alternateLinks,
routeChunkAssets,
context,
}: {
head: UserConfig['head'];
route: RouteMeta;
alternateLinks: AlternateLink[];
routeChunkAssets?: RouteChunkAssetsManifest;
context?: HtmlRenderContext;
}): string {
const hasRouteSource = 'absolutePath' in route;
const ssgMdContext =
hasRouteSource && context?.enableSsgMd ? context : undefined;
return [
renderRoutePreloadLinks(route.routePath, routeChunkAssets),
hasRouteSource ? renderConfigHead(head, route) : '',
renderHreflangLinks(alternateLinks),
ssgMdContext
? renderMarkdownAlternateLink(route.routePath, ssgMdContext)
: '',
ssgMdContext ? renderLlmsTxtLink(route, ssgMdContext) : '',
].join('');
}
18 changes: 18 additions & 0 deletions packages/core/src/node/ssg/headTags/llmsTxt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { RouteMeta } from '@rspress/shared';
import { getLlmsOutputPrefix, getSsgMdAssetUrl } from '../../../ssgMdPaths';
import type { HtmlRenderContext } from '../htmlRenderContext';
import { escapeHtmlAttribute } from './attributes';

export function renderLlmsTxtLink(
route: RouteMeta,
{ base, siteOrigin, defaultLang, defaultVersion }: HtmlRenderContext,
): string {
const prefix = getLlmsOutputPrefix(
route.lang,
route.version,
defaultLang,
defaultVersion,
);
const href = getSsgMdAssetUrl(`${prefix}llms.txt`, base, siteOrigin);
return `<link rel="describedby" href="${escapeHtmlAttribute(href)}">`;
}
15 changes: 15 additions & 0 deletions packages/core/src/node/ssg/headTags/markdownAlternate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { getSsgMdAssetUrl, routePathToMdFilename } from '../../../ssgMdPaths';
import type { HtmlRenderContext } from '../htmlRenderContext';
import { escapeHtmlAttribute } from './attributes';

export function renderMarkdownAlternateLink(
routePath: string,
{ base, siteOrigin }: HtmlRenderContext,
): string {
const href = getSsgMdAssetUrl(
routePathToMdFilename(routePath),
base,
siteOrigin,
);
return `<link rel="alternate" type="text/markdown" href="${escapeHtmlAttribute(href)}">`;
}
37 changes: 37 additions & 0 deletions packages/core/src/node/ssg/headTags/routePreload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { posix } from 'node:path';
import type { RouteChunkAssetsManifest } from '../../route/routeChunkAssets';
import { routePath2HtmlFileName } from '../htmlFile';
import { escapeHtmlAttribute } from './attributes';

export function renderRoutePreloadLinks(
routePath: string,
manifest?: RouteChunkAssetsManifest,
): string {
if (!manifest) return '';

const assets = manifest.assets[routePath];
if (!assets) return '';

return assets
.map(asset => {
const href =
manifest.assetPrefix === 'auto'
? posix.relative(
posix.dirname(routePath2HtmlFileName(routePath)),
asset,
)
: `${manifest.assetPrefix}${asset}`;
const rel = manifest.isModule ? 'modulepreload' : 'preload';
const as = manifest.isModule ? '' : ' as="script"';
const crossOrigin = manifest.crossOriginLoading;
const crossorigin =
crossOrigin &&
(manifest.isModule ||
crossOrigin === 'use-credentials' ||
/^(?:[a-z][a-z\d+.-]*:)?\/\//i.test(href))
? ` crossorigin="${crossOrigin}"`
: '';
return `<link rel="${rel}" href="${escapeHtmlAttribute(href)}"${as}${crossorigin}>`;
})
.join('');
}
8 changes: 8 additions & 0 deletions packages/core/src/node/ssg/htmlRenderContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { UserConfig } from '@rspress/shared';

export type HtmlRenderContext = Pick<UserConfig, 'base' | 'siteOrigin'> & {
defaultLang: string;
defaultVersion: string;
ssg: NonNullable<UserConfig['ssg']>;
enableSsgMd: boolean;
};
Loading