|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import { compile, CompileOptions } from '@mdx-js/mdx' |
|
|
import { VFile, VFileCompatible } from 'vfile' |
|
|
import { matter } from 'vfile-matter' |
|
|
|
|
|
import { createFormattedMDXError } from './format-mdx-error.js' |
|
|
import { removeImportsExportsPlugin } from './plugins/remove-imports-exports.js' |
|
|
|
|
|
|
|
|
import type { MDXRemoteSerializeResult, SerializeOptions } from './types.js' |
|
|
|
|
|
function getCompileOptions( |
|
|
mdxOptions: SerializeOptions['mdxOptions'] = {}, |
|
|
rsc: boolean = false |
|
|
): CompileOptions { |
|
|
const areImportsEnabled = mdxOptions.useDynamicImport ?? false |
|
|
|
|
|
|
|
|
const remarkPlugins = [ |
|
|
...(mdxOptions.remarkPlugins || []), |
|
|
...(areImportsEnabled ? [] : [removeImportsExportsPlugin]), |
|
|
] |
|
|
|
|
|
return { |
|
|
...mdxOptions, |
|
|
remarkPlugins, |
|
|
outputFormat: 'function-body', |
|
|
|
|
|
providerImportSource: rsc ? undefined : '@mdx-js/react', |
|
|
development: process.env.NODE_ENV !== 'production', |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export async function serialize< |
|
|
TScope = Record<string, unknown>, |
|
|
TFrontmatter = Record<string, unknown> |
|
|
>( |
|
|
source: VFileCompatible, |
|
|
{ |
|
|
scope = {}, |
|
|
mdxOptions = {}, |
|
|
parseFrontmatter = false, |
|
|
}: SerializeOptions = {}, |
|
|
rsc: boolean = false |
|
|
): Promise<MDXRemoteSerializeResult<TScope, TFrontmatter>> { |
|
|
const vfile = new VFile(source) |
|
|
|
|
|
|
|
|
if (parseFrontmatter) { |
|
|
matter(vfile, { strip: true }) |
|
|
} |
|
|
|
|
|
let compiledMdx: VFile |
|
|
|
|
|
try { |
|
|
compiledMdx = await compile(vfile, getCompileOptions(mdxOptions, rsc)) |
|
|
} catch (error: any) { |
|
|
throw createFormattedMDXError(error, String(vfile)) |
|
|
} |
|
|
|
|
|
let compiledSource = String(compiledMdx) |
|
|
|
|
|
return { |
|
|
compiledSource, |
|
|
frontmatter: (vfile.data.matter ?? {}) as TFrontmatter, |
|
|
scope: scope as TScope, |
|
|
} |
|
|
} |
|
|
|