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
96 changes: 96 additions & 0 deletions packages/docusaurus-mdx-loader/src/__tests__/loader.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {describe, expect, it, vi} from 'vitest';
import {DEFAULT_PARSE_FRONT_MATTER} from '@docusaurus/utils';
import {mdxLoader} from '../loader';
import type {CrossCompilerCache, Options} from '../options';
import type {SimpleProcessor} from '../processor';
import type {WebpackCompilerName} from '@docusaurus/utils';
import type {LoaderContext} from 'webpack';

describe('mdxLoader', () => {
it('compiles MDX only once for client/server with cloned loader options', async () => {
const processor = createFakeProcessor();
const options = createOptions({processor});

const [clientResult, serverResult] = await Promise.all([
runLoader({compilerName: 'client', options: cloneOptions(options)}),
runLoader({compilerName: 'server', options: cloneOptions(options)}),
]);

expect(processor.process).toHaveBeenCalledTimes(1);
expect(serverResult).toEqual(clientResult);
});
});

function createFakeProcessor(): SimpleProcessor {
return {
process: vi.fn(async () => ({content: 'export default "MDX";', data: {}})),
};
}

function createOptions({processor}: {processor: SimpleProcessor}): Options {
const crossCompilerCache: CrossCompilerCache = new Map();
return {
siteDir: __dirname,
staticDirs: [],
markdownConfig: {
format: 'mdx',
parseFrontMatter: DEFAULT_PARSE_FRONT_MATTER,
mermaid: false,
emoji: true,
mdx1Compat: {comments: true, admonitions: true, headingIds: true},
anchors: {maintainCase: false},
remarkRehypeOptions: undefined,
hooks: {
onBrokenMarkdownLinks: 'throw',
onBrokenMarkdownImages: 'throw',
onUnusedMarkdownDirectives: 'throw',
},
},
processors: {mdProcessor: processor, mdxProcessor: processor},
getCrossCompilerCache: () => crossCompilerCache,
};
}

// Emulates tools that deep-clone the loader options, such as Rsdoctor v1:
// objects (including Maps) become plain objects, functions are kept as is
function cloneOptions<T>(value: T): T {
if (typeof value !== 'object' || value === null) {
return value;
}
if (Array.isArray(value)) {
return value.map(cloneOptions) as T;
}
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [key, cloneOptions(item)]),
) as T;
}

function runLoader({
compilerName,
options,
}: {
compilerName: WebpackCompilerName;
options: Options;
}): Promise<string | undefined> {
return new Promise((resolve, reject) => {
const loaderContext = {
_compiler: {name: compilerName},
resource: '/site/docs/doc.mdx',
resourcePath: '/site/docs/doc.mdx',
getOptions: () => options,
addDependency: () => {},
async:
() => (error: Error | null | undefined, result?: string | Buffer) =>
error ? reject(error) : resolve(result?.toString()),
} as unknown as LoaderContext<Options>;

mdxLoader.call(loaderContext, '# Title');
});
}
5 changes: 3 additions & 2 deletions packages/docusaurus-mdx-loader/src/createMDXLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import {createProcessors} from './processor';
import type {Options} from './options';
import type {CrossCompilerCache, Options} from './options';
import type {RuleSetRule, RuleSetUseItem} from 'webpack';

// Escape hatch to disable the MDX cross-compiler cache, just in case
Expand All @@ -33,9 +33,10 @@ function normalizeOptions(optionsInput: Options): Options {
// We only have multiple compilers in production mode (docusaurus build)
// TODO wrong but good enough for now (example: "docusaurus build --dev")
if (!DisableCrossCompilerCache && process.env.NODE_ENV === 'production') {
const crossCompilerCache: CrossCompilerCache = new Map();
options = {
...options,
crossCompilerCache: new Map(),
getCrossCompilerCache: () => crossCompilerCache,
};
}

Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-mdx-loader/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ async function loadMDXWithCaching({
options: Options;
compilerName: WebpackCompilerName;
}): Promise<string> {
const {crossCompilerCache} = options;
const crossCompilerCache = options.getCrossCompilerCache?.();
if (!crossCompilerCache) {
return loadMDX({
fileContent,
Expand All @@ -144,7 +144,7 @@ async function loadMDXWithCaching({
// But we could eventually use WeakRef for the values
const deleteCacheEntry = () => crossCompilerCache.delete(cacheKey);

const cacheEntry = crossCompilerCache?.get(cacheKey);
const cacheEntry = crossCompilerCache.get(cacheKey);

// When deduplicating client/server compilations, we always use the client
// compilation and not the server compilation
Expand Down
9 changes: 8 additions & 1 deletion packages/docusaurus-mdx-loader/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,14 @@ export type Options = Partial<MDXOptions> & {

// Will usually be created by "createMDXLoaderItem"
processors?: SimpleProcessors;
crossCompilerCache?: Map<string, CrossCompilerCacheEntry>; // MDX => Promise<JSX> cache
// We pass a getter function instead of the cache Map itself because some
// tools deep-clone the loader options (Rsdoctor v1 for example)
// Cloning a Map would break the cache shared by client/server compilers
// Functions are not cloned, so the getter keeps returning the shared Map
getCrossCompilerCache?: () => CrossCompilerCache;
};

// MDX => Promise<JSX> cache
export type CrossCompilerCache = Map<string, CrossCompilerCacheEntry>;

type CrossCompilerCacheEntry = PromiseWithResolvers<string>;
Loading