Commit 331d26a3 authored by Jimmy Lai's avatar Jimmy Lai

feat(next): add experimental markdown output

parent 16206a7f
......@@ -997,6 +997,10 @@ pub fn mdx_import_source_file() -> RcStr {
format!("{VIRTUAL_PACKAGE_NAME}/mdx-import-source").into()
}
pub fn markdown_import_source_file() -> RcStr {
rcstr!("next-markdown-import-source-file")
}
// Insert aliases for Next.js stubs of fetch, object-assign, and url
// Keep in sync with getOptimizedModuleAliases in webpack-config.ts
async fn insert_optimized_module_aliases(
......@@ -1044,6 +1048,19 @@ async fn insert_next_shared_aliases(
],
);
insert_alias_to_alternatives(
import_map,
markdown_import_source_file(),
vec![
request_to_import_mapping(project_path.clone(), rcstr!("./markdown-components")),
request_to_import_mapping(project_path.clone(), rcstr!("./src/markdown-components")),
request_to_import_mapping(
project_path.clone(),
rcstr!("next/dist/server/markdown/default-markdown-components"),
),
],
);
insert_package_alias(
import_map,
&format!("{VIRTUAL_PACKAGE_NAME}/"),
......
---
title: How to generate Markdown output from your Next.js routes
nav_title: Markdown output
description: Learn how to have App Router and Pages Router routes return Markdown from the React tree they render.
version: experimental
related:
title: Related APIs
links:
- app/api-reference/config/next-config-js/markdown
- app/api-reference/file-conventions/markdown-components
- app/api-reference/functions/generate-markdown
- app/guides/mdx
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
Markdown output is different from file-based Markdown and MDX. Instead of compiling `.md` or `.mdx` files into HTML, Next.js can render your route and serialize the result to Markdown when the request prefers `text/markdown`.
This is useful when you want the same route to serve HTML to browsers and Markdown to AI clients, feeds, or downstream systems that prefer plain text.
Markdown output is currently supported in the Node.js runtime only. Routes that run in the Edge runtime continue to return their normal HTML responses.
## Enable the experiment
Enable the feature in `next.config.js`:
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
markdown: true,
},
}
module.exports = nextConfig
```
This enables the runtime, but routes still need to opt in individually.
## Add `markdown-components`
Create a `markdown-components.js` (or `.tsx`) file in the root of your project, next to `app` or `pages`, or inside `src` if your project uses `src/`.
```js filename="markdown-components.js"
export function useMarkdownComponents() {
return {
p({ children }) {
return `paragraph:${children}`
},
button({ children }) {
return children ? `action:${children}` : null
},
}
}
```
These serializers are used as the root-level defaults for Markdown responses. You can override them per route segment or page with the `markdown` export.
## Opt a route into Markdown
Use the `markdown` export to opt a route into Markdown responses.
<AppOnly>
You can export `markdown` from `layout.js` or `page.js`:
```jsx filename="app/blog/[slug]/page.js"
export const markdown = true
export default function Page() {
return (
<main>
<h1>Hello</h1>
<p>Rendered as Markdown when requested.</p>
</main>
)
}
```
You can also provide segment-level component overrides:
```jsx filename="app/blog/[slug]/layout.js"
export const markdown = {
components: {
p({ children }) {
return `segment:${children}`
},
},
}
export default function Layout({ children }) {
return <section>{children}</section>
}
```
</AppOnly>
<PagesOnly>
You can export `markdown` from a page:
```jsx filename="pages/blog/[slug].js"
export const markdown = true
export default function Page() {
return (
<main>
<h1>Hello</h1>
<p>Rendered as Markdown when requested.</p>
</main>
)
}
```
You can also provide page-level component overrides:
```jsx filename="pages/blog/[slug].js"
export const markdown = {
components: {
p({ children }) {
return `page:${children}`
},
},
}
```
</PagesOnly>
## Request Markdown
Markdown is returned from the same route when the request prefers `text/markdown`:
```bash filename="Terminal"
curl -H "Accept: text/markdown" http://localhost:3000/blog/hello
```
Normal browser requests still receive HTML by default.
## Customize the generated Markdown
Use `generateMarkdown` when you want to wrap, replace, or post-process the default serialization.
<AppOnly>
Pages receive the same props as the route component, plus a `renderDefault` helper:
```jsx filename="app/products/[id]/page.js"
export const markdown = true
export async function generateMarkdown(props, { renderDefault }) {
const content = await renderDefault()
return ['# Product export', content].join('\n\n')
}
export default function Page({ params }) {
return <p>Product {params.id}</p>
}
```
Layouts can compose child Markdown with the `children` helper:
```jsx filename="app/products/layout.js"
export const markdown = true
export async function generateMarkdown(_props, { children }) {
return ['catalog-start', await children, 'catalog-end'].join('\n')
}
export default function Layout({ children }) {
return <section>{children}</section>
}
```
</AppOnly>
<PagesOnly>
Pages receive a `context` object containing the resolved page props and query:
```jsx filename="pages/products/[id].js"
export const markdown = true
export async function generateMarkdown(context, { renderDefault }) {
const content = await renderDefault()
return [
`product:${context.props.product.id}`,
`query:${context.query.id}`,
content,
].join('\n')
}
export default function Page({ product }) {
return <p>{product.name}</p>
}
```
</PagesOnly>
## Default behavior
By default, the serializer:
- maps headings, paragraphs, emphasis, links, images, code blocks, lists, blockquotes, and tables to Markdown
- omits interactive controls such as `button`, `input`, `select`, `textarea`, and `form`
- omits nodes that expose event-handler props like `onClick`
- lets overrides return a string to replace the default output, or `null` / `undefined` to omit it
Override precedence is:
1. Child route segment or page overrides
2. Parent layout overrides
3. Root `markdown-components`
When both a component-name override and a host tag override match, the component-name override wins.
## Stable component names
Component-name overrides work best with named exports or components that set `displayName`. Client Components also use their exported name when it is available at runtime.
If a component does not have a stable runtime name, prefer a host tag override instead.
## Version History
| Version | Changes |
| ------------------- | ---------------------------------------- |
| `v16.2.0-canary.81` | Experimental Markdown output introduced. |
......@@ -26,6 +26,18 @@ Next.js can support both local MDX content inside your application, as well as r
> **Good to know**: View the [Portfolio Starter Kit](https://vercel.com/templates/next.js/portfolio-starter-kit) template for a complete working example.
<AppOnly>
> **Good to know**: If you want to return Markdown from a rendered route instead of compiling MDX to HTML, see [Markdown output](/docs/app/guides/markdown-output).
</AppOnly>
<PagesOnly>
> **Good to know**: If you want to return Markdown from a rendered route instead of compiling MDX to HTML, see [Markdown output](/docs/pages/guides/markdown-output).
</PagesOnly>
## Install dependencies
The `@next/mdx` package, and related packages, are used to configure Next.js so it can process markdown and MDX. **It sources data from local files**, allowing you to create pages with a `.md` or `.mdx` extension, directly in your `/pages` or `/app` directory.
......
---
title: markdown-components.js
description: API reference for the markdown-components.js file.
version: experimental
related:
title: Learn more about Markdown output
links:
- app/guides/markdown-output
- app/api-reference/functions/generate-markdown
---
The `markdown-components.js|tsx` file defines root-level Markdown serializers for routes that respond with `text/markdown`.
Use the file `markdown-components.tsx` (or `.js`) in the root of your project, next to `app` or `pages`, or inside `src` if applicable.
```tsx filename="markdown-components.tsx" switcher
const components = {
p({ children }: { children: string }) {
return `paragraph:${children}`
},
}
export function useMarkdownComponents() {
return components
}
```
```js filename="markdown-components.js" switcher
const components = {
p({ children }) {
return `paragraph:${children}`
},
}
export function useMarkdownComponents() {
return components
}
```
## Exports
### `useMarkdownComponents`
The file must export a function named `useMarkdownComponents`. It does not accept any arguments and should return an object whose keys are either:
- host tags such as `p`, `a`, `code`, or `button`
- component names such as `ArticleCard` or `ClientWidget`
Each serializer receives:
- `tagName` when the override matched a host element
- `componentName` when the override matched a component
- `attributes` as a map of rendered HTML attributes
- `children` as the already-serialized Markdown for the node's children
- `textContent` as the rendered text content for the node
- `renderDefault()` to reuse the built-in serializer
Return a string to replace the default output, or return `null` / `undefined` to omit the node.
## Good to know
- `markdown-components` only affects Markdown responses. It does not affect HTML rendering or MDX rendering.
- Route-level `markdown.components` overrides take precedence over `markdown-components`.
- Interactive elements are omitted by default unless you explicitly override them.
- Component-name overrides take precedence over tag overrides.
## Version History
| Version | Changes |
| ------------------- | -------------------------------------------- |
| `v16.2.0-canary.81` | `markdown-components` file convention added. |
---
title: generateMarkdown
description: Customize Markdown responses generated from App Router and Pages Router routes.
version: experimental
related:
title: Related APIs
links:
- app/guides/markdown-output
- app/api-reference/file-conventions/markdown-components
- app/api-reference/config/next-config-js/markdown
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
Use `generateMarkdown` to customize the Markdown returned by a route after Next.js renders the route's React tree.
`generateMarkdown` only runs when:
- `experimental.markdown` is enabled in `next.config.js`
- the route is opted into Markdown output
- the request is a full `GET` or `HEAD` document request that prefers `text/markdown`
- the route runs in the Node.js runtime
Normal HTML requests are not affected.
## Reference
<AppOnly>
### App Router
Export `generateMarkdown` from a `layout.js` or `page.js` file.
```tsx filename="app/blog/[slug]/page.tsx" switcher
export const markdown = true
export async function generateMarkdown(
props: PageProps<'/blog/[slug]'>,
helpers: { renderDefault(): Promise<string> }
) {
const content = await helpers.renderDefault()
return ['# Blog export', content].join('\n\n')
}
export default function Page() {
return <p>Hello</p>
}
```
```jsx filename="app/blog/[slug]/page.js" switcher
export const markdown = true
export async function generateMarkdown(props, { renderDefault }) {
const content = await renderDefault()
return ['# Blog export', content].join('\n\n')
}
export default function Page() {
return <p>Hello</p>
}
```
Layouts also receive a `children` helper containing the Markdown generated by nested segments:
```jsx filename="app/blog/layout.js"
export const markdown = true
export async function generateMarkdown(_props, { children }) {
return ['layout-start', await children, 'layout-end'].join('\n')
}
export default function Layout({ children }) {
return <section>{children}</section>
}
```
#### Parameters
- `props`: The same props passed to the route segment during rendering.
- `helpers.renderDefault()`: Returns the default Markdown for the current segment.
- `helpers.children`: Layout-only helper that resolves to the Markdown generated by child segments.
</AppOnly>
<PagesOnly>
### Pages Router
Export `generateMarkdown` from a page:
```tsx filename="pages/blog/[slug].tsx" switcher
export const markdown = true
export async function generateMarkdown(
context: {
props: { title: string }
query: { slug?: string | string[] }
},
helpers: { renderDefault(): Promise<string> }
) {
const content = await helpers.renderDefault()
return [`title:${context.props.title}`, content].join('\n')
}
export default function Page({ title }: { title: string }) {
return <p>{title}</p>
}
```
```jsx filename="pages/blog/[slug].js" switcher
export const markdown = true
export async function generateMarkdown(context, { renderDefault }) {
const content = await renderDefault()
return [`title:${context.props.title}`, content].join('\n')
}
export default function Page({ title }) {
return <p>{title}</p>
}
```
#### Parameters
- `context.props`: The resolved page props.
- `context.query`: The request query, including dynamic route params.
- `helpers.renderDefault()`: Returns the default Markdown for the page.
</PagesOnly>
### Returns
`generateMarkdown` can return:
- a string
- a promise that resolves to a string
- `null` or `undefined` to omit the current segment
## Good to know
- Export `markdown = true` or `markdown = { components: ... }` from the same route to opt it into Markdown output.
- In App Router, `generateMarkdown` is supported in pages and layouts.
- In Pages Router, `generateMarkdown` is supported in pages only. `_app` and `_document` are not part of Markdown generation.
- `generateMarkdown` is not supported in the Edge runtime.
- If you do not export `generateMarkdown`, Next.js uses the default serializer.
- `helpers.renderDefault()` uses the currently merged Markdown component overrides for that segment.
## Version History
| Version | Changes |
| ------------------- | ------------------------------ |
| `v16.2.0-canary.81` | `generateMarkdown` introduced. |
---
title: markdown
description: Enable experimental Markdown output for App Router and Pages Router routes.
version: experimental
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
Enable experimental Markdown output for routes that opt into `text/markdown` responses.
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
markdown: true,
},
}
module.exports = nextConfig
```
## Good to know
- This flag enables the Markdown runtime, but routes must still opt in with `export const markdown = true` or `export const markdown = { components: ... }`.
- Markdown is only returned for full document `GET` and `HEAD` requests that prefer `text/markdown`.
- RSC requests, prefetch requests, and data requests keep their existing response formats.
- The feature works in both App Router and Pages Router when the route runs in the Node.js runtime.
- Edge runtime routes ignore Markdown negotiation and continue to return their normal responses.
## Version History
| Version | Changes |
| ------------------- | ----------------------------------- |
| `v16.2.0-canary.81` | `experimental.markdown` introduced. |
---
title: How to generate Markdown output from your Next.js routes
nav_title: Markdown output
description: Learn how to have App Router and Pages Router routes return Markdown from the React tree they render.
source: app/guides/markdown-output
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
---
title: markdown-components.js
description: API reference for the markdown-components.js file.
source: app/api-reference/file-conventions/markdown-components
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
---
title: generateMarkdown
description: Customize Markdown responses generated from App Router and Pages Router routes.
source: app/api-reference/functions/generate-markdown
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
---
title: markdown
description: Enable experimental Markdown output for App Router and Pages Router routes.
source: app/api-reference/config/next-config-js/markdown
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
# `@next/markdown`
Internal Markdown serialization package used by Next.js experimental Markdown
output.
## Status
`@next/markdown` is a private package. It is not a supported public API and may
change without notice.
## What it does
This package contains the generic React and HTML to Markdown logic used by
Next.js:
- React tree instrumentation for Markdown-specific markers
- HTML to Markdown serialization
- root and segment-level component overrides
- default heuristics for omitting interactive controls
Next.js-specific routing, content negotiation, and route export handling live in
`packages/next`.
## Internal API
The package currently exposes:
- `markReactNode`
- `renderHtmlToMarkdown`
- marker constants
- Markdown component and segment types
## Development
```bash
pnpm --filter @next/markdown build
```
{
"name": "@next/markdown",
"version": "16.2.0-canary.81",
"private": true,
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": [
"dist",
"README.md"
],
"scripts": {
"prebuild": "node ../../scripts/rm.mjs dist",
"build": "tsc --project tsconfig.json"
},
"license": "MIT",
"repository": {
"url": "vercel/next.js",
"directory": "packages/next-markdown"
},
"dependencies": {
"node-html-parser": "7.0.1"
},
"peerDependencies": {
"react": "^18.2.0 || ^19.0.0"
}
}
This diff is collapsed.
{
"compilerOptions": {
"target": "es2019",
"module": "commonjs",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": false,
"rootDir": "src",
"outDir": "dist",
"declaration": true
},
"include": ["src/**/*.ts"],
"exclude": ["dist", "node_modules"]
}
......@@ -1086,5 +1086,7 @@
"1085": "Route \"%s\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata",
"1086": "Route \"%s\": %s This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport",
"1087": "Failed to parse \"%s\":\\n%s%s",
"1088": "Expected RSC navigation response to have a body"
"1088": "Expected RSC navigation response to have a body",
"1089": "RSC fetch failed after all retry attempts",
"1090": "Markdown output is not supported in the Edge runtime."
}
......@@ -98,6 +98,7 @@
},
"dependencies": {
"@next/env": "16.2.0-canary.81",
"@next/markdown": "16.2.0-canary.81",
"@swc/helpers": "0.5.15",
"baseline-browser-mapping": "^2.9.19",
"caniuse-lite": "^1.0.30001579",
......
......@@ -61,7 +61,12 @@ interface SharedRouteFields {
*/
filePath: string
/**
* pathname is the URL pathname the asset should be served at
* pathname is the URL pathname the asset should be served at.
* Some outputs have alternate representation suffixes like `.rsc`
* or `.markdown`.
* Document outputs can still negotiate alternate response content types
* such as `text/html` or `text/markdown` at runtime without a pathname
* change.
*/
pathname: string
......@@ -104,7 +109,6 @@ interface SharedRouteFields {
* region preferences to the provider being used
*/
preferredRegion?: string | string[]
/**
* env is the environment variables to expose, this is only
* populated for edge runtime currently
......@@ -116,6 +120,9 @@ interface SharedRouteFields {
export interface AdapterOutput {
/**
* `PAGES` represents all the React pages that are under `pages/`.
* These are document endpoints, so the same pathname may negotiate
* alternate response representations such as `text/html` or
* `text/markdown` at runtime.
*/
PAGES: SharedRouteFields & {
type: AdapterOutputType.PAGES
......@@ -130,6 +137,9 @@ export interface AdapterOutput {
/**
* `APP_PAGE` represents all the React pages that are under `app/` with the
* filename of `page.{j,t}s{,x}`.
* These are document endpoints, so the same pathname may negotiate
* alternate response representations such as `text/html` or
* `text/markdown` at runtime.
*/
APP_PAGE: SharedRouteFields & {
type: AdapterOutputType.APP_PAGE
......@@ -297,6 +307,12 @@ export interface AdapterOutputs {
staticFiles: Array<AdapterOutput['STATIC_FILE']>
}
const MARKDOWN_OUTPUT_SUFFIX = '.markdown'
function getMarkdownOutputPathname(pathname: string): string {
return `${normalizePagePath(pathname)}${MARKDOWN_OUTPUT_SUFFIX}`
}
type RewriteItem = {
source: string
sourceRegex: string
......@@ -363,6 +379,13 @@ export interface NextAdapter {
shouldNormalizeNextData: boolean
rsc: RoutesManifest['rsc']
}
/**
* outputs describe the deployable entrypoints and static artifacts.
* For document endpoints (`PAGES` and `APP_PAGE`), adapters should not
* assume a single response content type for a pathname. The same output
* may negotiate alternate representations like `text/html` and
* `text/markdown` at runtime.
*/
outputs: AdapterOutputs
/**
* projectDir is the absolute directory the Next.js application is in
......@@ -919,6 +942,10 @@ export async function handleBuildComplete({
sourcePage = sourcePage === 'api' ? 'api/index' : sourcePage
const baseConfig = {
maxDuration: functionConfig.maxDuration,
preferredRegion: functionConfig.regions,
}
const output: AdapterOutput['PAGES'] | AdapterOutput['PAGES_API'] = {
id: route,
type: page.startsWith('/api')
......@@ -929,16 +956,22 @@ export async function handleBuildComplete({
sourcePage,
assets,
runtime: 'nodejs',
config: {
maxDuration: functionConfig.maxDuration,
preferredRegion: functionConfig.regions,
},
config: baseConfig,
}
pageOutputMap[page] = output
if (output.type === AdapterOutputType.PAGES) {
outputs.pages.push(output)
if (functionConfig.markdown) {
const markdownPathname = getMarkdownOutputPathname(route)
outputs.pages.push({
...output,
pathname: markdownPathname,
id: markdownPathname,
})
}
// if page is get server side props we need to create
// the _next/data output as well
if (serverPropsPages.has(page)) {
......@@ -951,6 +984,7 @@ export async function handleBuildComplete({
...output,
pathname: dataPathname,
id: dataPathname,
config: baseConfig,
})
if (appPageKeys && appPageKeys.length > 0) {
......@@ -975,6 +1009,15 @@ export async function handleBuildComplete({
pathname: localePage,
})
if (functionConfig.markdown) {
const markdownPathname = getMarkdownOutputPathname(localePage)
outputs.pages.push({
...output,
pathname: markdownPathname,
id: markdownPathname,
})
}
if (serverPropsPages.has(page)) {
const dataPathname = path.posix.join(
'/_next/data',
......@@ -985,6 +1028,7 @@ export async function handleBuildComplete({
...output,
pathname: dataPathname,
id: dataPathname,
config: baseConfig,
})
if (appPageKeys && appPageKeys.length > 0) {
outputs.staticFiles.push({
......@@ -1078,6 +1122,11 @@ export async function handleBuildComplete({
const functionConfig =
functionsConfigManifest.functions[normalizedPage] || {}
const baseConfig = {
maxDuration: functionConfig.maxDuration,
preferredRegion: functionConfig.regions,
}
const output: AdapterOutput['APP_PAGE'] | AdapterOutput['APP_ROUTE'] =
{
pathname: normalizedPage,
......@@ -1089,10 +1138,7 @@ export async function handleBuildComplete({
: AdapterOutputType.APP_PAGE,
runtime: 'nodejs',
filePath: pageFile,
config: {
maxDuration: functionConfig.maxDuration,
preferredRegion: functionConfig.regions,
},
config: baseConfig,
}
appOutputMap[normalizedPage] = output
......@@ -1101,7 +1147,19 @@ export async function handleBuildComplete({
...output,
pathname: normalizePagePath(output.pathname) + '.rsc',
id: normalizePagePath(output.pathname) + '.rsc',
config: baseConfig,
})
if (functionConfig.markdown) {
const markdownPathname = getMarkdownOutputPathname(
output.pathname
)
outputs.appPages.push({
...output,
pathname: markdownPathname,
id: markdownPathname,
config: baseConfig,
})
}
outputs.appPages.push(output)
} else {
outputs.appRoutes.push(output)
......
......@@ -40,7 +40,7 @@ import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-pat
import { isProxyFile } from '../utils'
const PARSE_PATTERN =
/(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const|generateImageMetadata|generateSitemaps|middleware|proxy/
/(?<!(_jsx|jsx-))runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|generateMarkdown|markdown|export const|generateImageMetadata|generateSitemaps|middleware|proxy/
export type ProxyMatcher = {
regexp: string
......@@ -82,6 +82,7 @@ export interface AppPageStaticInfo {
runtime: AppSegmentConfig['runtime'] | undefined
preferredRegion: AppSegmentConfig['preferredRegion'] | undefined
maxDuration: number | undefined
supportsMarkdown: boolean
hadUnsupportedValue: boolean
}
......@@ -102,6 +103,7 @@ export interface PagesPageStaticInfo {
runtime: PagesSegmentConfig['runtime'] | undefined
preferredRegion: PagesSegmentConfigConfig['regions'] | undefined
maxDuration: number | undefined
supportsMarkdown: boolean
hadUnsupportedValue: boolean
}
......@@ -173,6 +175,8 @@ function checkExports(
generateImageMetadata?: boolean
generateSitemaps?: boolean
generateStaticParams?: boolean
hasMarkdownExport?: boolean
hasGenerateMarkdownExport?: boolean
directives?: Set<string>
exports?: Set<string>
} {
......@@ -193,6 +197,8 @@ function checkExports(
let generateImageMetadata: boolean = false
let generateSitemaps: boolean = false
let generateStaticParams = false
let hasMarkdownExport = false
let hasGenerateMarkdownExport = false
let exports = new Set<string>()
let directives = new Set<string>()
let hasLeadingNonDirectiveNode = false
......@@ -223,6 +229,12 @@ function checkExports(
if (expectedExports.includes(declaration.id.value)) {
exports.add(declaration.id.value)
}
if (declaration.id.value === 'markdown') {
hasMarkdownExport = true
}
if (declaration.id.value === 'generateMarkdown') {
hasGenerateMarkdownExport = true
}
}
}
......@@ -239,6 +251,14 @@ function checkExports(
generateStaticParams = id === 'generateStaticParams'
}
if (
node.type === 'ExportDeclaration' &&
node.declaration?.type === 'FunctionDeclaration' &&
node.declaration.identifier?.value === 'generateMarkdown'
) {
hasGenerateMarkdownExport = true
}
if (
node.type === 'ExportDeclaration' &&
node.declaration?.type === 'VariableDeclaration'
......@@ -276,6 +296,14 @@ function checkExports(
if (!generateStaticParams && value === 'generateStaticParams') {
generateStaticParams = true
}
const exportedIdentifier = specifier.exported || specifier.orig
const exportName = exportedIdentifier.value
if (exportName === 'markdown') {
hasMarkdownExport = true
}
if (exportName === 'generateMarkdown') {
hasGenerateMarkdownExport = true
}
if (expectedExports.includes(value) && !exports.has(value)) {
// An export was found that was actually a re-export, and not a
// literal value. We should warn here.
......@@ -294,6 +322,8 @@ function checkExports(
generateImageMetadata,
generateSitemaps,
generateStaticParams,
hasMarkdownExport,
hasGenerateMarkdownExport,
directives,
exports,
}
......@@ -620,6 +650,7 @@ export async function getAppPageStaticInfo({
runtime: undefined,
preferredRegion: undefined,
maxDuration: undefined,
supportsMarkdown: false,
hadUnsupportedValue: false,
}
}
......@@ -636,6 +667,8 @@ export async function getAppPageStaticInfo({
generateStaticParams,
generateImageMetadata,
generateSitemaps,
hasMarkdownExport,
hasGenerateMarkdownExport,
exports,
directives,
} = checkExports(ast, AppSegmentConfigSchemaKeys, page)
......@@ -702,6 +735,8 @@ export async function getAppPageStaticInfo({
runtime: config.runtime,
preferredRegion: config.preferredRegion,
maxDuration: config.maxDuration,
supportsMarkdown:
Boolean(hasMarkdownExport) || Boolean(hasGenerateMarkdownExport),
hadUnsupportedValue,
}
}
......@@ -720,6 +755,7 @@ export async function getPagesPageStaticInfo({
runtime: undefined,
preferredRegion: undefined,
maxDuration: undefined,
supportsMarkdown: false,
hadUnsupportedValue: false,
}
}
......@@ -732,11 +768,13 @@ export async function getPagesPageStaticInfo({
isDev,
})
const { getServerSideProps, getStaticProps, exports } = checkExports(
ast,
PagesSegmentConfigSchemaKeys,
page
)
const {
getServerSideProps,
getStaticProps,
hasMarkdownExport,
hasGenerateMarkdownExport,
exports,
} = checkExports(ast, PagesSegmentConfigSchemaKeys, page)
const { type: rsc } = getRSCModuleInformation(content, true)
......@@ -811,6 +849,8 @@ export async function getPagesPageStaticInfo({
runtime: resolvedRuntime,
preferredRegion: config.config?.regions,
maxDuration: config.maxDuration ?? config.config?.maxDuration,
supportsMarkdown:
Boolean(hasMarkdownExport) || Boolean(hasGenerateMarkdownExport),
hadUnsupportedValue,
}
}
......
......@@ -5,6 +5,7 @@ import {
PAGES_DIR_ALIAS,
ROOT_DIR_ALIAS,
APP_DIR_ALIAS,
MARKDOWN_COMPONENTS_ALIAS,
RSC_ACTION_PROXY_ALIAS,
RSC_ACTION_CLIENT_WRAPPER_ALIAS,
RSC_ACTION_VALIDATE_ALIAS,
......@@ -136,6 +137,11 @@ export function createWebpackAliases({
...(pagesDir ? { [PAGES_DIR_ALIAS]: pagesDir } : {}),
...(appDir ? { [APP_DIR_ALIAS]: appDir } : {}),
[ROOT_DIR_ALIAS]: dir,
[MARKDOWN_COMPONENTS_ALIAS]: [
`${ROOT_DIR_ALIAS}/src/markdown-components`,
`${ROOT_DIR_ALIAS}/markdown-components`,
'next/dist/server/markdown/default-markdown-components',
],
...(isClient
? {
'private-next-instrumentation-client': [
......
......@@ -87,6 +87,7 @@ export async function getStaticInfoIncludingLayouts({
}
const config = reduceAppConfig(segments)
const supportsMarkdown = segments.some((segment) => segment.supportsMarkdown)
return {
...pageStaticInfo,
......@@ -94,5 +95,6 @@ export async function getStaticInfoIncludingLayouts({
runtime: config.runtime,
preferredRegion: config.preferredRegion,
maxDuration: config.maxDuration,
supportsMarkdown,
}
}
......@@ -195,7 +195,7 @@ export function makeExternalHandler({
}
const notExternalModules =
/^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|cache|document|link|form|head|image|legacy\/image|constants|dynamic|script|navigation|headers|router|compat\/router|server)$)|string-hash|private-next-rsc-action-validate|private-next-rsc-action-client-wrapper|private-next-rsc-server-reference|private-next-rsc-cache-wrapper|private-next-rsc-track-dynamic-import$)/
/^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|cache|document|link|form|head|image|legacy\/image|constants|dynamic|script|navigation|headers|router|compat\/router|server)$)|string-hash|next-markdown-import-source-file|private-next-rsc-action-validate|private-next-rsc-action-client-wrapper|private-next-rsc-server-reference|private-next-rsc-cache-wrapper|private-next-rsc-track-dynamic-import$)/
if (notExternalModules.test(request)) {
return
}
......
......@@ -583,6 +583,7 @@ export interface FunctionsConfigManifest {
functions: Record<
string,
{
markdown?: boolean | undefined
maxDuration?: number | undefined
runtime?: 'nodejs'
regions?: string[] | string
......@@ -2216,9 +2217,20 @@ export default async function build(
errorFromUnsupportedSegmentConfig()
}
// If there's any thing that would contribute to the functions
const pageRuntime = middlewareManifest.functions[
originalAppPath || page
]
? 'edge'
: staticInfo?.runtime
const supportsMarkdown =
config.experimental.markdown === true &&
staticInfo?.supportsMarkdown === true &&
!isEdgeRuntime(pageRuntime)
// If there's anything that would contribute to the functions
// configuration, we need to add it to the manifest.
if (
supportsMarkdown ||
typeof staticInfo?.runtime !== 'undefined' ||
typeof staticInfo?.maxDuration !== 'undefined' ||
typeof staticInfo?.preferredRegion !== 'undefined'
......@@ -2232,15 +2244,10 @@ export default async function build(
functionsConfigManifest.functions[page] = {
maxDuration: staticInfo?.maxDuration,
...(regions && { regions }),
...(supportsMarkdown && { markdown: true }),
}
}
const pageRuntime = middlewareManifest.functions[
originalAppPath || page
]
? 'edge'
: staticInfo?.runtime
if (!isCompileMode) {
isServerComponent =
pageType === 'app' &&
......
......@@ -38,6 +38,7 @@ import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_INSTANT_PREFETCH_HEADER,
NEXT_INSTANT_TEST_COOKIE,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_IS_PRERENDER_HEADER,
NEXT_DID_POSTPONE_HEADER,
RSC_CONTENT_TYPE_HEADER,
......@@ -72,6 +73,7 @@ import {
getPostponedStateExceededErrorMessage,
readBodyWithSizeLimit,
} from '../../server/lib/postponed-request-body'
import { acceptsMarkdown } from '../../server/markdown/accepts-markdown'
// These are injected by the loader afterwards.
......@@ -226,6 +228,14 @@ export async function handler(
getRequestMeta(req, 'isRSCRequest') ?? Boolean(req.headers[RSC_HEADER])
const isPossibleServerAction = getIsPossibleServerAction(req)
const isMarkdownRequest =
nextConfig.experimental.markdown === true &&
(req.method === 'GET' || req.method === 'HEAD') &&
!isPossibleServerAction &&
!isRSCRequest &&
!isPrefetchRSCRequest &&
!req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] &&
acceptsMarkdown(req.headers.accept)
/**
* If the route being rendered is an app page, and the ppr feature has been
......@@ -480,7 +490,8 @@ export async function handler(
!supportsDynamicResponse &&
!isPossibleServerAction &&
!minimalPostponed &&
!isDynamicRSCRequest
!isDynamicRSCRequest &&
!isMarkdownRequest
) {
ssgCacheKey = resolvedPathname
}
......@@ -727,6 +738,7 @@ export async function handler(
: {}),
cacheComponents: Boolean(nextConfig.cacheComponents),
experimental: {
markdown: Boolean(nextConfig.experimental.markdown),
isRoutePPREnabled,
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
......
......@@ -20,6 +20,8 @@ export const getStaticPaths = hoist(userland, 'getStaticPaths')
export const getServerSideProps = hoist(userland, 'getServerSideProps')
export const config = hoist(userland, 'config')
export const reportWebVitals = hoist(userland, 'reportWebVitals')
export const markdown = hoist(userland, 'markdown')
export const generateMarkdown = hoist(userland, 'generateMarkdown')
// Re-export legacy methods.
export const unstable_getStaticProps = hoist(
......@@ -71,4 +73,6 @@ export const handler = getHandler({
getStaticPaths,
getStaticProps,
getServerSideProps,
markdown,
generateMarkdown,
})
......@@ -85,6 +85,8 @@ checkFields<Diff<{
: `
metadata?: any
generateMetadata?: Function
markdown?: any
generateMarkdown?: Function
viewport?: any
generateViewport?: Function
`
......@@ -154,6 +156,14 @@ if ('generateMetadata' in entry) {
checkFields<Diff<ResolvingMetadata, SecondArg<MaybeField<TEntry, 'generateMetadata'>>, 'generateMetadata'>>()
}
// Check the arguments and return type of the generateMarkdown function
if ('generateMarkdown' in entry) {
checkFields<Diff<${
options.type === 'page' ? 'PageProps' : 'LayoutProps'
}, FirstArg<MaybeField<TEntry, 'generateMarkdown'>>, 'generateMarkdown'>>()
checkFields<Diff<any, SecondArg<MaybeField<TEntry, 'generateMarkdown'>>, 'generateMarkdown'>>()
}
// Check the arguments and return type of the generateViewport function
if ('generateViewport' in entry) {
checkFields<Diff<${
......
......@@ -3,6 +3,7 @@ import type { ServerRuntime } from '../types'
export const TEXT_PLAIN_CONTENT_TYPE_HEADER = 'text/plain'
export const HTML_CONTENT_TYPE_HEADER = 'text/html; charset=utf-8'
export const JSON_CONTENT_TYPE_HEADER = 'application/json; charset=utf-8'
export const MARKDOWN_CONTENT_TYPE_HEADER = 'text/markdown; charset=utf-8'
export const NEXT_QUERY_PARAM_PREFIX = 'nxtP'
export const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI'
......@@ -61,6 +62,7 @@ export const PAGES_DIR_ALIAS = 'private-next-pages'
export const DOT_NEXT_ALIAS = 'private-dot-next'
export const ROOT_DIR_ALIAS = 'private-next-root-dir'
export const APP_DIR_ALIAS = 'private-next-app-dir'
export const MARKDOWN_COMPONENTS_ALIAS = 'next-markdown-import-source-file'
export const RSC_MOD_REF_PROXY_ALIAS = 'private-next-rsc-mod-ref-proxy'
export const RSC_ACTION_VALIDATE_ALIAS = 'private-next-rsc-action-validate'
export const RSC_ACTION_PROXY_ALIAS = 'private-next-rsc-server-reference'
......
import type { MarkdownComponents } from '../../../next-markdown/src'
import { existsSync, readFileSync, statSync } from 'node:fs'
import Module from 'node:module'
import { dirname, extname, isAbsolute, join, resolve } from 'node:path'
type MarkdownComponentsModule = {
default?: {
useMarkdownComponents?: () => MarkdownComponents
}
useMarkdownComponents?: () => MarkdownComponents
}
const MARKDOWN_COMPONENTS_CANDIDATES = [
join('src', 'markdown-components.tsx'),
join('src', 'markdown-components.ts'),
join('src', 'markdown-components.jsx'),
join('src', 'markdown-components.js'),
'markdown-components.tsx',
'markdown-components.ts',
'markdown-components.jsx',
'markdown-components.js',
]
const USER_MODULE_EXTENSIONS = [
'.ts',
'.tsx',
'.js',
'.jsx',
'.mjs',
'.cjs',
'.mts',
'.cts',
]
const userModuleCache = new Map<string, unknown>()
function getMarkdownComponentsPath(cwd: string): string | null {
for (const candidate of MARKDOWN_COMPONENTS_CANDIDATES) {
const filePath = join(cwd, candidate)
if (existsSync(filePath)) {
return filePath
}
}
return null
}
function isFile(filePath: string): boolean {
try {
return statSync(filePath).isFile()
} catch {
return false
}
}
function resolveUserModulePath(
fromFilename: string,
request: string
): string | null {
if (!request.startsWith('.') && !isAbsolute(request)) {
return null
}
const basePath = request.startsWith('.')
? resolve(dirname(fromFilename), request)
: request
if (isFile(basePath)) {
return basePath
}
for (const extension of USER_MODULE_EXTENSIONS) {
if (isFile(basePath + extension)) {
return basePath + extension
}
}
for (const extension of USER_MODULE_EXTENSIONS) {
const indexPath = join(basePath, `index${extension}`)
if (isFile(indexPath)) {
return indexPath
}
}
return null
}
function shouldEnableJsxTransform(filename: string): boolean {
const extension = extname(filename)
return extension === '.jsx' || extension === '.tsx'
}
function shouldUseTypeScriptParser(filename: string): boolean {
const extension = extname(filename)
return (
extension === '.ts' ||
extension === '.tsx' ||
extension === '.cts' ||
extension === '.mts'
)
}
function transformModule(code: string, filename: string): string {
// eslint-disable-next-line no-eval -- We need runtime `require` here so the Node-only SWC loader isn't statically bundled into edge-facing codepaths.
const dynamicRequire = eval('require') as NodeJS.Require
const { transformSync } = dynamicRequire(
'next/dist/build/swc'
) as typeof import('../build/swc')
const parser = shouldUseTypeScriptParser(filename)
? {
syntax: 'typescript' as const,
tsx: shouldEnableJsxTransform(filename),
}
: {
syntax: 'ecmascript' as const,
jsx: shouldEnableJsxTransform(filename),
}
return transformSync(code, {
filename,
jsc: {
parser,
transform: shouldEnableJsxTransform(filename)
? {
react: {
runtime: 'automatic',
},
}
: undefined,
},
module: {
type: 'commonjs',
},
isModule: 'unknown',
env: {
targets: {
node: process.versions.node ?? '20.19.0',
},
},
}).code
}
function executeUserModule(filePath: string): unknown {
const cached = userModuleCache.get(filePath)
if (cached) {
return cached
}
const source = readFileSync(filePath, 'utf8')
const transformed = transformModule(source, filePath)
const moduleRecord = { exports: {} as unknown }
userModuleCache.set(filePath, moduleRecord.exports)
const createRequire = Module.createRequire(filePath)
const localRequire = (request: string) => {
const resolvedUserModulePath = resolveUserModulePath(filePath, request)
if (resolvedUserModulePath) {
return executeUserModule(resolvedUserModulePath)
}
return createRequire(request)
}
// eslint-disable-next-line no-new-func -- We compile user-provided markdown-components modules to CommonJS and execute them in an isolated local module scope.
const wrapped = new Function(
'exports',
'require',
'module',
'__filename',
'__dirname',
transformed
) as (
exports: unknown,
require: (request: string) => unknown,
module: { exports: unknown },
__filename: string,
__dirname: string
) => void
wrapped(
moduleRecord.exports,
localRequire,
moduleRecord,
filePath,
dirname(filePath)
)
userModuleCache.set(filePath, moduleRecord.exports)
return moduleRecord.exports
}
function loadMarkdownComponentsModule(
filePath: string
): MarkdownComponentsModule {
return executeUserModule(filePath) as MarkdownComponentsModule
}
export function requireMarkdownComponents(): MarkdownComponents {
const filePath = getMarkdownComponentsPath(process.cwd())
if (!filePath) {
return {}
}
const mod = loadMarkdownComponentsModule(filePath)
const loadMarkdownComponents =
mod.useMarkdownComponents ?? mod.default?.useMarkdownComponents
if (typeof loadMarkdownComponents !== 'function') {
return {}
}
return loadMarkdownComponents()
}
......@@ -11,6 +11,7 @@ import {
import { getLayoutOrPageModule } from '../lib/app-dir-module'
import type { LoaderTree } from '../lib/app-dir-module'
import { interopDefault } from './interop-default'
import { markReactNode } from '../markdown/runtime'
import { parseLoaderTree } from '../../shared/lib/router/utils/parse-loader-tree'
import type { AppRenderContext, GetDynamicParamFromSegment } from './app-render'
import { createComponentStylesAndScripts } from './create-component-styles-and-scripts'
......@@ -855,6 +856,12 @@ async function createComponentTreeInternal(
}
}
if (ctx.markdownSegmentByComponent) {
pageElement = markReactNode(pageElement, {
segmentByComponent: ctx.markdownSegmentByComponent,
})
}
const isDefaultSegment = segment === DEFAULT_SEGMENT_KEY
const pageFilePath =
getConventionPathByType(tree, dir, 'page') ??
......@@ -1042,6 +1049,12 @@ async function createComponentTreeInternal(
)
}
if (ctx.markdownSegmentByComponent) {
serverSegment = markReactNode(serverSegment, {
segmentByComponent: ctx.markdownSegmentByComponent,
})
}
if (isRootLayoutWithChildrenSlotAndAtLeastOneMoreSlot) {
// TODO-APP: This is a hack to support unmatched parallel routes, which will throw `notFound()`.
// This ensures that a `HTTPAccessFallbackBoundary` is available for when that happens,
......
......@@ -142,6 +142,7 @@ export interface RenderOptsPartial {
isPrefetch?: boolean
htmlLimitedBots: string | undefined
experimental: {
markdown?: boolean
/**
* When true, it indicates that the current page supports partial
* prerendering.
......
......@@ -188,6 +188,7 @@ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({
export const experimentalSchema = {
adapterPath: z.string().optional(),
markdown: z.boolean().optional(),
useSkewCookie: z.boolean().optional(),
after: z.boolean().optional(),
appNavFailHandling: z.boolean().optional(),
......
......@@ -338,6 +338,7 @@ export interface LoggingConfig {
export interface ExperimentalConfig {
adapterPath?: string
appNewScrollHandler?: boolean
markdown?: boolean
useSkewCookie?: boolean
/** @deprecated use top-level `cacheHandlers` instead */
cacheHandlers?: NextConfig['cacheHandlers']
......@@ -1637,6 +1638,7 @@ export const defaultConfig = Object.freeze({
experimental: {
adapterPath: process.env.NEXT_ADAPTER_PATH || undefined,
appNewScrollHandler: false,
markdown: false,
useSkewCookie: false,
cssChunking: true,
multiZoneDraftMode: false,
......@@ -1787,6 +1789,7 @@ export interface NextConfigRuntime {
experimental: Pick<
NextConfigComplete['experimental'],
| 'markdown'
| 'ppr'
| 'taint'
| 'serverActions'
......@@ -1896,6 +1899,7 @@ export function getNextConfigRuntime(
devCacheControlNoCache: ex.devCacheControlNoCache,
exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild,
immutableAssetToken: ex.immutableAssetToken,
markdown: ex.markdown,
trustHostHeader: ex.trustHostHeader,
isExperimentalCompile: ex.isExperimentalCompile,
......
......@@ -504,11 +504,16 @@ export function generateValidatorFile(
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingMetadata
) => Promise<any> | any
generateMarkdown?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: any
) => Promise<any> | any
generateViewport?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingViewport
) => Promise<any> | any
metadata?: any
markdown?: any
viewport?: any
}
......@@ -522,6 +527,8 @@ export function generateValidatorFile(
getStaticPaths?: (context: any) => Promise<any> | any
getServerSideProps?: (context: any) => Promise<any> | any
getInitialProps?: (context: any) => Promise<any> | any
generateMarkdown?: (...args: any[]) => Promise<any> | any
markdown?: any
/**
* Segment configuration for legacy Pages Router pages.
* Validated at build-time by parsePagesSegmentConfig.
......@@ -544,11 +551,16 @@ export function generateValidatorFile(
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingMetadata
) => Promise<any> | any
generateMarkdown?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: any
) => Promise<any> | any
generateViewport?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingViewport
) => Promise<any> | any
metadata?: any
markdown?: any
viewport?: any
}
......@@ -739,11 +751,16 @@ export function generateValidatorFileStrict(
props: PageProps<Route>,
parent: ResolvingMetadata
) => Promise<any> | any
generateMarkdown?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: any
) => Promise<any> | any
generateViewport?: (
props: PageProps<Route>,
parent: ResolvingViewport
) => Promise<any> | any
metadata?: any
markdown?: any
viewport?: any
}
......@@ -757,6 +774,8 @@ export function generateValidatorFileStrict(
getStaticPaths?: (context: any) => Promise<any> | any
getServerSideProps?: (context: any) => Promise<any> | any
getInitialProps?: (context: any) => Promise<any> | any
generateMarkdown?: (...args: any[]) => Promise<any> | any
markdown?: any
/**
* Segment configuration for legacy Pages Router pages.
* Validated at build-time by parsePagesSegmentConfig.
......@@ -779,11 +798,16 @@ export function generateValidatorFileStrict(
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingMetadata
) => Promise<any> | any
generateMarkdown?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: any
) => Promise<any> | any
generateViewport?: (
props: { params: Promise<ParamMap[Route]> } & any,
parent: ResolvingViewport
) => Promise<any> | any
metadata?: any
markdown?: any
viewport?: any
}
......
import { acceptsMarkdown, appendAcceptVaryHeader } from './accepts-markdown'
describe('acceptsMarkdown', () => {
it('returns false when no accept header is present', () => {
expect(acceptsMarkdown(undefined)).toBe(false)
})
it('returns true when markdown is the preferred type', () => {
expect(acceptsMarkdown('text/markdown, text/html;q=0.9, */*;q=0.1')).toBe(
true
)
})
it('returns false when html is preferred', () => {
expect(acceptsMarkdown('text/html, text/markdown;q=0.5')).toBe(false)
})
})
describe('appendAcceptVaryHeader', () => {
it('appends Accept to an existing vary header', () => {
expect(appendAcceptVaryHeader('User-Agent')).toBe('User-Agent, Accept')
})
it('deduplicates Accept case-insensitively', () => {
expect(appendAcceptVaryHeader('accept, User-Agent')).toBe(
'accept, User-Agent'
)
})
it('supports array vary values', () => {
expect(appendAcceptVaryHeader(['User-Agent', 'Cookie'])).toBe(
'User-Agent, Cookie, Accept'
)
})
})
import { mediaType } from 'next/dist/compiled/@hapi/accept'
export function acceptsMarkdown(
accept: string | string[] | undefined
): boolean {
if (!accept) {
return false
}
const value = Array.isArray(accept) ? accept.join(', ') : accept
return mediaType(value, ['text/html', 'text/markdown']) === 'text/markdown'
}
export function appendAcceptVaryHeader(
vary: string | string[] | number | undefined
): string {
const values = (
Array.isArray(vary)
? vary.flatMap((entry) => String(entry).split(','))
: typeof vary === 'string'
? vary.split(',')
: []
)
.map((value) => value.trim())
.filter(Boolean)
if (values.some((value) => value.toLowerCase() === 'accept')) {
return values.join(', ')
}
values.push('Accept')
return values.join(', ')
}
import type { MarkdownComponents } from '../../../../next-markdown/src'
export function useMarkdownComponents(): MarkdownComponents {
return {}
}
/* eslint-disable @next/internal/no-ambiguous-jsx -- Test fixtures use concise JSX trees to exercise React-to-Markdown instrumentation. */
import React from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import {
markReactNode,
renderHtmlToMarkdown,
type MarkdownSegmentDefinition,
} from '../../../../next-markdown/src'
describe('markdown renderer', () => {
it('serializes basic markdown blocks', async () => {
const markdown = await renderHtmlToMarkdown(
[
'<h1>Hello</h1>',
'<p><strong>World</strong> <a href="/docs">docs</a></p>',
'<pre><code class="language-ts">const value = 1</code></pre>',
'<ul><li>One</li><li>Two</li></ul>',
].join('')
)
expect(markdown).toBe(
'# Hello\n\n**World** [docs](/docs)\n\n```ts\nconst value = 1\n```\n\n- One\n- Two'
)
})
it('normalizes full-document html before serializing markdown', async () => {
const markdown = await renderHtmlToMarkdown(
'<!DOCTYPE html><html><body><h1>Hello</h1><p>World</p></body></html>'
)
expect(markdown).toBe('# Hello\n\nWorld')
})
it('serializes images, tables, and nested lists', async () => {
const markdown = await renderHtmlToMarkdown(
[
'<img src="/logo.png" alt="Logo" />',
'<table><tr><th>Name</th><th>Value</th></tr><tr><td>A</td><td>1</td></tr></table>',
'<ul><li>One<ul><li>Nested</li></ul></li><li>Two</li></ul>',
].join('')
)
expect(markdown).toBe(
'![Logo](/logo.png)\n\n| Name | Value |\n| --- | --- |\n| A | 1 |\n\n- One\n - Nested\n- Two'
)
})
it('drops interactive host nodes by default and allows tag overrides', async () => {
const Interactive = () => (
<div>
<div onClick={() => {}}>Action card</div>
<button>Ignored</button>
</div>
)
const html = renderToStaticMarkup(
markReactNode(<Interactive />) as React.ReactElement
)
const withoutOverride = await renderHtmlToMarkdown(html)
const withOverride = await renderHtmlToMarkdown(html, {
rootComponents: {
div({ attributes, children, renderDefault }) {
if (attributes['data-react-markdown-interactive'] === 'true') {
return `ACTION: ${children || renderDefault()}`
}
return renderDefault()
},
button({ children }) {
return `BUTTON: ${children}`
},
},
})
expect(withoutOverride).toBe('')
expect(withOverride).toContain('ACTION: Action card')
expect(withOverride).toContain('BUTTON: Ignored')
})
it('prefers component-name overrides over tag overrides', async () => {
function FancyButton() {
return <button>Download</button>
}
const html = renderToStaticMarkup(
markReactNode(<FancyButton />) as React.ReactElement
)
const markdown = await renderHtmlToMarkdown(html, {
rootComponents: {
button() {
return 'tag override'
},
FancyButton() {
return 'component override'
},
},
})
expect(markdown).toBe('component override')
})
it('supports forwardRef and memo component-name overrides', async () => {
const FancyAction = React.forwardRef<HTMLButtonElement>(
function FancyAction(_props, ref) {
return <button ref={ref}>Save</button>
}
)
const MemoNote = React.memo(function MemoNote() {
return <p>Memo note</p>
})
const html = renderToStaticMarkup(
markReactNode(
<>
<FancyAction />
<MemoNote />
</>
) as React.ReactElement
)
const markdown = await renderHtmlToMarkdown(html, {
rootComponents: {
FancyAction() {
return 'forward-ref override'
},
MemoNote() {
return 'memo override'
},
},
})
expect(markdown).toBe('forward-ref override\n\nmemo override')
})
it('allows overrides to omit output by returning null', async () => {
const markdown = await renderHtmlToMarkdown(
'<p>Keep me?</p><img src="/x.png" alt="X" />',
{
rootComponents: {
p() {
return null
},
},
}
)
expect(markdown).toBe('![X](/x.png)')
})
it('preserves inline spacing and formatting for paragraph overrides', async () => {
const markdown = await renderHtmlToMarkdown(
'<p>Hello <strong>wide</strong> world</p>',
{
rootComponents: {
p({ children }) {
return `root:${children}`
},
},
}
)
expect(markdown).toBe('root:Hello **wide** world')
})
it('composes nested segments with child precedence', async () => {
const segments = new Map<string, MarkdownSegmentDefinition>([
[
'layout',
{
id: 'layout',
props: { title: 'Outer' },
components: {
p({ children }) {
return `layout:${children}`
},
},
async render(_props, { children }) {
return `layout-start\n${await children}\nlayout-end`
},
},
],
[
'page',
{
id: 'page',
props: { slug: 'hello' },
components: {
p({ children }) {
return `page:${children}`
},
},
render(_props, { renderDefault }) {
return renderDefault()
},
},
],
])
const markdown = await renderHtmlToMarkdown(
[
'<react-markdown-segment-marker data-segment-id="layout">',
'<section>',
'<react-markdown-segment-marker data-segment-id="page">',
'<p>Hello</p>',
'</react-markdown-segment-marker>',
'</section>',
'</react-markdown-segment-marker>',
].join(''),
{
rootComponents: {
p({ children }) {
return `root:${children}`
},
},
segments,
}
)
expect(markdown).toBe('layout-start\npage:Hello\nlayout-end')
})
it('registers segment props while instrumenting components', () => {
const captured: Array<any> = []
function Page(props: { title: string }) {
return <p>{props.title}</p>
}
const html = renderToStaticMarkup(
markReactNode(<Page title="Hello" />, {
segmentByComponent: new Map([
[
Page,
{
id: 'page',
registerProps(props) {
captured.push(props)
},
},
],
]),
}) as React.ReactElement
)
expect(captured).toEqual([{ title: 'Hello' }])
expect(html).toContain('data-segment-id="page"')
})
it('does not invoke client reference component types while instrumenting', () => {
const RawClientReference = function ClientReference() {
throw new Error('should not be called by markReactNode')
}
const ClientReference = new Proxy(RawClientReference, {
get(target, property, receiver) {
if (property === 'prototype') {
throw new Error('should not inspect prototype')
}
return Reflect.get(target, property, receiver)
},
})
;(ClientReference as any).$$typeof = Symbol.for('react.client.reference')
;(ClientReference as any).$$id = '/app/client-widget.jsx#ClientReference'
const marked = markReactNode(
React.createElement(ClientReference as any, { label: 'Hello' })
) as React.ReactElement
const markedChild = (marked.props as { children: React.ReactElement })
.children
expect(React.isValidElement(marked)).toBe(true)
expect(marked.type).toBe('react-markdown-component-marker')
expect((marked.props as { 'data-name': string })['data-name']).toBe(
'ClientReference'
)
expect(markedChild.type).toBe(ClientReference)
})
})
import type {
MarkdownComponent,
MarkdownComponentContext,
MarkdownComponents,
MarkdownSegmentDefinition,
} from '../../../../next-markdown/src'
type MarkdownRuntimeModule = typeof import('../../../../next-markdown/src')
let runtime: MarkdownRuntimeModule | null = null
function getMarkdownRuntime(): MarkdownRuntimeModule {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new Error('Markdown output is not supported in the Edge runtime.')
}
if (runtime) {
return runtime
}
try {
runtime =
require('../../../../next-markdown/src') as typeof import('../../../../next-markdown/src')
} catch {
runtime = require('@next/markdown') as typeof import('@next/markdown')
}
return runtime
}
export const MARKDOWN_COMPONENT_MARKER_TAG = 'react-markdown-component-marker'
export const MARKDOWN_INTERACTIVE_ATTR = 'data-react-markdown-interactive'
export const MARKDOWN_SEGMENT_MARKER_TAG = 'react-markdown-segment-marker'
export function markReactNode(
...args: Parameters<MarkdownRuntimeModule['markReactNode']>
) {
return getMarkdownRuntime().markReactNode(...args)
}
export function renderHtmlToMarkdown(
...args: Parameters<MarkdownRuntimeModule['renderHtmlToMarkdown']>
) {
return getMarkdownRuntime().renderHtmlToMarkdown(...args)
}
export type {
MarkdownComponent,
MarkdownComponentContext,
MarkdownComponents,
MarkdownSegmentDefinition,
}
......@@ -14,6 +14,7 @@ import { InvariantError } from '../shared/lib/invariant-error'
import type {
HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER,
MARKDOWN_CONTENT_TYPE_HEADER,
TEXT_PLAIN_CONTENT_TYPE_HEADER,
} from '../lib/constants'
import type { RSC_CONTENT_TYPE_HEADER } from '../client/components/app-router-headers'
......@@ -21,6 +22,7 @@ import type { RSC_CONTENT_TYPE_HEADER } from '../client/components/app-router-he
type ContentTypeOption =
| typeof RSC_CONTENT_TYPE_HEADER // For App Page RSC responses
| typeof HTML_CONTENT_TYPE_HEADER // For App Page, Pages HTML responses
| typeof MARKDOWN_CONTENT_TYPE_HEADER // For App Page, Pages Markdown responses
| typeof JSON_CONTENT_TYPE_HEADER // For API routes, Next.js data requests
| typeof TEXT_PLAIN_CONTENT_TYPE_HEADER // For simplified errors
......@@ -63,6 +65,8 @@ export type PagesRenderResultMetadata = {
mutableAssetQueryString?: string
isNotFound?: boolean
isRedirect?: boolean
headers?: OutgoingHttpHeaders
statusCode?: number
}
export type StaticRenderResultMetadata = {}
......
......@@ -54,6 +54,7 @@ import {
UNSTABLE_REVALIDATE_RENAME_ERROR,
HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER,
MARKDOWN_CONTENT_TYPE_HEADER,
} from '../lib/constants'
import {
NEXT_BUILTIN_DOCUMENT,
......@@ -106,6 +107,16 @@ import { getErrorSource } from '../shared/lib/error-source'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'
import { getScriptNonceFromHeader } from './app-render/get-script-nonce-from-header'
import {
acceptsMarkdown,
appendAcceptVaryHeader,
} from './markdown/accepts-markdown'
import {
markReactNode,
type MarkdownComponents,
type MarkdownSegmentDefinition,
renderHtmlToMarkdown,
} from './markdown/runtime'
let tryGetPreviewData: typeof import('./api-utils/node/try-get-preview-data').tryGetPreviewData
let warn: typeof import('../build/output/log').warn
......@@ -128,6 +139,16 @@ if (process.env.NEXT_RUNTIME !== 'edge') {
postProcessHTML = async (html: string) => html
}
function loadMarkdownRootComponents(): MarkdownComponents {
if (process.env.NEXT_RUNTIME === 'edge') {
return {}
}
return (
require('../lib/require-markdown-components') as typeof import('../lib/require-markdown-components')
).requireMarkdownComponents()
}
function noRouter() {
const message =
'No router instance found. you should only use "next/router" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance'
......@@ -140,6 +161,35 @@ async function renderToString(element: React.ReactElement) {
return streamToString(renderStream)
}
function normalizeMarkdownRouteConfig(markdown: unknown): {
enabled: boolean
components: MarkdownComponents
} {
if (markdown === true) {
return {
enabled: true,
components: {},
}
}
if (markdown && typeof markdown === 'object') {
return {
enabled: true,
components:
'components' in markdown &&
markdown.components &&
typeof markdown.components === 'object'
? (markdown.components as MarkdownComponents)
: {},
}
}
return {
enabled: false,
components: {},
}
}
class ServerRouter implements NextRouter {
route: string
pathname: string
......@@ -285,6 +335,7 @@ export type RenderOptsPartial = {
isBot?: boolean
expireTime?: number
experimental: {
markdown?: boolean
clientTraceMetadata?: string[]
}
}
......@@ -1233,6 +1284,92 @@ export async function renderToHTMLImpl(
// the response might be finished on the getInitialProps call
if (isResSent(res) && !isSSG) return RenderResult.EMPTY
const markdownConfig = normalizeMarkdownRouteConfig(
(renderOpts.ComponentMod as any).markdown
)
const generateMarkdown =
typeof (renderOpts.ComponentMod as any).generateMarkdown === 'function'
? (renderOpts.ComponentMod as any).generateMarkdown
: undefined
const supportsMarkdownResponse =
renderOpts.experimental.markdown === true &&
process.env.NEXT_RUNTIME !== 'edge' &&
(req.method === 'GET' || req.method === 'HEAD') &&
(markdownConfig.enabled || generateMarkdown)
const acceptsMarkdownRequest = acceptsMarkdown(req.headers.accept)
const wantsMarkdown = supportsMarkdownResponse && acceptsMarkdownRequest
if (supportsMarkdownResponse) {
metadata.headers ??= {}
metadata.headers.vary = appendAcceptVaryHeader(
res.getHeader('vary') ?? metadata.headers.vary
)
}
if (wantsMarkdown) {
const pageDefinition: MarkdownSegmentDefinition = {
id: 'page',
props: {},
components: markdownConfig.components,
render: generateMarkdown
? async (pageProps, { renderDefault }) =>
generateMarkdown(
{
props: pageProps,
query,
},
{
renderDefault,
}
)
: undefined,
}
const markdownSegmentByComponent = new Map([
[
Component,
{
id: pageDefinition.id,
registerProps(componentProps: any) {
pageDefinition.props = componentProps
},
},
],
])
const MarkdownPageComponent = function NextMarkdownPageComponent(
pageProps: Record<string, any>
) {
return markReactNode(React.createElement(Component, pageProps), {
segmentByComponent: markdownSegmentByComponent,
}) as React.ReactElement
}
MarkdownPageComponent.displayName = `NextMarkdownPage(${getDisplayName(
Component
)})`
const pageContent = renderPageTree(App, MarkdownPageComponent, {
...props,
router,
})
const html = await renderToString(pageContent as React.ReactElement)
const markdown = await renderHtmlToMarkdown(html, {
rootComponents: loadMarkdownRootComponents(),
segments: new Map([[pageDefinition.id, pageDefinition]]),
})
metadata.headers ??= {}
metadata.headers['Content-Type'] = MARKDOWN_CONTENT_TYPE_HEADER
metadata.statusCode = res.statusCode
return new RenderResult(markdown, {
metadata,
contentType: MARKDOWN_CONTENT_TYPE_HEADER,
})
}
// we preload the buildManifest for auto-export dynamic pages
// to speed up hydrating query values
let filteredBuildManifest = buildManifest
......
......@@ -6,6 +6,7 @@ import type {
NextComponentType,
PageConfig,
} from '../../../types'
import type { ParsedUrlQuery } from 'querystring'
import type { PagesRouteDefinition } from '../../route-definitions/pages-route-definition'
import type { NextParsedUrlQuery } from '../../request-meta'
import type {
......@@ -60,6 +61,19 @@ export type PagesUserlandModule = {
* The exported `getServerSideProps` function.
*/
readonly getServerSideProps?: GetServerSideProps
/**
* Enables Markdown output for this page route.
*/
readonly markdown?: unknown
/**
* Generates Markdown output for this page route.
*/
readonly generateMarkdown?: (
context: { props: any; query: ParsedUrlQuery },
helpers: { renderDefault(): Promise<string> }
) => Promise<string> | string
}
/**
......
......@@ -48,6 +48,7 @@ import type {
GetStaticPaths,
GetStaticProps,
} from '../../../types'
import { acceptsMarkdown } from '../../markdown/accepts-markdown'
export const getHandler = ({
srcPage: originalSrcPage,
......@@ -58,6 +59,8 @@ export const getHandler = ({
getStaticPaths,
getStaticProps,
getServerSideProps,
markdown,
generateMarkdown,
}: {
srcPage: string
config: Record<string, any> | undefined
......@@ -67,6 +70,8 @@ export const getHandler = ({
getStaticProps?: GetStaticProps
getStaticPaths?: GetStaticPaths
getServerSideProps?: GetServerSideProps
markdown?: unknown
generateMarkdown?: unknown
}) => {
return async function handler(
req: IncomingMessage,
......@@ -162,6 +167,11 @@ export const getHandler = ({
let isIsrFallback = false
let isNextDataRequest =
prepareResult.isNextDataRequest && (hasStaticProps || hasServerProps)
const isMarkdownRequest =
nextConfig.experimental.markdown === true &&
(req.method === 'GET' || req.method === 'HEAD') &&
!isNextDataRequest &&
acceptsMarkdown(req.headers.accept)
const is404Page = srcPage === '/404'
const is500Page = srcPage === '/500'
......@@ -180,6 +190,10 @@ export const getHandler = ({
// ensure /index and / is normalized to one key
cacheKey = cacheKey === '/index' ? '/' : cacheKey
if (cacheKey && isMarkdownRequest) {
cacheKey += '?__next_markdown=1'
}
}
if (hasStaticPaths && !isDraftMode) {
......@@ -277,7 +291,14 @@ export const getHandler = ({
page: srcPage,
pageConfig: config || {},
Component: interopDefault(userland),
ComponentMod: userland,
ComponentMod:
markdown !== undefined || generateMarkdown !== undefined
? {
...userland,
markdown,
generateMarkdown,
}
: userland,
getStaticProps,
getStaticPaths,
getServerSideProps,
......@@ -309,6 +330,7 @@ export const getHandler = ({
isExperimentalCompile,
experimental: {
markdown: Boolean(nextConfig.experimental.markdown),
clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata ||
([] as any),
......
......@@ -17,6 +17,8 @@ export const ALLOWED_EXPORTS = [
'generateStaticParams',
'metadata',
'generateMetadata',
'markdown',
'generateMarkdown',
'viewport',
'generateViewport',
]
......
export * from './dist/types'
export { default } from './dist/types'
export * from './dist/next/src/types'
export { default } from './dist/next/src/types'
This diff is collapsed.
export const markdown = true
export const dynamic = 'force-dynamic'
export default function AppBasicPage() {
return (
<main>
<h1>App Basic</h1>
<p>App paragraph</p>
<button>Ignore me</button>
</main>
)
}
'use client'
export function ClientWidget() {
return (
<section>
<p>Client paragraph</p>
<button>Tap me</button>
</section>
)
}
import { ClientWidget } from './client-widget'
export const markdown = true
export const dynamic = 'force-dynamic'
export default function AppClientPage() {
return <ClientWidget />
}
export const markdown = {
components: {
p({ children }) {
return `inner:${children}`
},
},
}
export async function generateMarkdown(_props, { children }) {
return `inner-start\n${await children}\ninner-end`
}
export default function InnerLayout({ children }) {
return <article>{children}</article>
}
export const markdown = {
components: {
p({ children }) {
return `page:${children}`
},
},
}
export const dynamic = 'force-dynamic'
export async function generateMarkdown(_props, { renderDefault }) {
return renderDefault()
}
export default function AppComposedPage() {
return <p>Nested value</p>
}
export const markdown = {
components: {
p({ children }) {
return `outer:${children}`
},
},
}
export async function generateMarkdown(_props, { children }) {
return `outer-start\n${await children}\nouter-end`
}
export default function OuterLayout({ children }) {
return <section>{children}</section>
}
export const markdown = true
export const runtime = 'edge'
export default function AppEdgePage() {
return (
<main>
<h1>App Edge</h1>
<p>Edge paragraph</p>
</main>
)
}
export function ActionButton() {
return <button>Download</button>
}
ActionButton.displayName = 'ActionButton'
'use client'
export function InteractiveCard() {
return <div onClick={() => {}}>Card</div>
}
InteractiveCard.displayName = 'InteractiveCard'
import { ActionButton } from './action-button'
import { InteractiveCard } from './interactive-card'
export const markdown = {
components: {
button({ children }) {
return `tag:${children}`
},
ActionButton() {
return 'component:Download'
},
InteractiveCard() {
return 'action:Card'
},
},
}
export const dynamic = 'force-dynamic'
export default function AppOverridePage() {
return (
<main>
<InteractiveCard />
<ActionButton />
<p>Override paragraph</p>
</main>
)
}
export const markdown = true
export async function generateStaticParams() {
return [{ slug: 'alpha' }]
}
export default async function AppStaticPage({ params }) {
const { slug } = await params
return (
<main>
<h1>App Static {slug}</h1>
<p>Static paragraph {slug}</p>
</main>
)
}
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function HomePage() {
return (
<main>
<h1>Home HTML Only</h1>
<p>Default HTML response</p>
</main>
)
}
export function useMarkdownComponents() {
return {
p({ children }) {
return `root:${children}`
},
}
}
import { nextTestSetup } from 'e2e-utils'
import {
NEXT_RSC_UNION_QUERY,
RSC_HEADER,
} from 'next/dist/client/components/app-router-headers'
describe('experimental markdown output', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('keeps html by default for opted-in app routes', async () => {
const response = await next.fetch('/app-basic')
const html = await response.text()
expect(response.headers.get('content-type')).toContain('text/html')
expect(response.headers.get('vary')).toContain('Accept')
expect(html).toContain('<h1>App Basic</h1>')
expect(html).toContain('Ignore me')
})
it('returns markdown for opted-in app routes when markdown is preferred', async () => {
const response = await next.fetch('/app-basic', {
headers: {
accept: 'text/markdown, text/html;q=0.9',
},
})
const markdown = await response.text()
expect(response.headers.get('content-type')).toBe(
'text/markdown; charset=utf-8'
)
expect(response.headers.get('vary')).toContain('Accept')
expect(markdown).toMatchInlineSnapshot(`
"# App Basic
root:App paragraph"
`)
})
it('returns markdown for app routes generated by generateStaticParams', async () => {
const response = await next.fetch('/app-static/alpha', {
headers: {
accept: 'text/markdown',
},
})
expect(response.headers.get('content-type')).toBe(
'text/markdown; charset=utf-8'
)
expect(response.headers.get('vary')).toContain('Accept')
expect(await response.text()).toMatchInlineSnapshot(`
"# App Static alpha
root:Static paragraph alpha"
`)
})
it('returns markdown headers for HEAD requests without a response body', async () => {
const response = await next.fetch('/app-basic', {
method: 'HEAD',
headers: {
accept: 'text/markdown',
},
})
expect(response.headers.get('content-type')).toBe(
'text/markdown; charset=utf-8'
)
expect(response.headers.get('vary')).toContain('Accept')
expect(await response.text()).toBe('')
})
it('does not negotiate markdown for routes without opt-in', async () => {
const response = await next.fetch('/', {
headers: {
accept: 'text/markdown',
},
})
const html = await response.text()
expect(response.headers.get('content-type')).toContain('text/html')
expect(html).toContain('<h1>Home HTML Only</h1>')
})
it('composes app layouts bottom-up with child component precedence', async () => {
const response = await next.fetch('/app-composed/inner', {
headers: {
accept: 'text/markdown',
},
})
expect(await response.text()).toMatchInlineSnapshot(`
"outer-start
inner-start
page:Nested value
inner-end
outer-end"
`)
})
it('supports component-name overrides before tag overrides and can reintroduce interactive output', async () => {
const response = await next.fetch('/app-override', {
headers: {
accept: 'text/markdown',
},
})
const markdown = await response.text()
expect(markdown).toMatchInlineSnapshot(`
"action:Card
component:Download
root:Override paragraph"
`)
expect(markdown).not.toContain('tag:Download')
})
it('serializes SSR-able client components and still omits interactive controls by default', async () => {
const response = await next.fetch('/app-client', {
headers: {
accept: 'text/markdown',
},
})
const markdown = await response.text()
expect(markdown).toMatchInlineSnapshot(`"root:Client paragraph"`)
expect(markdown).not.toContain('Tap me')
})
it('does not enable markdown negotiation in the edge runtime', async () => {
const response = await next.fetch('/app-edge', {
headers: {
accept: 'text/markdown',
},
})
expect(response.headers.get('content-type')).toContain('text/html')
expect(await response.text()).toContain('<h1>App Edge</h1>')
})
it('returns markdown for opted-in pages routes when markdown is preferred', async () => {
const response = await next.fetch('/pages-basic', {
headers: {
accept: 'text/markdown',
},
})
const markdown = await response.text()
expect(response.headers.get('content-type')).toBe(
'text/markdown; charset=utf-8'
)
expect(response.headers.get('vary')).toContain('Accept')
expect(markdown).toMatchInlineSnapshot(`
"# Pages Basic
root:Pages paragraph"
`)
})
it('keeps html by default for opted-in pages routes', async () => {
const response = await next.fetch('/pages-basic')
const html = await response.text()
expect(response.headers.get('content-type')).toContain('text/html')
expect(response.headers.get('vary')).toContain('Accept')
expect(html).toContain('<h1>Pages Basic</h1>')
})
it('supports pages generateMarkdown with resolved props and query', async () => {
const response = await next.fetch('/pages-custom?id=123', {
headers: {
accept: 'text/markdown',
},
})
expect(await response.text()).toMatchInlineSnapshot(`
"custom-start
message:hello-123
query:123
default:root:hello-123
custom-end"
`)
})
it('keeps next data requests as json even when markdown is preferred', async () => {
const response = await next.fetch(
`/_next/data/${next.buildId}/pages-custom.json?id=123`,
{
headers: {
accept: 'text/markdown',
},
}
)
expect(response.headers.get('content-type')).toContain('application/json')
await expect(response.json()).resolves.toMatchObject({
pageProps: {
message: 'hello-123',
},
})
})
it('keeps rsc requests as flight payload even when markdown is preferred', async () => {
const response = await next.fetch(`/app-basic?${NEXT_RSC_UNION_QUERY}`, {
headers: {
[RSC_HEADER]: '1',
accept: 'text/markdown',
},
})
const body = await response.text()
expect(response.headers.get('content-type')).toBe('text/x-component')
expect(body).toContain('__PAGE__')
expect(body).not.toContain('# App Basic')
})
})
module.exports = {
experimental: {
markdown: true,
},
}
export const markdown = true
export async function getServerSideProps() {
return {
props: {},
}
}
export default function PagesBasicPage() {
return (
<main>
<h1>Pages Basic</h1>
<p>Pages paragraph</p>
<button>Ignore me</button>
</main>
)
}
export const markdown = true
export async function getServerSideProps(context) {
return {
props: {
message: `hello-${context.query.id ?? 'missing'}`,
},
}
}
export async function generateMarkdown(context, { renderDefault }) {
const defaultMarkdown = await renderDefault()
return [
'custom-start',
`message:${context.props.message}`,
`query:${context.query.id}`,
`default:${defaultMarkdown}`,
'custom-end',
].join('\n')
}
export default function PagesCustomPage({ message }) {
return <p>{message}</p>
}
......@@ -51,6 +51,8 @@ describe('adapter-config', () => {
...outputs.pages,
...outputs.pagesApi,
]
const routeByPathname = (pathname: string) =>
combinedRouteOutputs.find((output) => output.pathname === pathname)
type PageRoutesType =
| AdapterOutput['APP_PAGE']
......@@ -88,6 +90,27 @@ describe('adapter-config', () => {
expect(edgeOutputs.length).toBeGreaterThan(0)
expect(staticOutputs.length).toBeGreaterThan(0)
expect(prerenderOutputs.length).toBeGreaterThan(0)
expect(routeByPathname('/docs/node-app.markdown')).toMatchObject({
pathname: '/docs/node-app.markdown',
runtime: 'nodejs',
filePath: routeByPathname('/docs/node-app')?.filePath,
})
expect(routeByPathname('/docs/node-app/[slug].markdown')).toMatchObject({
pathname: '/docs/node-app/[slug].markdown',
runtime: 'nodejs',
filePath: routeByPathname('/docs/node-app/[slug]')?.filePath,
})
expect(routeByPathname('/docs/node-pages.markdown')).toMatchObject({
pathname: '/docs/node-pages.markdown',
runtime: 'nodejs',
filePath: routeByPathname('/docs/node-pages')?.filePath,
})
expect(routeByPathname('/docs/node-app.rsc.markdown')).toBe(undefined)
expect(
routeByPathname(`/_next/data/${ctx.buildId}/node-pages.json.markdown`)
).toBe(undefined)
expect(routeByPathname('/docs/edge-app.markdown')).toBe(undefined)
expect(routeByPathname('/docs/edge-pages.markdown')).toBe(undefined)
for (const output of staticOutputs) {
expect(output.id).toBeTruthy()
......
export const runtime = 'edge'
export const markdown = true
export default function Page() {
return (
......
export const markdown = true
export default function Layout({ dialog, children }: any) {
return (
<>
......
......@@ -138,6 +138,8 @@ const myAdapter = {
appPagePathnames.set(basePathname, { rsc: false, nonRsc: false })
}
appPagePathnames.get(basePathname).rsc = true
} else if (pathname.endsWith('.markdown')) {
continue
} else {
const normalizedPathname = normalizePathname(pathname)
if (!appPagePathnames.has(normalizedPathname)) {
......@@ -170,6 +172,47 @@ const myAdapter = {
)
}
const markdownVariantSets = [...ctx.outputs.appPages, ...ctx.outputs.pages]
const markdownPathnames = new Map()
for (const output of markdownVariantSets) {
const pathname = output.pathname
if (pathname.endsWith('.markdown')) {
const basePathname = normalizePathname(pathname.slice(0, -9))
if (!markdownPathnames.has(basePathname)) {
markdownPathnames.set(basePathname, { markdown: false, base: false })
}
markdownPathnames.get(basePathname).markdown = true
} else if (!pathname.endsWith('.rsc')) {
const normalizedPathname = normalizePathname(pathname)
if (!markdownPathnames.has(normalizedPathname)) {
markdownPathnames.set(normalizedPathname, {
markdown: false,
base: false,
})
}
markdownPathnames.get(normalizedPathname).base = true
}
}
for (const [pathname, versions] of markdownPathnames.entries()) {
if (versions.markdown && !versions.base) {
validationErrors.push(
`Markdown output ${pathname}.markdown is missing corresponding base pathname`
)
}
}
const markdownVariantCount = Array.from(markdownPathnames.values()).filter(
(versions) => versions.markdown
).length
if (markdownVariantCount > 0) {
console.log(
`Validated ${markdownVariantCount} markdown pathname variant(s) have matching base pathnames`
)
}
if (validationErrors.length > 0) {
console.error('Validation errors:')
for (const error of validationErrors) {
......
......@@ -5,6 +5,7 @@ const require = Module.createRequire(import.meta.url)
const nextConfig = {
experimental: {
adapterPath: require.resolve('./my-adapter.mjs'),
markdown: true,
},
cacheComponents: process.env.TEST_CACHE_COMPONENTS === '1',
rewrites() {
......
import { NextApiRequest, NextApiResponse } from 'next/dist/types'
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
console.log(req.url)
......
export const config = {
runtime: 'experimental-edge',
}
export const markdown = true
export default function Page() {
return (
......
......@@ -6,6 +6,10 @@ export function getServerSideProps() {
}
}
export async function generateMarkdown(_context, { renderDefault }) {
return renderDefault()
}
export default function Page(props) {
return (
<>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment