Skip to content
Merged
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
6 changes: 6 additions & 0 deletions packages/astro-theme/src/components/DocsContent.astro
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
import DocsPage from "./DocsPage.astro";
import { toDocsMarkdownUrl } from "@farming-labs/docs";

const { data, config = null } = Astro.props;

Expand Down Expand Up @@ -71,6 +72,10 @@ const openDocsProviders = (() => {
})();

const pathname = Astro.url.pathname;
const pageUrl = typeof data.url === "string" ? data.url : pathname;
const markdownAlternateHref = config?.staticExport
? null
: toDocsMarkdownUrl(pageUrl, { locale: data.locale });
const githubFileUrl = config?.github && data.editOnGithub ? data.editOnGithub : null;

const pageActionsPosition = (() => {
Expand Down Expand Up @@ -141,6 +146,7 @@ const htmlWithoutFirstH1 = (data.html || "").replace(/<h1[^>]*>[\s\S]*?<\/h1>\s*
<head>
<title>{data.title}{titleSuffix}</title>
{data.description && <meta name="description" content={data.description} />}
{markdownAlternateHref && <link rel="alternate" type="text/markdown" href={markdownAlternateHref} />}
</head>

<DocsPage
Expand Down
2 changes: 2 additions & 0 deletions packages/astro/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ export interface DocsServer {
load: (pathname: string) => Promise<{
tree: ReturnType<typeof loadDocsNavTree>;
flatPages: PageNode[];
url: string;
title: string;
description?: string;
html: string;
Expand Down Expand Up @@ -710,6 +711,7 @@ export function createDocsServer(config: Record<string, any> = {}): DocsServer {
return {
tree,
flatPages,
url: currentUrl,
title: (data.title as string) ?? fallbackTitle,
description: data.description as string | undefined,
html,
Expand Down
13 changes: 13 additions & 0 deletions packages/docs/src/agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
resolveDocsLlmsTxtFormat,
resolveDocsSkillFormat,
resolveDocsMarkdownRequest,
toDocsMarkdownUrl,
} from "./agent.js";

describe("agent route helpers", () => {
Expand Down Expand Up @@ -123,6 +124,18 @@ describe("agent route helpers", () => {
expect(hijackRoute).toBeNull();
});

it("builds per-page markdown alternate URLs", () => {
expect(toDocsMarkdownUrl("/docs")).toBe("/docs.md");
expect(toDocsMarkdownUrl("/docs/install")).toBe("/docs/install.md");
expect(toDocsMarkdownUrl("/docs/install.md")).toBe("/docs/install.md");
expect(toDocsMarkdownUrl("/docs/install?ref=sidebar", { locale: "fr" })).toBe(
"/docs/install.md?ref=sidebar&lang=fr",
);
expect(toDocsMarkdownUrl("/docs/install?lang=es", { locale: "fr" })).toBe(
"/docs/install.md?lang=es",
);
});

it("renders agent-specific markdown documents", () => {
const human = resolveDocsAgentMdxContent("Visible\n\n<Agent>\nHidden\n</Agent>", "human");
const agent = resolveDocsAgentMdxContent("Visible\n\n<Agent>\nHidden\n</Agent>", "agent");
Expand Down
11 changes: 11 additions & 0 deletions packages/docs/src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,17 @@ export function normalizeDocsUrlPath(value: string): string {
return normalized.replace(/\/+$/, "");
}

export function toDocsMarkdownUrl(url: string, options: { locale?: string } = {}): string {
const [withoutHash, hash = ""] = url.split("#", 2);
const [pathname, query = ""] = withoutHash.split("?", 2);
const normalizedPath = normalizeDocsUrlPath(pathname || "/");
const markdownPath = normalizedPath.endsWith(".md") ? normalizedPath : `${normalizedPath}.md`;
const params = new URLSearchParams(query);
if (options.locale && !params.has("lang")) params.set("lang", options.locale);
const search = params.toString();
return `${markdownPath}${search ? `?${search}` : ""}${hash ? `#${hash}` : ""}`;
}

export function isDocsAgentDiscoveryRequest(url: URL): boolean {
const pathname = normalizeDocsUrlPath(url.pathname);
if (pathname === DEFAULT_DOCS_API_ROUTE && url.searchParams.get("agent")?.trim() === "spec") {
Expand Down
9 changes: 8 additions & 1 deletion packages/docs/src/cli/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1085,13 +1085,17 @@ export function tanstackDocsIndexRouteTemplate(opts: TanstackRouteTemplateOption
const entryUrl = `/${opts.entry.replace(/^\/+|\/+$/g, "")}`;
return `\
import { createFileRoute } from "@tanstack/react-router";
import { toDocsMarkdownUrl } from "@farming-labs/docs";
import { TanstackDocsPage } from "@farming-labs/tanstack-start/react";
import { loadDocPage } from "${tanstackDocsFunctionsImport(opts)}";
import docsConfig from "${tanstackDocsConfigImport(opts.filePath)}";

export const Route = createFileRoute("${entryUrl}/")({
loader: () => loadDocPage({ data: { pathname: "${entryUrl}" } }),
head: ({ loaderData }) => ({
links: loaderData && !docsConfig.staticExport
? [{ rel: "alternate", type: "text/markdown", href: toDocsMarkdownUrl(loaderData.url, { locale: loaderData.locale }) }]
: [],
meta: [
{ title: loaderData ? \`\${loaderData.title} – ${opts.projectName}\` : "${opts.projectName}" },
...(loaderData?.description
Expand All @@ -1116,7 +1120,7 @@ export function tanstackDocsCatchAllRouteTemplate(opts: TanstackRouteTemplateOpt
: relativeImport(opts.filePath, "src/lib/docs.server.ts");
return `\
import { createFileRoute, notFound } from "@tanstack/react-router";
import { isDocsPublicGetRequest } from "@farming-labs/docs";
import { isDocsPublicGetRequest, toDocsMarkdownUrl } from "@farming-labs/docs";
import { TanstackDocsPage } from "@farming-labs/tanstack-start/react";
import { loadDocPage } from "${tanstackDocsFunctionsImport(opts)}";
import { docsServer } from "${serverImport}";
Expand Down Expand Up @@ -1150,6 +1154,9 @@ export const Route = createFileRoute("${entryUrl}/$")({
}
},
head: ({ loaderData }) => ({
links: loaderData && !docsConfig.staticExport
? [{ rel: "alternate", type: "text/markdown", href: toDocsMarkdownUrl(loaderData.url, { locale: loaderData.locale }) }]
: [],
meta: [
{ title: loaderData ? \`\${loaderData.title} – ${opts.projectName}\` : "${opts.projectName}" },
...(loaderData?.description
Expand Down
1 change: 1 addition & 0 deletions packages/docs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export {
resolveDocsLlmsTxtFormat,
resolveDocsSkillFormat,
resolveDocsMarkdownRequest,
toDocsMarkdownUrl,
} from "./agent.js";
export {
DEFAULT_SITEMAP_MANIFEST_PATH,
Expand Down
16 changes: 15 additions & 1 deletion packages/fumadocs/src/docs-layout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { createDocsLayout } from "./docs-layout.js";
import { createDocsLayout, createPageMetadata } from "./docs-layout.js";

function findDocsPageClientProps(node: unknown): Record<string, unknown> | null {
if (!node || typeof node !== "object") return null;
Expand Down Expand Up @@ -57,6 +57,20 @@ function findDocsLayoutTree(node: unknown): Record<string, unknown> | null {
return children ? findDocsLayoutTree(children) : null;
}

describe("createPageMetadata", () => {
it("preserves the active locale in markdown alternate links", () => {
const metadata = createPageMetadata(
{ entry: "docs" },
{ title: "Installation", description: "Install the framework" },
undefined,
"/docs/installation",
{ locale: "fr" },
) as { alternates?: { types?: Record<string, string> } };

expect(metadata.alternates?.types?.["text/markdown"]).toBe("/docs/installation.md?lang=fr");
});
});

describe("createDocsLayout pageActions", () => {
let tmpDir: string;
let originalCwd: string;
Expand Down
13 changes: 12 additions & 1 deletion packages/fumadocs/src/docs-layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
resolveDocsAgentMdxContent,
resolveDocsAnalyticsConfig,
resolvePageSidebarFolderIndexBehavior,
toDocsMarkdownUrl,
} from "@farming-labs/docs";
import type {
DocsConfig,
Expand Down Expand Up @@ -605,20 +606,30 @@ export function createDocsMetadata(config: DocsConfig) {
* ```ts
* export function generateMetadata({ params }) {
* const page = getPage(params.slug);
* return createPageMetadata(docsConfig, page.data);
* return createPageMetadata(docsConfig, page.data, undefined, page.url, { locale });
* }
* ```
*/
export function createPageMetadata(
config: DocsConfig,
page: Pick<PageFrontmatter, "title" | "description" | "ogImage" | "openGraph" | "twitter">,
baseUrl?: string,
url?: string,
options: { locale?: string } = {},
) {
const result: Record<string, unknown> = {
title: page.title,
...(page.description ? { description: page.description } : {}),
};

if (url && !(config as { staticExport?: boolean }).staticExport) {
result.alternates = {
types: {
"text/markdown": toDocsMarkdownUrl(url, { locale: options.locale }),
},
};
}

if (config.og?.enabled !== false) {
const openGraph = buildPageOpenGraph(page, config.og, baseUrl);
if (openGraph) result.openGraph = openGraph;
Expand Down
5 changes: 5 additions & 0 deletions packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@
"types": "./dist/mdx-plugins/remark-og.d.mts",
"import": "./dist/mdx-plugins/remark-og.mjs",
"default": "./dist/mdx-plugins/remark-og.mjs"
},
"./mdx-plugins/remark-markdown-alternate": {
"types": "./dist/mdx-plugins/remark-markdown-alternate.d.mts",
"import": "./dist/mdx-plugins/remark-markdown-alternate.mjs",
"default": "./dist/mdx-plugins/remark-markdown-alternate.mjs"
}
},
"scripts": {
Expand Down
39 changes: 27 additions & 12 deletions packages/next/src/changelog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -557,10 +557,15 @@ export function createNextChangelogStaticParams(entries: GeneratedChangelogEntry

export function createNextChangelogIndexMetadata(config: DocsConfig): Metadata {
const changelog = resolveChangelogConfig(config.changelog);
return createPageMetadata(config, {
title: changelog.title,
description: changelog.description,
}) as Metadata;
return createPageMetadata(
config,
{
title: changelog.title,
description: changelog.description,
},
undefined,
getListingUrl(config),
) as Metadata;
}

export function createNextChangelogEntryMetadata(
Expand All @@ -576,15 +581,25 @@ export function createNextChangelogEntryMetadata(

if (!entry) {
const changelog = resolveChangelogConfig(config.changelog);
return createPageMetadata(config, {
title: changelog.title,
description: changelog.description,
}) as Metadata;
return createPageMetadata(
config,
{
title: changelog.title,
description: changelog.description,
},
undefined,
getListingUrl(config),
) as Metadata;
}

return createPageMetadata(config, {
title: entry.title,
description: entry.description,
}) as Metadata;
return createPageMetadata(
config,
{
title: entry.title,
description: entry.description,
},
undefined,
`${getListingUrl(config)}/${entry.slug}`,
) as Metadata;
};
}
14 changes: 14 additions & 0 deletions packages/next/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,8 @@ function createDocsWorkspaceAliases(): Record<string, string> {
"@farming-labs/next/mdx-plugins/remark-heading":
"./packages/next/src/mdx-plugins/remark-heading.ts",
"@farming-labs/next/mdx-plugins/remark-og": "./packages/next/src/mdx-plugins/remark-og.ts",
"@farming-labs/next/mdx-plugins/remark-markdown-alternate":
"./packages/next/src/mdx-plugins/remark-markdown-alternate.ts",
"@farming-labs/theme": "./packages/fumadocs/src/index.ts",
"@farming-labs/theme/api": "./packages/fumadocs/src/docs-api.ts",
"@farming-labs/theme/client-hooks": "./packages/fumadocs/src/docs-client-hooks.tsx",
Expand Down Expand Up @@ -1628,6 +1630,10 @@ export function withDocs(nextConfig: NextConfig = {}): NextConfig {
if (ogEndpoint) {
remarkPlugins.push(["@farming-labs/next/mdx-plugins/remark-og", { endpoint: ogEndpoint }]);
}
remarkPlugins.push([
"@farming-labs/next/mdx-plugins/remark-markdown-alternate",
{ entry, appDir, contentDir: docsContentDir, enabled: !isStaticExport },
]);
remarkPlugins.push(
["remark-mdx-frontmatter", { name: "metadata" }],
"@farming-labs/next/mdx-plugins/remark-heading",
Expand Down Expand Up @@ -1721,6 +1727,14 @@ export function withDocs(nextConfig: NextConfig = {}): NextConfig {
"client-callbacks.mjs",
),
"@farming-labs/next/layout": join(workspaceRoot, "packages", "next", "dist", "layout.mjs"),
"@farming-labs/next/mdx-plugins/remark-markdown-alternate": join(
workspaceRoot,
"packages",
"next",
"dist",
"mdx-plugins",
"remark-markdown-alternate.mjs",
),
"@farming-labs/theme$": join(workspaceRoot, "packages", "fumadocs", "dist", "index.mjs"),
"@farming-labs/theme/api": join(
workspaceRoot,
Expand Down
54 changes: 54 additions & 0 deletions packages/next/src/mdx-plugins/remark-markdown-alternate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import remarkMarkdownAlternate from "./remark-markdown-alternate.js";

describe("remarkMarkdownAlternate", () => {
it("adds a text/markdown alternate URL for docs page routes", () => {
const tree = {
children: [{ type: "yaml", value: 'title: "Install"' }],
};
const transform = remarkMarkdownAlternate({ entry: "docs", contentDir: "app/docs" });

transform(tree, { path: "/repo/app/docs/install/page.mdx" });

expect(tree.children[0]?.value).toContain("alternates:");
expect(tree.children[0]?.value).toContain('text/markdown: "/docs/install.md"');
});

it("adds root docs markdown alternate URLs", () => {
const tree = {
children: [{ type: "yaml", value: 'title: "Docs"' }],
};
const transform = remarkMarkdownAlternate({ entry: "docs", contentDir: "app/docs" });

transform(tree, { path: "/repo/app/docs/page.mdx" });

expect(tree.children[0]?.value).toContain('text/markdown: "/docs.md"');
});

it("handles relative source paths", () => {
const tree = {
children: [{ type: "yaml", value: 'title: "Quickstart"' }],
};
const transform = remarkMarkdownAlternate({ entry: "docs", contentDir: "app/docs" });

transform(tree, { path: "app/docs/quickstart/page.md" });

expect(tree.children[0]?.value).toContain('text/markdown: "/docs/quickstart.md"');
});

it("does not overwrite custom alternates", () => {
const tree = {
children: [
{
type: "yaml",
value: 'title: "Install"\nalternates:\n canonical: "/custom"',
},
],
};
const transform = remarkMarkdownAlternate({ entry: "docs", contentDir: "app/docs" });

transform(tree, { path: "/repo/app/docs/install/page.mdx" });

expect(tree.children[0]?.value).not.toContain("text/markdown");
});
});
Loading
Loading