From 8d45009dbb5b08ecab17e3881ee06c71bc0902a7 Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 17:04:07 +0200 Subject: [PATCH 01/37] extract Markdown config types to separate file + add config.markdown.hooks.onBrokenLink --- packages/docusaurus-types/src/config.d.ts | 110 ++---------------- packages/docusaurus-types/src/markdown.d.ts | 119 ++++++++++++++++++++ 2 files changed, 131 insertions(+), 98 deletions(-) create mode 100644 packages/docusaurus-types/src/markdown.d.ts diff --git a/packages/docusaurus-types/src/config.d.ts b/packages/docusaurus-types/src/config.d.ts index 684aa3992eea..1d5f3e2402e9 100644 --- a/packages/docusaurus-types/src/config.d.ts +++ b/packages/docusaurus-types/src/config.d.ts @@ -11,10 +11,6 @@ import type {DeepPartial, Overwrite} from 'utility-types'; import type {I18nConfig} from './i18n'; import type {PluginConfig, PresetConfig, HtmlTagObject} from './plugin'; -import type {ProcessorOptions} from '@mdx-js/mdx'; - -export type RemarkRehypeOptions = ProcessorOptions['remarkRehypeOptions']; - export type ReportingSeverity = 'ignore' | 'log' | 'warn' | 'throw'; export type RouterType = 'browser' | 'hash'; @@ -23,100 +19,18 @@ export type ThemeConfig = { [key: string]: unknown; }; -export type MarkdownPreprocessor = (args: { - filePath: string; - fileContent: string; -}) => string; - -export type MDX1CompatOptions = { - comments: boolean; - admonitions: boolean; - headingIds: boolean; -}; - -export type ParseFrontMatterParams = {filePath: string; fileContent: string}; -export type ParseFrontMatterResult = { - frontMatter: {[key: string]: unknown}; - content: string; -}; -export type DefaultParseFrontMatter = ( - params: ParseFrontMatterParams, -) => Promise; -export type ParseFrontMatter = ( - params: ParseFrontMatterParams & { - defaultParseFrontMatter: DefaultParseFrontMatter; - }, -) => Promise; - -export type MarkdownAnchorsConfig = { - /** - * Preserves the case of the heading text when generating anchor ids. - */ - maintainCase: boolean; -}; - -export type MarkdownConfig = { - /** - * The Markdown format to use by default. - * - * This is the format passed down to the MDX compiler, impacting the way the - * content is parsed. - * - * Possible values: - * - `'mdx'`: use the MDX format (JSX support) - * - `'md'`: use the CommonMark format (no JSX support) - * - `'detect'`: select the format based on file extension (.md / .mdx) - * - * @see https://mdxjs.com/packages/mdx/#optionsformat - * @default 'mdx' - */ - format: 'mdx' | 'md' | 'detect'; - - /** - * A function callback that lets users parse the front matter themselves. - * Gives the opportunity to read it from a different source, or process it. - * - * @see https://github.com/facebook/docusaurus/issues/5568 - */ - parseFrontMatter: ParseFrontMatter; - - /** - * Allow mermaid language code blocks to be rendered into Mermaid diagrams: - * - * - `true`: code blocks with language mermaid will be rendered. - * - `false` | `undefined` (default): code blocks with language mermaid - * will be left as code blocks. - * - * @see https://docusaurus.io/docs/markdown-features/diagrams/ - * @default false - */ - mermaid: boolean; - - /** - * Gives opportunity to preprocess the MDX string content before compiling. - * A good escape hatch that can be used to handle edge cases. - * - * @param args - */ - preprocessor?: MarkdownPreprocessor; - - /** - * Set of flags make it easier to upgrade from MDX 1 to MDX 2 - * See also https://github.com/facebook/docusaurus/issues/4029 - */ - mdx1Compat: MDX1CompatOptions; - - /** - * Ability to provide custom remark-rehype options - * See also https://github.com/remarkjs/remark-rehype#options - */ - remarkRehypeOptions: RemarkRehypeOptions; - - /** - * Options to control the behavior of anchors generated from Markdown headings - */ - anchors: MarkdownAnchorsConfig; -}; +// We probably expose too many types here, I kept exports for v3.x retro compat +export type { + RemarkRehypeOptions, + MarkdownPreprocessor, + MDX1CompatOptions, + ParseFrontMatterParams, + ParseFrontMatterResult, + DefaultParseFrontMatter, + ParseFrontMatter, + MarkdownAnchorsConfig, + MarkdownConfig, +} from './markdown'; export type StorageConfig = { type: SiteStorage['type']; diff --git a/packages/docusaurus-types/src/markdown.d.ts b/packages/docusaurus-types/src/markdown.d.ts new file mode 100644 index 000000000000..b119d3f8e802 --- /dev/null +++ b/packages/docusaurus-types/src/markdown.d.ts @@ -0,0 +1,119 @@ +/** + * 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 type {ProcessorOptions} from '@mdx-js/mdx'; +import type {ReportingSeverity} from './config'; + +export type RemarkRehypeOptions = ProcessorOptions['remarkRehypeOptions']; + +export type MarkdownPreprocessor = (args: { + filePath: string; + fileContent: string; +}) => string; + +export type MDX1CompatOptions = { + comments: boolean; + admonitions: boolean; + headingIds: boolean; +}; + +export type ParseFrontMatterParams = {filePath: string; fileContent: string}; +export type ParseFrontMatterResult = { + frontMatter: {[key: string]: unknown}; + content: string; +}; +export type DefaultParseFrontMatter = ( + params: ParseFrontMatterParams, +) => Promise; +export type ParseFrontMatter = ( + params: ParseFrontMatterParams & { + defaultParseFrontMatter: DefaultParseFrontMatter; + }, +) => Promise; + +export type MarkdownAnchorsConfig = { + /** + * Preserves the case of the heading text when generating anchor ids. + */ + maintainCase: boolean; +}; + +// TODO refactor doc links! +export type MarkdownHooks = { + /** + * The behavior of Docusaurus when it detects any broken Markdown link. + * + * @see https://docusaurus.io/docs/api/docusaurus-config#onBrokenMarkdownLinks + * @default "warn" + */ + onBrokenLinks: ReportingSeverity; +}; + +export type MarkdownConfig = { + /** + * The Markdown format to use by default. + * + * This is the format passed down to the MDX compiler, impacting the way the + * content is parsed. + * + * Possible values: + * - `'mdx'`: use the MDX format (JSX support) + * - `'md'`: use the CommonMark format (no JSX support) + * - `'detect'`: select the format based on file extension (.md / .mdx) + * + * @see https://mdxjs.com/packages/mdx/#optionsformat + * @default 'mdx' + */ + format: 'mdx' | 'md' | 'detect'; + + /** + * A function callback that lets users parse the front matter themselves. + * Gives the opportunity to read it from a different source, or process it. + * + * @see https://github.com/facebook/docusaurus/issues/5568 + */ + parseFrontMatter: ParseFrontMatter; + + /** + * Allow mermaid language code blocks to be rendered into Mermaid diagrams: + * + * - `true`: code blocks with language mermaid will be rendered. + * - `false` | `undefined` (default): code blocks with language mermaid + * will be left as code blocks. + * + * @see https://docusaurus.io/docs/markdown-features/diagrams/ + * @default false + */ + mermaid: boolean; + + /** + * Gives opportunity to preprocess the MDX string content before compiling. + * A good escape hatch that can be used to handle edge cases. + * + * @param args + */ + preprocessor?: MarkdownPreprocessor; + + /** + * Set of flags make it easier to upgrade from MDX 1 to MDX 2 + * See also https://github.com/facebook/docusaurus/issues/4029 + */ + mdx1Compat: MDX1CompatOptions; + + /** + * Ability to provide custom remark-rehype options + * See also https://github.com/remarkjs/remark-rehype#options + */ + remarkRehypeOptions: RemarkRehypeOptions; + + /** + * Options to control the behavior of anchors generated from Markdown headings + */ + anchors: MarkdownAnchorsConfig; + + hooks: MarkdownHooks; +}; From 36a22cc1738642c28966c51045a8e802bfea7c05 Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 17:43:36 +0200 Subject: [PATCH 02/37] add onBrokenMarkdownLinks hook --- .../docusaurus-mdx-loader/src/processor.ts | 8 ++++++- .../src/remark/resolveMarkdownLinks/index.ts | 23 +++++++++++++++---- .../src/index.ts | 10 ++------ .../src/index.ts | 9 +------- packages/docusaurus-types/src/markdown.d.ts | 2 +- .../docusaurus/src/server/configValidation.ts | 11 +++++++++ 6 files changed, 40 insertions(+), 23 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/processor.ts b/packages/docusaurus-mdx-loader/src/processor.ts index 30a2143c9d80..ee11b3ee7369 100644 --- a/packages/docusaurus-mdx-loader/src/processor.ts +++ b/packages/docusaurus-mdx-loader/src/processor.ts @@ -22,6 +22,7 @@ import type {WebpackCompilerName} from '@docusaurus/utils'; import type {MDXFrontMatter} from './frontMatter'; import type {Options} from './options'; import type {AdmonitionOptions} from './remark/admonitions'; +import type {PluginOptions as ResolveMarkdownLinksOptions} from './remark/resolveMarkdownLinks'; import type {ProcessorOptions} from '@mdx-js/mdx'; // TODO as of April 2023, no way to import/re-export this ESM type easily :/ @@ -127,7 +128,12 @@ async function createProcessorFactory() { options.resolveMarkdownLink ? [ resolveMarkdownLinks, - {resolveMarkdownLink: options.resolveMarkdownLink}, + { + siteDir: options.siteDir, + resolveMarkdownLink: options.resolveMarkdownLink, + onBrokenMarkdownLinks: + options.markdownConfig.hooks.onBrokenMarkdownLinks, + } satisfies ResolveMarkdownLinksOptions, ] : undefined, [ diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts index 7903ac3b183a..6f672251b057 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts @@ -5,14 +5,16 @@ * LICENSE file in the root directory of this source tree. */ +import path from 'path'; import { parseLocalURLPath, serializeURLPath, type URLPath, } from '@docusaurus/utils'; - +import logger from '@docusaurus/logger'; import type {Plugin, Transformer} from 'unified'; import type {Definition, Link, Root} from 'mdast'; +import type {MarkdownConfig} from '@docusaurus/types'; type ResolveMarkdownLinkParams = { /** @@ -31,7 +33,9 @@ export type ResolveMarkdownLink = ( ) => string | null; export interface PluginOptions { + siteDir: string; resolveMarkdownLink: ResolveMarkdownLink; + onBrokenMarkdownLinks: MarkdownConfig['hooks']['onBrokenMarkdownLinks']; } const HAS_MARKDOWN_EXTENSION = /\.mdx?$/i; @@ -60,7 +64,7 @@ function parseMarkdownLinkURLPath(link: string): URLPath | null { const plugin: Plugin = function plugin( options, ): Transformer { - const {resolveMarkdownLink} = options; + const {resolveMarkdownLink, onBrokenMarkdownLinks, siteDir} = options; return async (root, file) => { const {visit} = await import('unist-util-visit'); @@ -71,18 +75,27 @@ const plugin: Plugin = function plugin( return; } + const sourceFilePath = file.path; + const permalink = resolveMarkdownLink({ - sourceFilePath: file.path, + sourceFilePath, linkPathname: linkURLPath.pathname, }); + if (permalink === null) { + logger.report( + onBrokenMarkdownLinks, + )`Markdown link couldn't be resolved: (url=${ + linkURLPath.pathname + }) in source file path=${path.relative(siteDir, sourceFilePath)} `; + } + if (permalink) { // This reapplies the link ?qs#hash part to the resolved pathname - const resolvedUrl = serializeURLPath({ + link.url = serializeURLPath({ ...linkURLPath, pathname: permalink, }); - link.url = resolvedUrl; } }); }; diff --git a/packages/docusaurus-plugin-content-blog/src/index.ts b/packages/docusaurus-plugin-content-blog/src/index.ts index e22f2e54f2cb..fe38ec471c3d 100644 --- a/packages/docusaurus-plugin-content-blog/src/index.ts +++ b/packages/docusaurus-plugin-content-blog/src/index.ts @@ -71,7 +71,7 @@ export default async function pluginContentBlog( ); } - const {onBrokenMarkdownLinks, baseUrl} = siteConfig; + const {baseUrl} = siteConfig; const contentPaths: BlogContentPaths = { contentPath: path.resolve(siteDir, options.path), @@ -154,18 +154,12 @@ export default async function pluginContentBlog( }, markdownConfig: siteConfig.markdown, resolveMarkdownLink: ({linkPathname, sourceFilePath}) => { - const permalink = resolveMarkdownLinkPathname(linkPathname, { + return resolveMarkdownLinkPathname(linkPathname, { sourceFilePath, sourceToPermalink: contentHelpers.sourceToPermalink, siteDir, contentPaths, }); - if (permalink === null) { - logger.report( - onBrokenMarkdownLinks, - )`Blog markdown link couldn't be resolved: (url=${linkPathname}) in source file path=${sourceFilePath}`; - } - return permalink; }, }); diff --git a/packages/docusaurus-plugin-content-docs/src/index.ts b/packages/docusaurus-plugin-content-docs/src/index.ts index a740b7f5e296..d20a88185a0b 100644 --- a/packages/docusaurus-plugin-content-docs/src/index.ts +++ b/packages/docusaurus-plugin-content-docs/src/index.ts @@ -7,7 +7,6 @@ import path from 'path'; import fs from 'fs-extra'; -import logger from '@docusaurus/logger'; import { normalizeUrl, docuHash, @@ -158,18 +157,12 @@ export default async function pluginContentDocs( sourceFilePath, versionsMetadata, ); - const permalink = resolveMarkdownLinkPathname(linkPathname, { + return resolveMarkdownLinkPathname(linkPathname, { sourceFilePath, sourceToPermalink: contentHelpers.sourceToPermalink, siteDir, contentPaths: version, }); - if (permalink === null) { - logger.report( - siteConfig.onBrokenMarkdownLinks, - )`Docs markdown link couldn't be resolved: (url=${linkPathname}) in source file path=${sourceFilePath} for version number=${version.versionName}`; - } - return permalink; }, }, }); diff --git a/packages/docusaurus-types/src/markdown.d.ts b/packages/docusaurus-types/src/markdown.d.ts index b119d3f8e802..263a7ade933a 100644 --- a/packages/docusaurus-types/src/markdown.d.ts +++ b/packages/docusaurus-types/src/markdown.d.ts @@ -50,7 +50,7 @@ export type MarkdownHooks = { * @see https://docusaurus.io/docs/api/docusaurus-config#onBrokenMarkdownLinks * @default "warn" */ - onBrokenLinks: ReportingSeverity; + onBrokenMarkdownLinks: ReportingSeverity; }; export type MarkdownConfig = { diff --git a/packages/docusaurus/src/server/configValidation.ts b/packages/docusaurus/src/server/configValidation.ts index 67fe593f2208..7ae4caf2c905 100644 --- a/packages/docusaurus/src/server/configValidation.ts +++ b/packages/docusaurus/src/server/configValidation.ts @@ -17,6 +17,7 @@ import { removeTrailingSlash, } from '@docusaurus/utils-common'; import logger from '@docusaurus/logger'; +import type {MarkdownHooks} from '@docusaurus/types/src/markdown'; import type { FasterConfig, FutureConfig, @@ -84,6 +85,10 @@ export const DEFAULT_FUTURE_CONFIG: FutureConfig = { experimental_router: 'browser', }; +export const DEFAULT_MARKDOWN_HOOKS: MarkdownHooks = { + onBrokenMarkdownLinks: 'warn', +}; + export const DEFAULT_MARKDOWN_CONFIG: MarkdownConfig = { format: 'mdx', // TODO change this to "detect" in Docusaurus v4? mermaid: false, @@ -98,6 +103,7 @@ export const DEFAULT_MARKDOWN_CONFIG: MarkdownConfig = { maintainCase: false, }, remarkRehypeOptions: undefined, + hooks: DEFAULT_MARKDOWN_HOOKS, }; export const DEFAULT_CONFIG: Pick< @@ -455,6 +461,11 @@ export const ConfigSchema = Joi.object({ DEFAULT_CONFIG.markdown.anchors.maintainCase, ), }).default(DEFAULT_CONFIG.markdown.anchors), + hooks: Joi.object({ + onBrokenMarkdownLinks: Joi.string() + .equal('ignore', 'log', 'warn', 'throw') + .default(DEFAULT_CONFIG.markdown.hooks.onBrokenMarkdownLinks), + }).default(DEFAULT_CONFIG.markdown.hooks), }).default(DEFAULT_CONFIG.markdown), }).messages({ 'docusaurus.configValidationWarning': From 6eebe373cfcb32fc6320dc8b67792bca5847f779 Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 18:11:39 +0200 Subject: [PATCH 03/37] refactor tests + test for onBrokenMarkdownLinks --- .../server/__tests__/configValidation.test.ts | 139 ++++++++++++------ 1 file changed, 91 insertions(+), 48 deletions(-) diff --git a/packages/docusaurus/src/server/__tests__/configValidation.test.ts b/packages/docusaurus/src/server/__tests__/configValidation.test.ts index 861faa8cd52e..a939ae2cd45e 100644 --- a/packages/docusaurus/src/server/__tests__/configValidation.test.ts +++ b/packages/docusaurus/src/server/__tests__/configValidation.test.ts @@ -16,6 +16,7 @@ import { DEFAULT_STORAGE_CONFIG, validateConfig, } from '../configValidation'; +import type {MarkdownConfig, MarkdownHooks} from '@docusaurus/types/src/markdown'; import type { FasterConfig, FutureConfig, @@ -36,7 +37,7 @@ const normalizeConfig = (config: DeepPartial) => describe('normalizeConfig', () => { it('normalizes empty config', () => { - const value = normalizeConfig({}); + const value = normalizeConfig({markdown: {}}); expect(value).toEqual({ ...DEFAULT_CONFIG, ...baseConfig, @@ -357,20 +358,15 @@ describe('onBrokenLinks', () => { }); describe('markdown', () => { + function normalizeMarkdown(markdown: DeepPartial) { + return normalizeConfig({markdown}).markdown; + } it('accepts undefined object', () => { - expect( - normalizeConfig({ - markdown: undefined, - }), - ).toEqual(expect.objectContaining({markdown: DEFAULT_CONFIG.markdown})); + expect(normalizeMarkdown(undefined)).toEqual(DEFAULT_CONFIG.markdown); }); it('accepts empty object', () => { - expect( - normalizeConfig({ - markdown: {}, - }), - ).toEqual(expect.objectContaining({markdown: DEFAULT_CONFIG.markdown})); + expect(normalizeMarkdown({})).toEqual(DEFAULT_CONFIG.markdown); }); it('accepts valid markdown object', () => { @@ -393,12 +389,11 @@ describe('markdown', () => { // @ts-expect-error: we don't validate it on purpose anyKey: 'heck we accept it on purpose', }, + hooks: { + onBrokenMarkdownLinks: 'log', + }, }; - expect( - normalizeConfig({ - markdown, - }), - ).toEqual(expect.objectContaining({markdown})); + expect(normalizeMarkdown(markdown)).toEqual(markdown); }); it('accepts partial markdown object', () => { @@ -408,22 +403,14 @@ describe('markdown', () => { headingIds: false, }, }; - expect( - normalizeConfig({ - markdown, - }), - ).toEqual( - expect.objectContaining({ - markdown: { - ...DEFAULT_CONFIG.markdown, - ...markdown, - mdx1Compat: { - ...DEFAULT_CONFIG.markdown.mdx1Compat, - ...markdown.mdx1Compat, - }, - }, - }), - ); + expect(normalizeMarkdown(markdown)).toEqual({ + ...DEFAULT_CONFIG.markdown, + ...markdown, + mdx1Compat: { + ...DEFAULT_CONFIG.markdown.mdx1Compat, + ...markdown.mdx1Compat, + }, + }); }); it('throw for preprocessor bad arity', () => { @@ -436,10 +423,10 @@ describe('markdown', () => { " `); expect(() => - normalizeConfig({ + normalizeMarkdown( // @ts-expect-error: types forbid this - markdown: {preprocessor: (arg1, arg2) => String(arg1) + String(arg2)}, - }), + {preprocessor: (arg1, arg2) => String(arg1) + String(arg2)}, + ), ).toThrowErrorMatchingInlineSnapshot(` ""markdown.preprocessor" must have an arity of 1 " @@ -447,18 +434,14 @@ describe('markdown', () => { }); it('accepts undefined markdown format', () => { - expect( - normalizeConfig({markdown: {format: undefined}}).markdown.format, - ).toBe('mdx'); + expect(normalizeMarkdown({format: undefined}).format).toBe('mdx'); }); it('throw for bad markdown format', () => { expect(() => - normalizeConfig({ - markdown: { - // @ts-expect-error: bad value - format: null, - }, + normalizeMarkdown({ + // @ts-expect-error: bad value + format: null, }), ).toThrowErrorMatchingInlineSnapshot(` ""markdown.format" must be one of [mdx, md, detect] @@ -466,9 +449,9 @@ describe('markdown', () => { " `); expect(() => - normalizeConfig( + normalizeMarkdown( // @ts-expect-error: bad value - {markdown: {format: 'xyz'}}, + {format: 'xyz'}, ), ).toThrowErrorMatchingInlineSnapshot(` ""markdown.format" must be one of [mdx, md, detect] @@ -478,15 +461,75 @@ describe('markdown', () => { it('throw for null object', () => { expect(() => { - normalizeConfig({ + normalizeMarkdown( // @ts-expect-error: bad value - markdown: null, - }); + null, + ); }).toThrowErrorMatchingInlineSnapshot(` ""markdown" must be of type object " `); }); + + describe('hooks', () => { + function normalizeHooks(hooks: DeepPartial): MarkdownHooks { + return normalizeMarkdown({ + hooks, + }).hooks; + } + + describe('onBrokenMarkdownLinks', () => { + function normalizeValue( + onBrokenMarkdownLinks?: MarkdownHooks['onBrokenMarkdownLinks'], + ) { + return normalizeHooks({ + onBrokenMarkdownLinks, + }).onBrokenMarkdownLinks; + } + + it('accepts undefined', () => { + expect(normalizeValue(undefined)).toBe('warn'); + }); + + it('accepts severity level', () => { + expect(normalizeValue('log')).toBe('log'); + }); + + it('rejects number', () => { + expect(() => + normalizeValue( + // @ts-expect-error: bad value + 42, + ), + ).toThrowErrorMatchingInlineSnapshot(` + ""markdown.hooks.onBrokenMarkdownLinks" must be one of [ignore, log, warn, throw] + "markdown.hooks.onBrokenMarkdownLinks" must be a string + " + `); + }); + + it('rejects function', () => { + expect(() => + normalizeValue( + // @ts-expect-error: bad value + () => {}, + ), + ).toThrowErrorMatchingInlineSnapshot(` + ""markdown.hooks.onBrokenMarkdownLinks" must be one of [ignore, log, warn, throw] + "markdown.hooks.onBrokenMarkdownLinks" must be a string + " + `); + }); + + it('rejects null', () => { + expect(() => normalizeValue(null)).toThrowErrorMatchingInlineSnapshot(` + ""markdown.hooks.onBrokenMarkdownLinks" must be one of [ignore, log, warn, throw] + "markdown.hooks.onBrokenMarkdownLinks" must be a string + " + `); + }); + }); + }); }); describe('plugins', () => { From 3a445fe9afd7e7db09800bf61e10f3261ba0373f Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 18:17:03 +0200 Subject: [PATCH 04/37] fix types --- packages/docusaurus-types/src/config.d.ts | 17 ++--------------- packages/docusaurus-types/src/index.d.ts | 12 ++++++++---- packages/docusaurus-types/src/reporting.d.ts | 8 ++++++++ 3 files changed, 18 insertions(+), 19 deletions(-) create mode 100644 packages/docusaurus-types/src/reporting.d.ts diff --git a/packages/docusaurus-types/src/config.d.ts b/packages/docusaurus-types/src/config.d.ts index 1d5f3e2402e9..05bb058787db 100644 --- a/packages/docusaurus-types/src/config.d.ts +++ b/packages/docusaurus-types/src/config.d.ts @@ -10,8 +10,8 @@ import type {RuleSetRule} from 'webpack'; import type {DeepPartial, Overwrite} from 'utility-types'; import type {I18nConfig} from './i18n'; import type {PluginConfig, PresetConfig, HtmlTagObject} from './plugin'; - -export type ReportingSeverity = 'ignore' | 'log' | 'warn' | 'throw'; +import type {ReportingSeverity} from './hooks'; +import type {MarkdownConfig} from './markdown'; export type RouterType = 'browser' | 'hash'; @@ -19,19 +19,6 @@ export type ThemeConfig = { [key: string]: unknown; }; -// We probably expose too many types here, I kept exports for v3.x retro compat -export type { - RemarkRehypeOptions, - MarkdownPreprocessor, - MDX1CompatOptions, - ParseFrontMatterParams, - ParseFrontMatterResult, - DefaultParseFrontMatter, - ParseFrontMatter, - MarkdownAnchorsConfig, - MarkdownConfig, -} from './markdown'; - export type StorageConfig = { type: SiteStorage['type']; namespace: boolean | string; diff --git a/packages/docusaurus-types/src/index.d.ts b/packages/docusaurus-types/src/index.d.ts index a6cb0b00b483..32d12992eaf6 100644 --- a/packages/docusaurus-types/src/index.d.ts +++ b/packages/docusaurus-types/src/index.d.ts @@ -6,12 +6,8 @@ */ export { - ReportingSeverity, RouterType, ThemeConfig, - MarkdownConfig, - DefaultParseFrontMatter, - ParseFrontMatter, DocusaurusConfig, FutureConfig, FasterConfig, @@ -19,6 +15,14 @@ export { Config, } from './config'; +export { + MarkdownConfig, + DefaultParseFrontMatter, + ParseFrontMatter, +} from './markdown'; + +export {ReportingSeverity} from './reporting'; + export { SiteMetadata, DocusaurusContext, diff --git a/packages/docusaurus-types/src/reporting.d.ts b/packages/docusaurus-types/src/reporting.d.ts new file mode 100644 index 000000000000..0b3ef3d42654 --- /dev/null +++ b/packages/docusaurus-types/src/reporting.d.ts @@ -0,0 +1,8 @@ +/** + * 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. + */ + +export type ReportingSeverity = 'ignore' | 'log' | 'warn' | 'throw'; From 3c863dff655cfe88558904ad6e29909a018524d4 Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 18:17:11 +0200 Subject: [PATCH 05/37] fix tests --- .../src/server/__tests__/configValidation.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/docusaurus/src/server/__tests__/configValidation.test.ts b/packages/docusaurus/src/server/__tests__/configValidation.test.ts index a939ae2cd45e..33382dbd2dca 100644 --- a/packages/docusaurus/src/server/__tests__/configValidation.test.ts +++ b/packages/docusaurus/src/server/__tests__/configValidation.test.ts @@ -16,7 +16,10 @@ import { DEFAULT_STORAGE_CONFIG, validateConfig, } from '../configValidation'; -import type {MarkdownConfig, MarkdownHooks} from '@docusaurus/types/src/markdown'; +import type { + MarkdownConfig, + MarkdownHooks, +} from '@docusaurus/types/src/markdown'; import type { FasterConfig, FutureConfig, @@ -109,6 +112,9 @@ describe('normalizeConfig', () => { remarkRehypeOptions: { footnoteLabel: 'Pied de page', }, + hooks: { + onBrokenMarkdownLinks: 'log', + }, }, }; const normalizedConfig = normalizeConfig(userConfig); From 717cca8630e2ae2ef0882337d4455edce2023338 Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 18:46:14 +0200 Subject: [PATCH 06/37] add deprecation warning for siteConfig.onBrokenMarkdownLinks + use it as a retro-compatible fallback for config.markdown.hooks.onBrokenMarkdownLinks --- packages/docusaurus-types/src/config.d.ts | 3 +- .../server/__tests__/configValidation.test.ts | 63 +++++++++++++++++++ .../docusaurus/src/server/configValidation.ts | 16 +++-- 3 files changed, 77 insertions(+), 5 deletions(-) diff --git a/packages/docusaurus-types/src/config.d.ts b/packages/docusaurus-types/src/config.d.ts index 05bb058787db..882b2907dbbb 100644 --- a/packages/docusaurus-types/src/config.d.ts +++ b/packages/docusaurus-types/src/config.d.ts @@ -159,7 +159,8 @@ export type DocusaurusConfig = { * @see https://docusaurus.io/docs/api/docusaurus-config#onBrokenMarkdownLinks * @default "warn" */ - onBrokenMarkdownLinks: ReportingSeverity; + // TODO Docusaurus v4 remove + onBrokenMarkdownLinks: ReportingSeverity | undefined; /** * The behavior of Docusaurus when it detects any [duplicate * routes](https://docusaurus.io/docs/creating-pages#duplicate-routes). diff --git a/packages/docusaurus/src/server/__tests__/configValidation.test.ts b/packages/docusaurus/src/server/__tests__/configValidation.test.ts index 33382dbd2dca..31c83c92283a 100644 --- a/packages/docusaurus/src/server/__tests__/configValidation.test.ts +++ b/packages/docusaurus/src/server/__tests__/configValidation.test.ts @@ -5,6 +5,7 @@ * LICENSE file in the root directory of this source tree. */ +import {jest} from '@jest/globals'; import { ConfigSchema, DEFAULT_CONFIG, @@ -534,6 +535,68 @@ describe('markdown', () => { " `); }); + + describe('onBrokenMarkdownLinks migration', () => { + const warnMock = jest + .spyOn(console, 'warn') + .mockImplementation(() => {}); + beforeEach(() => { + warnMock.mockClear(); + }); + + it('accepts migrated v3 config', () => { + expect( + normalizeConfig({ + onBrokenMarkdownLinks: undefined, + markdown: { + hooks: { + onBrokenMarkdownLinks: 'throw', + }, + }, + }), + ).toEqual( + expect.objectContaining({ + onBrokenMarkdownLinks: undefined, + markdown: expect.objectContaining({ + hooks: { + onBrokenMarkdownLinks: 'throw', + }, + }), + }), + ); + + expect(warnMock).not.toHaveBeenCalled(); + }); + + it('accepts deprecated v3 config with migration warning', () => { + expect( + normalizeConfig({ + onBrokenMarkdownLinks: 'log', + markdown: { + hooks: { + onBrokenMarkdownLinks: 'throw', + }, + }, + }), + ).toEqual( + expect.objectContaining({ + onBrokenMarkdownLinks: undefined, + markdown: expect.objectContaining({ + hooks: { + onBrokenMarkdownLinks: 'log', + }, + }), + }), + ); + + expect(warnMock).toHaveBeenCalledTimes(1); + expect(warnMock.mock.calls[0]).toMatchInlineSnapshot(` + [ + "[WARNING] The \`siteConfig.onBrokenMarkdownLinks\` config option is deprecated and will be removed in Docusaurus v4. Please migrate and move this option to \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` instead.", + ] + `); + }); + }); }); }); }); diff --git a/packages/docusaurus/src/server/configValidation.ts b/packages/docusaurus/src/server/configValidation.ts index 7ae4caf2c905..0bfad089c9de 100644 --- a/packages/docusaurus/src/server/configValidation.ts +++ b/packages/docusaurus/src/server/configValidation.ts @@ -134,7 +134,7 @@ export const DEFAULT_CONFIG: Pick< future: DEFAULT_FUTURE_CONFIG, onBrokenLinks: 'throw', onBrokenAnchors: 'warn', // TODO Docusaurus v4: change to throw - onBrokenMarkdownLinks: 'warn', + onBrokenMarkdownLinks: undefined, onDuplicateRoutes: 'warn', plugins: [], themes: [], @@ -356,7 +356,7 @@ export const ConfigSchema = Joi.object({ .default(DEFAULT_CONFIG.onBrokenAnchors), onBrokenMarkdownLinks: Joi.string() .equal('ignore', 'log', 'warn', 'throw') - .default(DEFAULT_CONFIG.onBrokenMarkdownLinks), + .default(() => DEFAULT_CONFIG.onBrokenMarkdownLinks), onDuplicateRoutes: Joi.string() .equal('ignore', 'log', 'warn', 'throw') .default(DEFAULT_CONFIG.onDuplicateRoutes), @@ -474,7 +474,15 @@ export const ConfigSchema = Joi.object({ // Expressing this kind of logic in Joi is a pain // We also want to decouple logic from Joi: easier to remove it later! -function ensureDocusaurusConfigConsistency(config: DocusaurusConfig) { +function postProcessDocusaurusConfig(config: DocusaurusConfig) { + if (config.onBrokenMarkdownLinks) { + logger.warn`The code=${'siteConfig.onBrokenMarkdownLinks'} config option is deprecated and will be removed in Docusaurus v4. Please migrate and move this option to code=${'siteConfig.markdown.hooks.onBrokenMarkdownLinks'} instead.`; + // For v3 retro compatibility we use the old attribute over the new one + config.markdown.hooks.onBrokenMarkdownLinks = config.onBrokenMarkdownLinks; + // We erase the former one to ensure we don't use it anywhere + config.onBrokenMarkdownLinks = undefined; + } + if ( config.future.experimental_faster.ssgWorkerThreads && !config.future.v4.removeLegacyPostBuildHeadAttribute @@ -539,7 +547,7 @@ export function validateConfig( throw new Error(formattedError); } - ensureDocusaurusConfigConsistency(value); + postProcessDocusaurusConfig(value); return value; } From 84299a17dc276c7db6ac330d4a22f515369f49cc Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 18:57:54 +0200 Subject: [PATCH 07/37] fix types --- packages/docusaurus-types/src/config.d.ts | 2 +- packages/docusaurus-types/src/markdown.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/docusaurus-types/src/config.d.ts b/packages/docusaurus-types/src/config.d.ts index 882b2907dbbb..ec1c8aee7ee5 100644 --- a/packages/docusaurus-types/src/config.d.ts +++ b/packages/docusaurus-types/src/config.d.ts @@ -10,7 +10,7 @@ import type {RuleSetRule} from 'webpack'; import type {DeepPartial, Overwrite} from 'utility-types'; import type {I18nConfig} from './i18n'; import type {PluginConfig, PresetConfig, HtmlTagObject} from './plugin'; -import type {ReportingSeverity} from './hooks'; +import type {ReportingSeverity} from './reporting'; import type {MarkdownConfig} from './markdown'; export type RouterType = 'browser' | 'hash'; diff --git a/packages/docusaurus-types/src/markdown.d.ts b/packages/docusaurus-types/src/markdown.d.ts index 263a7ade933a..81ab1a41e39f 100644 --- a/packages/docusaurus-types/src/markdown.d.ts +++ b/packages/docusaurus-types/src/markdown.d.ts @@ -6,7 +6,7 @@ */ import type {ProcessorOptions} from '@mdx-js/mdx'; -import type {ReportingSeverity} from './config'; +import type {ReportingSeverity} from './reporting'; export type RemarkRehypeOptions = ProcessorOptions['remarkRehypeOptions']; From f1171143d954a0cabe04c86ce341ad98d8b84264 Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 19:02:16 +0200 Subject: [PATCH 08/37] remove deprecated options from init templates + website --- .../templates/classic-typescript/docusaurus.config.ts | 1 - .../create-docusaurus/templates/classic/docusaurus.config.js | 1 - website/docusaurus.config.ts | 4 +++- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/create-docusaurus/templates/classic-typescript/docusaurus.config.ts b/packages/create-docusaurus/templates/classic-typescript/docusaurus.config.ts index 95cb36ccd717..1ef45060973f 100644 --- a/packages/create-docusaurus/templates/classic-typescript/docusaurus.config.ts +++ b/packages/create-docusaurus/templates/classic-typescript/docusaurus.config.ts @@ -26,7 +26,6 @@ const config: Config = { projectName: 'docusaurus', // Usually your repo name. onBrokenLinks: 'throw', - onBrokenMarkdownLinks: 'warn', // Even if you don't use internationalization, you can use this field to set // useful metadata like html lang. For example, if your site is Chinese, you diff --git a/packages/create-docusaurus/templates/classic/docusaurus.config.js b/packages/create-docusaurus/templates/classic/docusaurus.config.js index c1d553465e4c..124755d17f9e 100644 --- a/packages/create-docusaurus/templates/classic/docusaurus.config.js +++ b/packages/create-docusaurus/templates/classic/docusaurus.config.js @@ -31,7 +31,6 @@ const config = { projectName: 'docusaurus', // Usually your repo name. onBrokenLinks: 'throw', - onBrokenMarkdownLinks: 'warn', // Even if you don't use internationalization, you can use this field to set // useful metadata like html lang. For example, if your site is Chinese, you diff --git a/website/docusaurus.config.ts b/website/docusaurus.config.ts index daf01f83f43e..47eddc851a08 100644 --- a/website/docusaurus.config.ts +++ b/website/docusaurus.config.ts @@ -217,6 +217,9 @@ export default async function createConfigAsync() { markdown: { format: 'detect', mermaid: true, + hooks: { + onBrokenMarkdownLinks: 'warn', + }, mdx1Compat: { // comments: false, }, @@ -265,7 +268,6 @@ export default async function createConfigAsync() { process.env.DOCUSAURUS_CURRENT_LOCALE !== defaultLocale ? 'warn' : 'throw', - onBrokenMarkdownLinks: 'warn', favicon: 'img/docusaurus.ico', customFields: { crashTest, From 04c87e5c9213fa472fcd3880c06c8c8a6c15ce92 Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 19:03:48 +0200 Subject: [PATCH 09/37] upgade test message --- .../docusaurus/src/server/__tests__/configValidation.test.ts | 3 ++- packages/docusaurus/src/server/configValidation.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/docusaurus/src/server/__tests__/configValidation.test.ts b/packages/docusaurus/src/server/__tests__/configValidation.test.ts index 31c83c92283a..750e385e609c 100644 --- a/packages/docusaurus/src/server/__tests__/configValidation.test.ts +++ b/packages/docusaurus/src/server/__tests__/configValidation.test.ts @@ -592,7 +592,8 @@ describe('markdown', () => { expect(warnMock).toHaveBeenCalledTimes(1); expect(warnMock.mock.calls[0]).toMatchInlineSnapshot(` [ - "[WARNING] The \`siteConfig.onBrokenMarkdownLinks\` config option is deprecated and will be removed in Docusaurus v4. Please migrate and move this option to \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` instead.", + "[WARNING] The \`siteConfig.onBrokenMarkdownLinks\` config option is deprecated and will be removed in Docusaurus v4. + Please migrate and move this option to \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` instead.", ] `); }); diff --git a/packages/docusaurus/src/server/configValidation.ts b/packages/docusaurus/src/server/configValidation.ts index 0bfad089c9de..12d7ed0949e9 100644 --- a/packages/docusaurus/src/server/configValidation.ts +++ b/packages/docusaurus/src/server/configValidation.ts @@ -476,7 +476,8 @@ export const ConfigSchema = Joi.object({ // We also want to decouple logic from Joi: easier to remove it later! function postProcessDocusaurusConfig(config: DocusaurusConfig) { if (config.onBrokenMarkdownLinks) { - logger.warn`The code=${'siteConfig.onBrokenMarkdownLinks'} config option is deprecated and will be removed in Docusaurus v4. Please migrate and move this option to code=${'siteConfig.markdown.hooks.onBrokenMarkdownLinks'} instead.`; + logger.warn`The code=${'siteConfig.onBrokenMarkdownLinks'} config option is deprecated and will be removed in Docusaurus v4. +Please migrate and move this option to code=${'siteConfig.markdown.hooks.onBrokenMarkdownLinks'} instead.`; // For v3 retro compatibility we use the old attribute over the new one config.markdown.hooks.onBrokenMarkdownLinks = config.onBrokenMarkdownLinks; // We erase the former one to ensure we don't use it anywhere From b7f2062ca5221b14ad7b98b9df6eb1a50ddccd3c Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 19:06:11 +0200 Subject: [PATCH 10/37] upgrade snapshots --- .../__snapshots__/config.test.ts.snap | 40 ++++++++++++++----- .../__tests__/__snapshots__/site.test.ts.snap | 4 +- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap b/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap index bc5e43776718..e565adc3f11f 100644 --- a/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap +++ b/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap @@ -42,6 +42,9 @@ exports[`loadSiteConfig website with .cjs siteConfig 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -55,7 +58,6 @@ exports[`loadSiteConfig website with .cjs siteConfig 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], @@ -117,6 +119,9 @@ exports[`loadSiteConfig website with ts + js config 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -130,7 +135,6 @@ exports[`loadSiteConfig website with ts + js config 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], @@ -192,6 +196,9 @@ exports[`loadSiteConfig website with valid JS CJS config 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -205,7 +212,6 @@ exports[`loadSiteConfig website with valid JS CJS config 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], @@ -267,6 +273,9 @@ exports[`loadSiteConfig website with valid JS ESM config 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -280,7 +289,6 @@ exports[`loadSiteConfig website with valid JS ESM config 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], @@ -342,6 +350,9 @@ exports[`loadSiteConfig website with valid TypeScript CJS config 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -355,7 +366,6 @@ exports[`loadSiteConfig website with valid TypeScript CJS config 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], @@ -417,6 +427,9 @@ exports[`loadSiteConfig website with valid TypeScript ESM config 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -430,7 +443,6 @@ exports[`loadSiteConfig website with valid TypeScript ESM config 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], @@ -492,6 +504,9 @@ exports[`loadSiteConfig website with valid async config 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -505,7 +520,6 @@ exports[`loadSiteConfig website with valid async config 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "organizationName": "endiliey", "plugins": [], @@ -569,6 +583,9 @@ exports[`loadSiteConfig website with valid async config creator function 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -582,7 +599,6 @@ exports[`loadSiteConfig website with valid async config creator function 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "organizationName": "endiliey", "plugins": [], @@ -646,6 +662,9 @@ exports[`loadSiteConfig website with valid config creator function 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -659,7 +678,6 @@ exports[`loadSiteConfig website with valid config creator function 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "organizationName": "endiliey", "plugins": [], @@ -726,6 +744,9 @@ exports[`loadSiteConfig website with valid siteConfig 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -739,7 +760,6 @@ exports[`loadSiteConfig website with valid siteConfig 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "organizationName": "endiliey", "plugins": [ diff --git a/packages/docusaurus/src/server/__tests__/__snapshots__/site.test.ts.snap b/packages/docusaurus/src/server/__tests__/__snapshots__/site.test.ts.snap index 3a85ce8cb2c0..7e3fb1f7dd6f 100644 --- a/packages/docusaurus/src/server/__tests__/__snapshots__/site.test.ts.snap +++ b/packages/docusaurus/src/server/__tests__/__snapshots__/site.test.ts.snap @@ -126,6 +126,9 @@ exports[`load loads props for site with custom i18n path 1`] = ` "maintainCase": false, }, "format": "mdx", + "hooks": { + "onBrokenMarkdownLinks": "warn", + }, "mdx1Compat": { "admonitions": true, "comments": true, @@ -139,7 +142,6 @@ exports[`load loads props for site with custom i18n path 1`] = ` "noIndex": false, "onBrokenAnchors": "warn", "onBrokenLinks": "throw", - "onBrokenMarkdownLinks": "warn", "onDuplicateRoutes": "warn", "plugins": [], "presets": [], From fa4e79ca88b7bf773051040372587d651bcdfbce Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 19:26:45 +0200 Subject: [PATCH 11/37] Add tests for resolveMarkdownLinks --- .../__tests__/index.test.ts | 114 +++++++++++++++++- 1 file changed, 108 insertions(+), 6 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts index 00a76da679ee..663cda47e6a2 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts @@ -5,17 +5,32 @@ * LICENSE file in the root directory of this source tree. */ +import {jest} from '@jest/globals'; +import * as path from 'path'; import plugin from '..'; import type {PluginOptions} from '../index'; +import type {ReportingSeverity} from '@docusaurus/types'; + +const DefaultTestOptions: PluginOptions = { + resolveMarkdownLink: ({linkPathname}) => `/RESOLVED---${linkPathname}`, + siteDir: '/absolute/siteDir', + onBrokenMarkdownLinks: 'throw', +}; + +async function process(content: string, optionsInput?: Partial) { + const options = { + ...DefaultTestOptions, + ...optionsInput, + }; -async function process(content: string) { const {remark} = await import('remark'); - const options: PluginOptions = { - resolveMarkdownLink: ({linkPathname}) => `/RESOLVED---${linkPathname}`, - }; - - const result = await remark().use(plugin, options).process(content); + const result = await remark() + .use(plugin, options) + .process({ + value: content, + path: path.posix.join(DefaultTestOptions.siteDir, 'docs', 'myFile.mdx'), + }); return result.value; } @@ -157,4 +172,91 @@ this is a code block " `); }); + + describe('resolution errors', () => { + const warnMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); + beforeEach(() => { + warnMock.mockClear(); + }); + + async function processResolutionErrors( + content: string, + level: ReportingSeverity = 'throw', + ) { + return process(content, { + resolveMarkdownLink: () => null, + onBrokenMarkdownLinks: level, + }); + } + + it('accepts non-md link', async () => { + /* language=markdown */ + const content = `[link1](link1)`; + const result = await processResolutionErrors(content); + expect(result).toMatchInlineSnapshot(` + "[link1](link1) + " + `); + }); + + it('throws for unresolvable mdx link', async () => { + /* language=markdown */ + const content = `[link1](link1.mdx)`; + + await expect(() => + processResolutionErrors(content), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Markdown link couldn't be resolved: (link1.mdx) in source file "docs/myFile.mdx" "`, + ); + }); + + it('throws for unresolvable md link', async () => { + /* language=markdown */ + const content = `[link1](link1.md)`; + + await expect(() => + processResolutionErrors(content), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Markdown link couldn't be resolved: (link1.md) in source file "docs/myFile.mdx" "`, + ); + }); + + it('warns for unresolvable md and mdx link', async () => { + /* language=markdown */ + const content = ` +[link1](link1.mdx) + +[link2](link2) + +[link3](link3.md) + +[link 4](/link/4) + `; + + const result = await processResolutionErrors(content, 'warn'); + + expect(result).toMatchInlineSnapshot(` + "[link1](link1.mdx) + + [link2](link2) + + [link3](link3.md) + + [link 4](/link/4) + " + `); + + expect(warnMock).toHaveBeenCalledTimes(2); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "[WARNING] Markdown link couldn't be resolved: (link1.mdx) in source file "docs/myFile.mdx" ", + ], + [ + "[WARNING] Markdown link couldn't be resolved: (link3.md) in source file "docs/myFile.mdx" ", + ], + ] + `); + }); + }); }); From df0c9655d624199df26e947cfe918983bd28aa07 Mon Sep 17 00:00:00 2001 From: sebastien Date: Fri, 20 Jun 2025 19:56:46 +0200 Subject: [PATCH 12/37] Support onBrokenMarkdownLinks function form and broken url recovery --- .../__tests__/index.test.ts | 59 ++++++++++++++++--- .../src/remark/resolveMarkdownLinks/index.ts | 40 +++++++++---- packages/docusaurus-types/src/index.d.ts | 1 + packages/docusaurus-types/src/markdown.d.ts | 21 ++++++- 4 files changed, 101 insertions(+), 20 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts index 663cda47e6a2..3259318a6cd5 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts @@ -9,7 +9,6 @@ import {jest} from '@jest/globals'; import * as path from 'path'; import plugin from '..'; import type {PluginOptions} from '../index'; -import type {ReportingSeverity} from '@docusaurus/types'; const DefaultTestOptions: PluginOptions = { resolveMarkdownLink: ({linkPathname}) => `/RESOLVED---${linkPathname}`, @@ -181,11 +180,11 @@ this is a code block async function processResolutionErrors( content: string, - level: ReportingSeverity = 'throw', + onBrokenMarkdownLinks: PluginOptions['onBrokenMarkdownLinks'] = 'throw', ) { return process(content, { resolveMarkdownLink: () => null, - onBrokenMarkdownLinks: level, + onBrokenMarkdownLinks, }); } @@ -199,7 +198,7 @@ this is a code block `); }); - it('throws for unresolvable mdx link', async () => { + it('throws by default for unresolvable mdx link', async () => { /* language=markdown */ const content = `[link1](link1.mdx)`; @@ -210,7 +209,7 @@ this is a code block ); }); - it('throws for unresolvable md link', async () => { + it('throws by default for unresolvable md link', async () => { /* language=markdown */ const content = `[link1](link1.md)`; @@ -228,7 +227,7 @@ this is a code block [link2](link2) -[link3](link3.md) +[link3](dir/link3.md) [link 4](/link/4) `; @@ -240,7 +239,7 @@ this is a code block [link2](link2) - [link3](link3.md) + [link3](dir/link3.md) [link 4](/link/4) " @@ -253,7 +252,51 @@ this is a code block "[WARNING] Markdown link couldn't be resolved: (link1.mdx) in source file "docs/myFile.mdx" ", ], [ - "[WARNING] Markdown link couldn't be resolved: (link3.md) in source file "docs/myFile.mdx" ", + "[WARNING] Markdown link couldn't be resolved: (dir/link3.md) in source file "docs/myFile.mdx" ", + ], + ] + `); + }); + + it('can from recover unresolvable md and mdx link', async () => { + /* language=markdown */ + const content = ` +[link1](link1.mdx) + +[link2](link2) + +[link3](dir/link3.md?query#hash) + +[link 4](/link/4) + `; + + const result = await processResolutionErrors( + content, + ({sourceFilePath, url}) => { + console.warn(`recovering broken markdown link ${url}`); + return `/recovered/___${sourceFilePath}___/___${url}`; + }, + ); + + expect(result).toMatchInlineSnapshot(` + "[link1](/recovered/___docs/myFile.mdx___/___link1.mdx) + + [link2](link2) + + [link3](/recovered/___docs/myFile.mdx___/___dir/link3.md?query#hash) + + [link 4](/link/4) + " + `); + + expect(warnMock).toHaveBeenCalledTimes(2); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "recovering broken markdown link link1.mdx", + ], + [ + "recovering broken markdown link dir/link3.md?query#hash", ], ] `); diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts index 6f672251b057..facd1a7742e1 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts @@ -14,7 +14,10 @@ import { import logger from '@docusaurus/logger'; import type {Plugin, Transformer} from 'unified'; import type {Definition, Link, Root} from 'mdast'; -import type {MarkdownConfig} from '@docusaurus/types'; +import type { + MarkdownConfig, + OnBrokenMarkdownLinksFunction, +} from '@docusaurus/types'; type ResolveMarkdownLinkParams = { /** @@ -56,6 +59,20 @@ function parseMarkdownLinkURLPath(link: string): URLPath | null { return urlPath; } +function asFunction( + onBrokenMarkdownLinks: PluginOptions['onBrokenMarkdownLinks'], +): OnBrokenMarkdownLinksFunction { + if (typeof onBrokenMarkdownLinks === 'string') { + return ({sourceFilePath, url}) => { + logger.report( + onBrokenMarkdownLinks, + )`Markdown link couldn't be resolved: (url=${url}) in source file path=${sourceFilePath} `; + }; + } else { + return onBrokenMarkdownLinks; + } +} + /** * A remark plugin to extract the h1 heading found in Markdown files * This is exposed as "data.contentTitle" to the processed vfile @@ -64,7 +81,10 @@ function parseMarkdownLinkURLPath(link: string): URLPath | null { const plugin: Plugin = function plugin( options, ): Transformer { - const {resolveMarkdownLink, onBrokenMarkdownLinks, siteDir} = options; + const {resolveMarkdownLink, siteDir} = options; + + const onBrokenMarkdownLinks = asFunction(options.onBrokenMarkdownLinks); + return async (root, file) => { const {visit} = await import('unist-util-visit'); @@ -82,20 +102,20 @@ const plugin: Plugin = function plugin( linkPathname: linkURLPath.pathname, }); - if (permalink === null) { - logger.report( - onBrokenMarkdownLinks, - )`Markdown link couldn't be resolved: (url=${ - linkURLPath.pathname - }) in source file path=${path.relative(siteDir, sourceFilePath)} `; - } - if (permalink) { // This reapplies the link ?qs#hash part to the resolved pathname link.url = serializeURLPath({ ...linkURLPath, pathname: permalink, }); + } else { + const recoverUrl = onBrokenMarkdownLinks({ + url: link.url, + sourceFilePath: path.relative(siteDir, sourceFilePath), + }); + if (typeof recoverUrl !== 'undefined') { + link.url = recoverUrl; + } } }); }; diff --git a/packages/docusaurus-types/src/index.d.ts b/packages/docusaurus-types/src/index.d.ts index 32d12992eaf6..1be704d25a20 100644 --- a/packages/docusaurus-types/src/index.d.ts +++ b/packages/docusaurus-types/src/index.d.ts @@ -19,6 +19,7 @@ export { MarkdownConfig, DefaultParseFrontMatter, ParseFrontMatter, + OnBrokenMarkdownLinksFunction, } from './markdown'; export {ReportingSeverity} from './reporting'; diff --git a/packages/docusaurus-types/src/markdown.d.ts b/packages/docusaurus-types/src/markdown.d.ts index 81ab1a41e39f..4021b4b98053 100644 --- a/packages/docusaurus-types/src/markdown.d.ts +++ b/packages/docusaurus-types/src/markdown.d.ts @@ -42,15 +42,32 @@ export type MarkdownAnchorsConfig = { maintainCase: boolean; }; -// TODO refactor doc links! +export type OnBrokenMarkdownLinksFunction = (params: { + /** + * Path of the source file on which the broken link was found + * Relative to the site dir. + * Example: "docs/category/myDoc.mdx" + */ + sourceFilePath: string; + + /** + * The Markdown link url that couldn't be resolved. + * Technically, in this context, it's more a "relative file path", but let's + * name it url for consistency with usual Markdown names and the MDX AST + * Example: "relative/dir/myTargetDoc.mdx?query#hash" + */ + url: string; +}) => void | string; + export type MarkdownHooks = { /** * The behavior of Docusaurus when it detects any broken Markdown link. * + * // TODO refactor doc links! * @see https://docusaurus.io/docs/api/docusaurus-config#onBrokenMarkdownLinks * @default "warn" */ - onBrokenMarkdownLinks: ReportingSeverity; + onBrokenMarkdownLinks: ReportingSeverity | OnBrokenMarkdownLinksFunction; }; export type MarkdownConfig = { From abebb13116dc3b03afa84f45c1fe6eb0dec8295d Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 11:39:30 +0200 Subject: [PATCH 13/37] add onBrokenMarkdownImages config + validation --- packages/docusaurus-types/src/index.d.ts | 1 + packages/docusaurus-types/src/markdown.d.ts | 19 ++++++ .../server/__tests__/configValidation.test.ts | 62 +++++++++++++++++-- .../docusaurus/src/server/configValidation.ts | 5 +- 4 files changed, 82 insertions(+), 5 deletions(-) diff --git a/packages/docusaurus-types/src/index.d.ts b/packages/docusaurus-types/src/index.d.ts index 1be704d25a20..2c75fde3ad72 100644 --- a/packages/docusaurus-types/src/index.d.ts +++ b/packages/docusaurus-types/src/index.d.ts @@ -20,6 +20,7 @@ export { DefaultParseFrontMatter, ParseFrontMatter, OnBrokenMarkdownLinksFunction, + OnBrokenMarkdownImagesFunction, } from './markdown'; export {ReportingSeverity} from './reporting'; diff --git a/packages/docusaurus-types/src/markdown.d.ts b/packages/docusaurus-types/src/markdown.d.ts index 4021b4b98053..d2ac1d173738 100644 --- a/packages/docusaurus-types/src/markdown.d.ts +++ b/packages/docusaurus-types/src/markdown.d.ts @@ -59,6 +59,23 @@ export type OnBrokenMarkdownLinksFunction = (params: { url: string; }) => void | string; +export type OnBrokenMarkdownImagesFunction = (params: { + /** + * Path of the source file on which the broken image was found + * Relative to the site dir. + * Example: "docs/category/myDoc.mdx" + */ + sourceFilePath: string; + + /** + * The Markdown image url that couldn't be resolved. + * Technically, in this context, it's more a "relative file path", but let's + * name it url for consistency with usual Markdown names and the MDX AST + * Example: "relative/dir/myImage.png" + */ + url: string; +}) => void | string; + export type MarkdownHooks = { /** * The behavior of Docusaurus when it detects any broken Markdown link. @@ -68,6 +85,8 @@ export type MarkdownHooks = { * @default "warn" */ onBrokenMarkdownLinks: ReportingSeverity | OnBrokenMarkdownLinksFunction; + + onBrokenMarkdownImages: ReportingSeverity | OnBrokenMarkdownImagesFunction; }; export type MarkdownConfig = { diff --git a/packages/docusaurus/src/server/__tests__/configValidation.test.ts b/packages/docusaurus/src/server/__tests__/configValidation.test.ts index 750e385e609c..ec975cb9c553 100644 --- a/packages/docusaurus/src/server/__tests__/configValidation.test.ts +++ b/packages/docusaurus/src/server/__tests__/configValidation.test.ts @@ -115,6 +115,7 @@ describe('normalizeConfig', () => { }, hooks: { onBrokenMarkdownLinks: 'log', + onBrokenMarkdownImages: 'log', }, }, }; @@ -398,6 +399,7 @@ describe('markdown', () => { }, hooks: { onBrokenMarkdownLinks: 'log', + onBrokenMarkdownImages: 'warn', }, }; expect(normalizeMarkdown(markdown)).toEqual(markdown); @@ -558,9 +560,9 @@ describe('markdown', () => { expect.objectContaining({ onBrokenMarkdownLinks: undefined, markdown: expect.objectContaining({ - hooks: { + hooks: expect.objectContaining({ onBrokenMarkdownLinks: 'throw', - }, + }), }), }), ); @@ -582,9 +584,9 @@ describe('markdown', () => { expect.objectContaining({ onBrokenMarkdownLinks: undefined, markdown: expect.objectContaining({ - hooks: { + hooks: expect.objectContaining({ onBrokenMarkdownLinks: 'log', - }, + }), }), }), ); @@ -599,6 +601,58 @@ describe('markdown', () => { }); }); }); + + describe('onBrokenMarkdownImages', () => { + function normalizeValue( + onBrokenMarkdownImages?: MarkdownHooks['onBrokenMarkdownImages'], + ) { + return normalizeHooks({ + onBrokenMarkdownImages, + }).onBrokenMarkdownImages; + } + + it('accepts undefined', () => { + expect(normalizeValue(undefined)).toBe('warn'); + }); + + it('accepts severity level', () => { + expect(normalizeValue('log')).toBe('log'); + }); + + it('rejects number', () => { + expect(() => + normalizeValue( + // @ts-expect-error: bad value + 42, + ), + ).toThrowErrorMatchingInlineSnapshot(` + ""markdown.hooks.onBrokenMarkdownImages" must be one of [ignore, log, warn, throw] + "markdown.hooks.onBrokenMarkdownImages" must be a string + " + `); + }); + + it('rejects function', () => { + expect(() => + normalizeValue( + // @ts-expect-error: bad value + () => {}, + ), + ).toThrowErrorMatchingInlineSnapshot(` + ""markdown.hooks.onBrokenMarkdownImages" must be one of [ignore, log, warn, throw] + "markdown.hooks.onBrokenMarkdownImages" must be a string + " + `); + }); + + it('rejects null', () => { + expect(() => normalizeValue(null)).toThrowErrorMatchingInlineSnapshot(` + ""markdown.hooks.onBrokenMarkdownImages" must be one of [ignore, log, warn, throw] + "markdown.hooks.onBrokenMarkdownImages" must be a string + " + `); + }); + }); }); }); diff --git a/packages/docusaurus/src/server/configValidation.ts b/packages/docusaurus/src/server/configValidation.ts index 12d7ed0949e9..3bdf617701ca 100644 --- a/packages/docusaurus/src/server/configValidation.ts +++ b/packages/docusaurus/src/server/configValidation.ts @@ -17,7 +17,6 @@ import { removeTrailingSlash, } from '@docusaurus/utils-common'; import logger from '@docusaurus/logger'; -import type {MarkdownHooks} from '@docusaurus/types/src/markdown'; import type { FasterConfig, FutureConfig, @@ -87,6 +86,7 @@ export const DEFAULT_FUTURE_CONFIG: FutureConfig = { export const DEFAULT_MARKDOWN_HOOKS: MarkdownHooks = { onBrokenMarkdownLinks: 'warn', + onBrokenMarkdownImages: 'warn', }; export const DEFAULT_MARKDOWN_CONFIG: MarkdownConfig = { @@ -465,6 +465,9 @@ export const ConfigSchema = Joi.object({ onBrokenMarkdownLinks: Joi.string() .equal('ignore', 'log', 'warn', 'throw') .default(DEFAULT_CONFIG.markdown.hooks.onBrokenMarkdownLinks), + onBrokenMarkdownImages: Joi.string() + .equal('ignore', 'log', 'warn', 'throw') + .default(DEFAULT_CONFIG.markdown.hooks.onBrokenMarkdownImages), }).default(DEFAULT_CONFIG.markdown.hooks), }).default(DEFAULT_CONFIG.markdown), }).messages({ From d0fe0436053b9960f841664a1a53f1cc911c4e1c Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 11:41:25 +0200 Subject: [PATCH 14/37] refactor bad TS imports --- packages/docusaurus-types/src/index.d.ts | 2 ++ packages/docusaurus/src/server/configValidation.ts | 3 +-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/docusaurus-types/src/index.d.ts b/packages/docusaurus-types/src/index.d.ts index 2c75fde3ad72..d7e61f569d6f 100644 --- a/packages/docusaurus-types/src/index.d.ts +++ b/packages/docusaurus-types/src/index.d.ts @@ -10,6 +10,7 @@ export { ThemeConfig, DocusaurusConfig, FutureConfig, + FutureV4Config, FasterConfig, StorageConfig, Config, @@ -17,6 +18,7 @@ export { export { MarkdownConfig, + MarkdownHooks, DefaultParseFrontMatter, ParseFrontMatter, OnBrokenMarkdownLinksFunction, diff --git a/packages/docusaurus/src/server/configValidation.ts b/packages/docusaurus/src/server/configValidation.ts index 3bdf617701ca..747a32ea4c7f 100644 --- a/packages/docusaurus/src/server/configValidation.ts +++ b/packages/docusaurus/src/server/configValidation.ts @@ -22,11 +22,10 @@ import type { FutureConfig, FutureV4Config, StorageConfig, -} from '@docusaurus/types/src/config'; -import type { DocusaurusConfig, I18nConfig, MarkdownConfig, + MarkdownHooks, } from '@docusaurus/types'; const DEFAULT_I18N_LOCALE = 'en'; From 84eef7081d8b3f2d3d71e20b6dcf01bb9360fd07 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 11:46:23 +0200 Subject: [PATCH 15/37] Validation should allow function form --- .../server/__tests__/configValidation.test.ts | 44 ++++--------------- .../docusaurus/src/server/configValidation.ts | 14 ++++-- 2 files changed, 19 insertions(+), 39 deletions(-) diff --git a/packages/docusaurus/src/server/__tests__/configValidation.test.ts b/packages/docusaurus/src/server/__tests__/configValidation.test.ts index ec975cb9c553..0815a73db23c 100644 --- a/packages/docusaurus/src/server/__tests__/configValidation.test.ts +++ b/packages/docusaurus/src/server/__tests__/configValidation.test.ts @@ -449,7 +449,6 @@ describe('markdown', () => { it('throw for bad markdown format', () => { expect(() => normalizeMarkdown({ - // @ts-expect-error: bad value format: null, }), ).toThrowErrorMatchingInlineSnapshot(` @@ -470,10 +469,7 @@ describe('markdown', () => { it('throw for null object', () => { expect(() => { - normalizeMarkdown( - // @ts-expect-error: bad value - null, - ); + normalizeMarkdown(null); }).toThrowErrorMatchingInlineSnapshot(` ""markdown" must be of type object " @@ -511,29 +507,18 @@ describe('markdown', () => { 42, ), ).toThrowErrorMatchingInlineSnapshot(` - ""markdown.hooks.onBrokenMarkdownLinks" must be one of [ignore, log, warn, throw] - "markdown.hooks.onBrokenMarkdownLinks" must be a string + ""markdown.hooks.onBrokenMarkdownLinks" does not match any of the allowed types " `); }); - it('rejects function', () => { - expect(() => - normalizeValue( - // @ts-expect-error: bad value - () => {}, - ), - ).toThrowErrorMatchingInlineSnapshot(` - ""markdown.hooks.onBrokenMarkdownLinks" must be one of [ignore, log, warn, throw] - "markdown.hooks.onBrokenMarkdownLinks" must be a string - " - `); + it('accepts function', () => { + expect(normalizeValue(() => {})).toBeInstanceOf(Function); }); it('rejects null', () => { expect(() => normalizeValue(null)).toThrowErrorMatchingInlineSnapshot(` - ""markdown.hooks.onBrokenMarkdownLinks" must be one of [ignore, log, warn, throw] - "markdown.hooks.onBrokenMarkdownLinks" must be a string + ""markdown.hooks.onBrokenMarkdownLinks" does not match any of the allowed types " `); }); @@ -626,29 +611,18 @@ describe('markdown', () => { 42, ), ).toThrowErrorMatchingInlineSnapshot(` - ""markdown.hooks.onBrokenMarkdownImages" must be one of [ignore, log, warn, throw] - "markdown.hooks.onBrokenMarkdownImages" must be a string + ""markdown.hooks.onBrokenMarkdownImages" does not match any of the allowed types " `); }); - it('rejects function', () => { - expect(() => - normalizeValue( - // @ts-expect-error: bad value - () => {}, - ), - ).toThrowErrorMatchingInlineSnapshot(` - ""markdown.hooks.onBrokenMarkdownImages" must be one of [ignore, log, warn, throw] - "markdown.hooks.onBrokenMarkdownImages" must be a string - " - `); + it('accepts function', () => { + expect(normalizeValue(() => {})).toBeInstanceOf(Function); }); it('rejects null', () => { expect(() => normalizeValue(null)).toThrowErrorMatchingInlineSnapshot(` - ""markdown.hooks.onBrokenMarkdownImages" must be one of [ignore, log, warn, throw] - "markdown.hooks.onBrokenMarkdownImages" must be a string + ""markdown.hooks.onBrokenMarkdownImages" does not match any of the allowed types " `); }); diff --git a/packages/docusaurus/src/server/configValidation.ts b/packages/docusaurus/src/server/configValidation.ts index 747a32ea4c7f..94b0437e0f48 100644 --- a/packages/docusaurus/src/server/configValidation.ts +++ b/packages/docusaurus/src/server/configValidation.ts @@ -461,11 +461,17 @@ export const ConfigSchema = Joi.object({ ), }).default(DEFAULT_CONFIG.markdown.anchors), hooks: Joi.object({ - onBrokenMarkdownLinks: Joi.string() - .equal('ignore', 'log', 'warn', 'throw') + onBrokenMarkdownLinks: Joi.alternatives() + .try( + Joi.string().equal('ignore', 'log', 'warn', 'throw'), + Joi.function(), + ) .default(DEFAULT_CONFIG.markdown.hooks.onBrokenMarkdownLinks), - onBrokenMarkdownImages: Joi.string() - .equal('ignore', 'log', 'warn', 'throw') + onBrokenMarkdownImages: Joi.alternatives() + .try( + Joi.string().equal('ignore', 'log', 'warn', 'throw'), + Joi.function(), + ) .default(DEFAULT_CONFIG.markdown.hooks.onBrokenMarkdownImages), }).default(DEFAULT_CONFIG.markdown.hooks), }).default(DEFAULT_CONFIG.markdown), From d7671f0e46d95fe4d151d6b3a483b876bea829da Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 11:47:03 +0200 Subject: [PATCH 16/37] fix TS errors --- .../docusaurus/src/server/__tests__/configValidation.test.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/docusaurus/src/server/__tests__/configValidation.test.ts b/packages/docusaurus/src/server/__tests__/configValidation.test.ts index 0815a73db23c..4d72e10ebeff 100644 --- a/packages/docusaurus/src/server/__tests__/configValidation.test.ts +++ b/packages/docusaurus/src/server/__tests__/configValidation.test.ts @@ -987,7 +987,6 @@ describe('future', () => { }); it('rejects router - null', () => { - // @ts-expect-error: bad value const router: Config['future']['experimental_router'] = null; expect(() => normalizeConfig({ @@ -1196,7 +1195,6 @@ describe('future', () => { }); it('rejects namespace - null', () => { - // @ts-expect-error: bad value const storage: Partial = {namespace: null}; expect(() => normalizeConfig({ From 182f63edcc8bdfc0e50404e53712695ece62b056 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 12:24:06 +0200 Subject: [PATCH 17/37] use "throw" by default, same as current behavior --- .../docusaurus/src/server/__tests__/configValidation.test.ts | 2 +- packages/docusaurus/src/server/configValidation.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/docusaurus/src/server/__tests__/configValidation.test.ts b/packages/docusaurus/src/server/__tests__/configValidation.test.ts index 4d72e10ebeff..7a56519fe1c1 100644 --- a/packages/docusaurus/src/server/__tests__/configValidation.test.ts +++ b/packages/docusaurus/src/server/__tests__/configValidation.test.ts @@ -597,7 +597,7 @@ describe('markdown', () => { } it('accepts undefined', () => { - expect(normalizeValue(undefined)).toBe('warn'); + expect(normalizeValue(undefined)).toBe('throw'); }); it('accepts severity level', () => { diff --git a/packages/docusaurus/src/server/configValidation.ts b/packages/docusaurus/src/server/configValidation.ts index 94b0437e0f48..1731068e083b 100644 --- a/packages/docusaurus/src/server/configValidation.ts +++ b/packages/docusaurus/src/server/configValidation.ts @@ -85,7 +85,7 @@ export const DEFAULT_FUTURE_CONFIG: FutureConfig = { export const DEFAULT_MARKDOWN_HOOKS: MarkdownHooks = { onBrokenMarkdownLinks: 'warn', - onBrokenMarkdownImages: 'warn', + onBrokenMarkdownImages: 'throw', }; export const DEFAULT_MARKDOWN_CONFIG: MarkdownConfig = { From ecb4380cb1afb1ffdc8b89b8503996148fa16dba Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 12:26:30 +0200 Subject: [PATCH 18/37] wire onBrokenMarkdownImages in transformImage plugin --- packages/docusaurus-mdx-loader/src/processor.ts | 5 ++++- .../src/remark/transformImage/__tests__/index.test.ts | 9 +++++++-- .../src/remark/transformImage/index.ts | 4 +++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/processor.ts b/packages/docusaurus-mdx-loader/src/processor.ts index ee11b3ee7369..3912c6f5c5ba 100644 --- a/packages/docusaurus-mdx-loader/src/processor.ts +++ b/packages/docusaurus-mdx-loader/src/processor.ts @@ -23,6 +23,7 @@ import type {MDXFrontMatter} from './frontMatter'; import type {Options} from './options'; import type {AdmonitionOptions} from './remark/admonitions'; import type {PluginOptions as ResolveMarkdownLinksOptions} from './remark/resolveMarkdownLinks'; +import type {PluginOptions as TransformImageOptions} from './remark/transformImage'; import type {ProcessorOptions} from '@mdx-js/mdx'; // TODO as of April 2023, no way to import/re-export this ESM type easily :/ @@ -122,7 +123,9 @@ async function createProcessorFactory() { { staticDirs: options.staticDirs, siteDir: options.siteDir, - }, + onBrokenMarkdownImages: + options.markdownConfig.hooks.onBrokenMarkdownImages, + } satisfies TransformImageOptions, ], // TODO merge this with transformLinks? options.resolveMarkdownLink diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index f491fd7ac365..337d61571692 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -6,7 +6,7 @@ */ import {jest} from '@jest/globals'; -import path from 'path'; +import * as path from 'path'; import vfile from 'to-vfile'; import plugin, {type PluginOptions} from '../index'; @@ -21,7 +21,12 @@ const processFixture = async ( const result = await remark() .use(mdx) - .use(plugin, {siteDir: __dirname, staticDirs: [], ...options}) + .use(plugin, { + siteDir: __dirname, + staticDirs: [], + onBrokenMarkdownImages: 'throw', + ...options, + }) .process(file); return result.value; diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts index 8cc4af821daf..26bd13822005 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts @@ -24,10 +24,12 @@ import type {Plugin, Transformer} from 'unified'; import type {MdxJsxTextElement} from 'mdast-util-mdx'; import type {Image, Root} from 'mdast'; import type {Parent} from 'unist'; +import type {MarkdownConfig} from '@docusaurus/types'; -type PluginOptions = { +export type PluginOptions = { staticDirs: string[]; siteDir: string; + onBrokenMarkdownImages: MarkdownConfig['hooks']['onBrokenMarkdownImages']; }; type Context = PluginOptions & { From 70b4e6eaf224be76ee2779cb445ab787af071e02 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 12:27:52 +0200 Subject: [PATCH 19/37] use inline snapshots for error messages --- .../__tests__/__snapshots__/index.test.ts.snap | 6 ------ .../remark/transformImage/__tests__/index.test.ts | 14 +++++++++++--- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap index 8572403706d6..574ec0541c1e 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap @@ -5,12 +5,6 @@ exports[`transformImage plugin does not choke on invalid image 1`] = ` " `; -exports[`transformImage plugin fail if image does not exist 1`] = `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md not found."`; - -exports[`transformImage plugin fail if image relative path does not exist 1`] = `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md not found."`; - -exports[`transformImage plugin fail if image url is absent 1`] = `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md" file"`; - exports[`transformImage plugin pathname protocol 1`] = ` "![img](/img/unchecked.png) " diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index 337d61571692..5e1035be7623 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -43,17 +43,25 @@ describe('transformImage plugin', () => { it('fail if image does not exist', async () => { await expect( processFixture('fail', {staticDirs}), - ).rejects.toThrowErrorMatchingSnapshot(); + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md not found."`, + ); }); + it('fail if image relative path does not exist', async () => { await expect( processFixture('fail2', {staticDirs}), - ).rejects.toThrowErrorMatchingSnapshot(); + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md not found."`, + ); }); + it('fail if image url is absent', async () => { await expect( processFixture('noUrl', {staticDirs}), - ).rejects.toThrowErrorMatchingSnapshot(); + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md" file"`, + ); }); it('transform md images to ', async () => { From 8a087660e9b52535ed81c9bece9ed57d77d52d78 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 12:31:14 +0200 Subject: [PATCH 20/37] refactor plugin tests --- .../transformImage/__tests__/index.test.ts | 50 ++++++++++--------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index 5e1035be7623..8d0bb42534b7 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -40,30 +40,6 @@ const staticDirs = [ const siteDir = path.join(__dirname, '__fixtures__'); describe('transformImage plugin', () => { - it('fail if image does not exist', async () => { - await expect( - processFixture('fail', {staticDirs}), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md not found."`, - ); - }); - - it('fail if image relative path does not exist', async () => { - await expect( - processFixture('fail2', {staticDirs}), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md not found."`, - ); - }); - - it('fail if image url is absent', async () => { - await expect( - processFixture('noUrl', {staticDirs}), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md" file"`, - ); - }); - it('transform md images to ', async () => { const result = await processFixture('img', {staticDirs, siteDir}); expect(result).toMatchSnapshot(); @@ -80,4 +56,30 @@ describe('transformImage plugin', () => { expect(result).toMatchSnapshot(); expect(errorMock).toHaveBeenCalledTimes(1); }); + + describe('errors', () => { + it('fail if image does not exist', async () => { + await expect( + processFixture('fail', {staticDirs}), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md not found."`, + ); + }); + + it('fail if image relative path does not exist', async () => { + await expect( + processFixture('fail2', {staticDirs}), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md not found."`, + ); + }); + + it('fail if image url is absent', async () => { + await expect( + processFixture('noUrl', {staticDirs}), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md" file"`, + ); + }); + }); }); From 5a0ff72546cfb2ce4d35cc3e6ec2a00e685a0b7f Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 12:47:36 +0200 Subject: [PATCH 21/37] refactor plugin tests --- .../__tests__/__fixtures__/fail.md | 1 - .../__tests__/__fixtures__/fail2.md | 1 - .../__tests__/__fixtures__/invalid-img.md | 1 - .../__tests__/__fixtures__/noUrl.md | 1 - .../__tests__/__fixtures__/pathname.md | 1 - .../__snapshots__/index.test.ts.snap | 2 +- .../transformImage/__tests__/index.test.ts | 81 ++++++++++++------- 7 files changed, 55 insertions(+), 33 deletions(-) delete mode 100644 packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md delete mode 100644 packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md delete mode 100644 packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/invalid-img.md delete mode 100644 packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md delete mode 100644 packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/pathname.md diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md deleted file mode 100644 index d23f36ad8d6d..000000000000 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md +++ /dev/null @@ -1 +0,0 @@ -![img](/img/doesNotExist.png) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md deleted file mode 100644 index 1779d93e04e3..000000000000 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md +++ /dev/null @@ -1 +0,0 @@ -![img](./notFound.png) \ No newline at end of file diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/invalid-img.md b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/invalid-img.md deleted file mode 100644 index a41a28b708db..000000000000 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/invalid-img.md +++ /dev/null @@ -1 +0,0 @@ -![invalid image](/invalid.png) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md deleted file mode 100644 index 4763436babdb..000000000000 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md +++ /dev/null @@ -1 +0,0 @@ -![img]() diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/pathname.md b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/pathname.md deleted file mode 100644 index 73f37cbd516e..000000000000 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/pathname.md +++ /dev/null @@ -1 +0,0 @@ -![img](pathname:///img/unchecked.png) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap index 574ec0541c1e..162093487218 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap @@ -1,7 +1,7 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`transformImage plugin does not choke on invalid image 1`] = ` -"invalid image/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=/node_modules/file-loader/dist/cjs.js!./static/invalid.png").default} /> +"invalid image/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=/node_modules/file-loader/dist/cjs.js!./../static/invalid.png").default} /> " `; diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index 8d0bb42534b7..de5fef97fca8 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -10,49 +10,66 @@ import * as path from 'path'; import vfile from 'to-vfile'; import plugin, {type PluginOptions} from '../index'; -const processFixture = async ( - name: string, - options: Partial, -) => { +const siteDir = path.join(__dirname, '__fixtures__'); + +const staticDirs = [ + path.join(__dirname, '__fixtures__/static'), + path.join(__dirname, '__fixtures__/static2'), +]; + +const getProcessor = async (options?: Partial) => { const {remark} = await import('remark'); const {default: mdx} = await import('remark-mdx'); - const filePath = path.join(__dirname, `__fixtures__/${name}.md`); - const file = await vfile.read(filePath); - - const result = await remark() + return remark() .use(mdx) .use(plugin, { - siteDir: __dirname, - staticDirs: [], + siteDir, + staticDirs, onBrokenMarkdownImages: 'throw', ...options, - }) - .process(file); + }); +}; +const processFixture = async ( + name: string, + options?: Partial, +) => { + const filePath = path.join(__dirname, `__fixtures__/${name}.md`); + const file = await vfile.read(filePath); + const processor = await getProcessor(options); + const result = await processor.process(file); return result.value; }; -const staticDirs = [ - path.join(__dirname, '__fixtures__/static'), - path.join(__dirname, '__fixtures__/static2'), -]; - -const siteDir = path.join(__dirname, '__fixtures__'); +const processContent = async ( + content: string, + options?: Partial, +) => { + const processor = await getProcessor(options); + const result = await processor.process({ + value: content, + path: path.posix.join(siteDir, 'docs', 'myFile.mdx'), + }); + return result.value; +}; describe('transformImage plugin', () => { it('transform md images to ', async () => { - const result = await processFixture('img', {staticDirs, siteDir}); + // TODO split that large fixture into many smaller test cases? + const result = await processFixture('img'); expect(result).toMatchSnapshot(); }); it('pathname protocol', async () => { - const result = await processFixture('pathname', {staticDirs}); + const result = await processContent( + `![img](pathname:///img/unchecked.png)`, + ); expect(result).toMatchSnapshot(); }); it('does not choke on invalid image', async () => { const errorMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); - const result = await processFixture('invalid-img', {staticDirs}); + const result = await processContent(`![invalid image](/invalid.png)`); expect(result).toMatchSnapshot(); expect(errorMock).toHaveBeenCalledTimes(1); }); @@ -60,25 +77,35 @@ describe('transformImage plugin', () => { describe('errors', () => { it('fail if image does not exist', async () => { await expect( - processFixture('fail', {staticDirs}), + processContent(`![img](/img/doesNotExist.png)`), ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md not found."`, + `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx not found."`, ); }); it('fail if image relative path does not exist', async () => { await expect( - processFixture('fail2', {staticDirs}), + processContent(`![img](./notFound.png)`), ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md not found."`, + `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx not found."`, ); }); it('fail if image url is absent', async () => { await expect( - processFixture('noUrl', {staticDirs}), + processContent(`![img]()`), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" file"`, + ); + }); + }); + + describe('warnings', () => { + it('fail if image does not exist', async () => { + await expect( + processFixture('fail'), ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md" file"`, + `"ENOENT: no such file or directory, open '/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md'"`, ); }); }); From 1b453c10756ea85c2d2f873a5215ebf640753982 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 12:57:07 +0200 Subject: [PATCH 22/37] add basic test case --- .../transformImage/__tests__/index.test.ts | 79 ++++++++++++------- .../src/remark/transformImage/index.ts | 12 ++- 2 files changed, 59 insertions(+), 32 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index de5fef97fca8..c5b7177931e4 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -50,7 +50,7 @@ const processContent = async ( value: content, path: path.posix.join(siteDir, 'docs', 'myFile.mdx'), }); - return result.value; + return result.value.toString(); }; describe('transformImage plugin', () => { @@ -74,39 +74,58 @@ describe('transformImage plugin', () => { expect(errorMock).toHaveBeenCalledTimes(1); }); - describe('errors', () => { - it('fail if image does not exist', async () => { - await expect( - processContent(`![img](/img/doesNotExist.png)`), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx not found."`, - ); - }); + describe('onBrokenMarkdownImages', () => { + describe('throw', () => { + it('fail if image does not exist', async () => { + await expect( + processContent(`![img](/img/doesNotExist.png)`), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx not found."`, + ); + }); - it('fail if image relative path does not exist', async () => { - await expect( - processContent(`![img](./notFound.png)`), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx not found."`, - ); - }); + it('fail if image relative path does not exist', async () => { + await expect( + processContent(`![img](./notFound.png)`), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx not found."`, + ); + }); - it('fail if image url is absent', async () => { - await expect( - processContent(`![img]()`), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" file"`, - ); + it('fail if image url is absent', async () => { + await expect( + processContent(`![img]()`), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" file"`, + ); + }); }); - }); - describe('warnings', () => { - it('fail if image does not exist', async () => { - await expect( - processFixture('fail'), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"ENOENT: no such file or directory, open '/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md'"`, - ); + describe('warn', () => { + function processWarn(content: string) { + return processContent(content, {onBrokenMarkdownImages: 'warn'}); + } + + const warnMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); + beforeEach(() => { + warnMock.mockClear(); + }); + + it('warn if image does not exist', async () => { + const result = await processWarn(`![img](/img/doesNotExist.png)`); + expect(result).toMatchInlineSnapshot(` + "![img](/img/doesNotExist.png) + " + `); + expect(warnMock).toHaveBeenCalledTimes(1); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "Not found image /img/doesNotExist.png", + ], + ] + `); + }); }); }); }); diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts index 26bd13822005..0898863e7d31 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts @@ -128,7 +128,7 @@ async function ensureImageFileExist(imagePath: string, sourceFilePath: string) { async function getImageAbsolutePath( imagePath: string, - {siteDir, filePath, staticDirs}: Context, + {siteDir, filePath, staticDirs, onBrokenMarkdownImages}: Context, ) { if (imagePath.startsWith('@site/')) { const imageFilePath = path.join(siteDir, imagePath.replace('@site/', '')); @@ -142,6 +142,12 @@ async function getImageAbsolutePath( fs.pathExists, ); if (!imageFilePath) { + // TODO TEMPORARY + if (onBrokenMarkdownImages === 'warn') { + console.warn(`Not found image ${imagePath}`); + return null; + } + throw new Error( `Image ${possiblePaths .map((p) => toMessageRelativeFilePath(p)) @@ -186,7 +192,9 @@ async function processImageNode(target: Target, context: Context) { // We try to convert image urls without protocol to images with require calls // going through webpack ensures that image assets exist at build time const imagePath = await getImageAbsolutePath(decodedPathname, context); - await toImageRequireNode(target, imagePath, context); + if (imagePath !== null) { + await toImageRequireNode(target, imagePath, context); + } } const plugin: Plugin = function plugin( From da38b0afd0409b33307f3ccfb9c5f1433db1dcbb Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 15:41:43 +0200 Subject: [PATCH 23/37] add proper implementation and unit tests for onBrokenMarkdownImages --- .../transformImage/__tests__/index.test.ts | 212 ++++++++++++++++-- .../src/remark/transformImage/index.ts | 127 +++++++---- 2 files changed, 269 insertions(+), 70 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index c5b7177931e4..57cb0e961dae 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -75,33 +75,48 @@ describe('transformImage plugin', () => { }); describe('onBrokenMarkdownImages', () => { - describe('throw', () => { - it('fail if image does not exist', async () => { - await expect( - processContent(`![img](/img/doesNotExist.png)`), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx not found."`, - ); + const fixtures = { + doesNotExistAbsolute: `![img](/img/doesNotExist.png)`, + doesNotExistRelative: `![img](./doesNotExist.png)`, + doesNotExistSiteAlias: `![img](@site/doesNotExist.png)`, + urlEmpty: `![img]()`, + }; + + describe('throws', () => { + it('if image absolute path does not exist', async () => { + await expect(processContent(fixtures.doesNotExistAbsolute)).rejects + .toThrowErrorMatchingInlineSnapshot(` + "Markdown image with URL \`/img/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. + To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs." + `); + }); + + it('if image relative path does not exist', async () => { + await expect(processContent(fixtures.doesNotExistRelative)).rejects + .toThrowErrorMatchingInlineSnapshot(` + "Markdown image with URL \`./doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. + To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs." + `); }); - it('fail if image relative path does not exist', async () => { - await expect( - processContent(`![img](./notFound.png)`), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx not found."`, - ); + it('if image @site path does not exist', async () => { + await expect(processContent(fixtures.doesNotExistSiteAlias)).rejects + .toThrowErrorMatchingInlineSnapshot(` + "Markdown image with URL \`@site/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. + To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs." + `); }); - it('fail if image url is absent', async () => { - await expect( - processContent(`![img]()`), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" file"`, - ); + it('if image url empty', async () => { + await expect(processContent(fixtures.urlEmpty)).rejects + .toThrowErrorMatchingInlineSnapshot(` + "Markdown image with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx". + To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs." + `); }); }); - describe('warn', () => { + describe('warns', () => { function processWarn(content: string) { return processContent(content, {onBrokenMarkdownImages: 'warn'}); } @@ -111,8 +126,8 @@ describe('transformImage plugin', () => { warnMock.mockClear(); }); - it('warn if image does not exist', async () => { - const result = await processWarn(`![img](/img/doesNotExist.png)`); + it('if image absolute path does not exist', async () => { + const result = await processWarn(fixtures.doesNotExistAbsolute); expect(result).toMatchInlineSnapshot(` "![img](/img/doesNotExist.png) " @@ -121,7 +136,158 @@ describe('transformImage plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "Not found image /img/doesNotExist.png", + "[WARNING] Markdown image with URL \`/img/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. + To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs.", + ], + ] + `); + }); + + it('if image relative path does not exist', async () => { + const result = await processWarn(fixtures.doesNotExistRelative); + expect(result).toMatchInlineSnapshot(` + "![img](./doesNotExist.png) + " + `); + expect(warnMock).toHaveBeenCalledTimes(1); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "[WARNING] Markdown image with URL \`./doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. + To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs.", + ], + ] + `); + }); + + it('if image @site path does not exist', async () => { + const result = await processWarn(fixtures.doesNotExistSiteAlias); + expect(result).toMatchInlineSnapshot(` + "![img](@site/doesNotExist.png) + " + `); + expect(warnMock).toHaveBeenCalledTimes(1); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "[WARNING] Markdown image with URL \`@site/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. + To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs.", + ], + ] + `); + }); + + it('if image url empty', async () => { + const result = await processWarn(fixtures.urlEmpty); + expect(result).toMatchInlineSnapshot(` + "![img]() + " + `); + expect(warnMock).toHaveBeenCalledTimes(1); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "[WARNING] Markdown image with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx". + To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs.", + ], + ] + `); + }); + }); + + describe('function form', () => { + function processWarn(content: string) { + return processContent(content, { + onBrokenMarkdownImages: ({sourceFilePath, url}) => { + console.log('onBrokenMarkdownImages called for ', { + sourceFilePath, + url, + }); + return '/404.png'; + }, + }); + } + + const logMock = jest.spyOn(console, 'log').mockImplementation(() => {}); + beforeEach(() => { + logMock.mockClear(); + }); + + it('if image absolute path does not exist', async () => { + const result = await processWarn(fixtures.doesNotExistAbsolute); + expect(result).toMatchInlineSnapshot(` + "![img](/404.png) + " + `); + expect(logMock).toHaveBeenCalledTimes(1); + expect(logMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "onBrokenMarkdownImages called for ", + { + "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx", + "url": "/img/doesNotExist.png", + }, + ], + ] + `); + }); + + it('if image relative path does not exist', async () => { + const result = await processWarn(fixtures.doesNotExistRelative); + expect(result).toMatchInlineSnapshot(` + "![img](/404.png) + " + `); + expect(logMock).toHaveBeenCalledTimes(1); + expect(logMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "onBrokenMarkdownImages called for ", + { + "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx", + "url": "./doesNotExist.png", + }, + ], + ] + `); + }); + + it('if image @site path does not exist', async () => { + const result = await processWarn(fixtures.doesNotExistSiteAlias); + expect(result).toMatchInlineSnapshot(` + "![img](/404.png) + " + `); + expect(logMock).toHaveBeenCalledTimes(1); + expect(logMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "onBrokenMarkdownImages called for ", + { + "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx", + "url": "@site/doesNotExist.png", + }, + ], + ] + `); + }); + + it('if image url empty', async () => { + const result = await processWarn(fixtures.urlEmpty); + expect(result).toMatchInlineSnapshot(` + "![img](/404.png) + " + `); + expect(logMock).toHaveBeenCalledTimes(1); + expect(logMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "onBrokenMarkdownImages called for ", + { + "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx", + "url": "", + }, ], ] `); diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts index 0898863e7d31..6b56de323855 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts @@ -24,7 +24,10 @@ import type {Plugin, Transformer} from 'unified'; import type {MdxJsxTextElement} from 'mdast-util-mdx'; import type {Image, Root} from 'mdast'; import type {Parent} from 'unist'; -import type {MarkdownConfig} from '@docusaurus/types'; +import type { + MarkdownConfig, + OnBrokenMarkdownImagesFunction, +} from '@docusaurus/types'; export type PluginOptions = { staticDirs: string[]; @@ -32,11 +35,40 @@ export type PluginOptions = { onBrokenMarkdownImages: MarkdownConfig['hooks']['onBrokenMarkdownImages']; }; -type Context = PluginOptions & { +type Context = { + staticDirs: PluginOptions['staticDirs']; + siteDir: PluginOptions['siteDir']; + onBrokenMarkdownImages: OnBrokenMarkdownImagesFunction; filePath: string; inlineMarkdownImageFileLoader: string; }; +function asFunction( + onBrokenMarkdownImages: PluginOptions['onBrokenMarkdownImages'], +): OnBrokenMarkdownImagesFunction { + if (typeof onBrokenMarkdownImages === 'string') { + return ({sourceFilePath, url: imageUrl}) => { + const relativePath = toMessageRelativeFilePath(sourceFilePath); + const help = logger.interpolate`To ignore this error, use the code=${'onBrokenMarkdownImages'} site config option, or apply the code=${'pathname://'} protocol to the broken image URLs.`; + if (imageUrl) { + logger.report( + onBrokenMarkdownImages, + )`Markdown image with URL code=${imageUrl} in source file path=${relativePath} couldn't be resolved to an existing local image file.\n${help}`; + } else { + logger.report( + onBrokenMarkdownImages, + )`Markdown image with empty URL found in source file path=${relativePath}.\n${help}`; + } + }; + } else { + return (params) => + onBrokenMarkdownImages({ + ...params, + sourceFilePath: toMessageRelativeFilePath(params.sourceFilePath), + }); + } +} + type Target = [node: Image, index: number, parent: Parent]; async function toImageRequireNode( @@ -53,7 +85,7 @@ async function toImageRequireNode( ); relativeImagePath = `./${relativeImagePath}`; - const parsedUrl = parseURLOrPath(node.url, 'https://example.com'); + const parsedUrl = parseURLOrPath(node.url); const hash = parsedUrl.hash ?? ''; const search = parsedUrl.search ?? ''; const requireString = `${context.inlineMarkdownImageFileLoader}${ @@ -115,63 +147,52 @@ ${(err as Error).message}`; }); } -async function ensureImageFileExist(imagePath: string, sourceFilePath: string) { - const imageExists = await fs.pathExists(imagePath); - if (!imageExists) { - throw new Error( - `Image ${toMessageRelativeFilePath( - imagePath, - )} used in ${toMessageRelativeFilePath(sourceFilePath)} not found.`, - ); - } -} - -async function getImageAbsolutePath( - imagePath: string, - {siteDir, filePath, staticDirs, onBrokenMarkdownImages}: Context, +async function getLocalImageAbsolutePath( + originalImagePath: string, + {siteDir, filePath, staticDirs}: Context, ) { - if (imagePath.startsWith('@site/')) { - const imageFilePath = path.join(siteDir, imagePath.replace('@site/', '')); - await ensureImageFileExist(imageFilePath, filePath); + if (originalImagePath.startsWith('@site/')) { + const imageFilePath = path.join( + siteDir, + originalImagePath.replace('@site/', ''), + ); + if (!(await fs.pathExists(imageFilePath))) { + return null; + } return imageFilePath; - } else if (path.isAbsolute(imagePath)) { + } else if (path.isAbsolute(originalImagePath)) { // Absolute paths are expected to exist in the static folder. - const possiblePaths = staticDirs.map((dir) => path.join(dir, imagePath)); + const possiblePaths = staticDirs.map((dir) => + path.join(dir, originalImagePath), + ); const imageFilePath = await findAsyncSequential( possiblePaths, fs.pathExists, ); if (!imageFilePath) { - // TODO TEMPORARY - if (onBrokenMarkdownImages === 'warn') { - console.warn(`Not found image ${imagePath}`); - return null; - } - - throw new Error( - `Image ${possiblePaths - .map((p) => toMessageRelativeFilePath(p)) - .join(' or ')} used in ${toMessageRelativeFilePath( - filePath, - )} not found.`, - ); + return null; + } + return imageFilePath; + } else { + // relative paths are resolved against the source file's folder + const imageFilePath = path.join(path.dirname(filePath), originalImagePath); + if (!(await fs.pathExists(imageFilePath))) { + return null; } return imageFilePath; } - // relative paths are resolved against the source file's folder - const imageFilePath = path.join(path.dirname(filePath), imagePath); - await ensureImageFileExist(imageFilePath, filePath); - return imageFilePath; } async function processImageNode(target: Target, context: Context) { const [node] = target; + if (!node.url) { - throw new Error( - `Markdown image URL is mandatory in "${toMessageRelativeFilePath( - context.filePath, - )}" file`, - ); + node.url = + context.onBrokenMarkdownImages({ + url: node.url, + sourceFilePath: context.filePath, + }) ?? node.url; + return; } const parsedUrl = url.parse(node.url); @@ -191,15 +212,26 @@ async function processImageNode(target: Target, context: Context) { // We try to convert image urls without protocol to images with require calls // going through webpack ensures that image assets exist at build time - const imagePath = await getImageAbsolutePath(decodedPathname, context); - if (imagePath !== null) { - await toImageRequireNode(target, imagePath, context); + const localImagePath = await getLocalImageAbsolutePath( + decodedPathname, + context, + ); + if (localImagePath === null) { + node.url = + context.onBrokenMarkdownImages({ + url: node.url, + sourceFilePath: context.filePath, + }) ?? node.url; + } else { + await toImageRequireNode(target, localImagePath, context); } } const plugin: Plugin = function plugin( options, ): Transformer { + const onBrokenMarkdownImages = asFunction(options.onBrokenMarkdownImages); + return async (root, vfile) => { const {visit} = await import('unist-util-visit'); @@ -211,6 +243,7 @@ const plugin: Plugin = function plugin( filePath: vfile.path!, inlineMarkdownImageFileLoader: fileLoaderUtils.loaders.inlineMarkdownImageFileLoader, + onBrokenMarkdownImages, }; const promises: Promise[] = []; From 9ee6060f3b29d96a1c50d04ad6e223a8410c305c Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 15:46:34 +0200 Subject: [PATCH 24/37] better resolveMarkdownLinks --- .../__tests__/index.test.ts | 17 ++++++------ .../src/remark/resolveMarkdownLinks/index.ts | 26 ++++++++++--------- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts index 3259318a6cd5..f207091fc470 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts @@ -10,9 +10,10 @@ import * as path from 'path'; import plugin from '..'; import type {PluginOptions} from '../index'; +const siteDir = __dirname; + const DefaultTestOptions: PluginOptions = { resolveMarkdownLink: ({linkPathname}) => `/RESOLVED---${linkPathname}`, - siteDir: '/absolute/siteDir', onBrokenMarkdownLinks: 'throw', }; @@ -28,7 +29,7 @@ async function process(content: string, optionsInput?: Partial) { .use(plugin, options) .process({ value: content, - path: path.posix.join(DefaultTestOptions.siteDir, 'docs', 'myFile.mdx'), + path: path.posix.join(siteDir, 'docs', 'myFile.mdx'), }); return result.value; @@ -205,7 +206,7 @@ this is a code block await expect(() => processResolutionErrors(content), ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Markdown link couldn't be resolved: (link1.mdx) in source file "docs/myFile.mdx" "`, + `"Markdown link couldn't be resolved: (link1.mdx) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" "`, ); }); @@ -216,7 +217,7 @@ this is a code block await expect(() => processResolutionErrors(content), ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Markdown link couldn't be resolved: (link1.md) in source file "docs/myFile.mdx" "`, + `"Markdown link couldn't be resolved: (link1.md) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" "`, ); }); @@ -249,10 +250,10 @@ this is a code block expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown link couldn't be resolved: (link1.mdx) in source file "docs/myFile.mdx" ", + "[WARNING] Markdown link couldn't be resolved: (link1.mdx) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" ", ], [ - "[WARNING] Markdown link couldn't be resolved: (dir/link3.md) in source file "docs/myFile.mdx" ", + "[WARNING] Markdown link couldn't be resolved: (dir/link3.md) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" ", ], ] `); @@ -279,11 +280,11 @@ this is a code block ); expect(result).toMatchInlineSnapshot(` - "[link1](/recovered/___docs/myFile.mdx___/___link1.mdx) + "[link1](/recovered/___packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx___/___link1.mdx) [link2](link2) - [link3](/recovered/___docs/myFile.mdx___/___dir/link3.md?query#hash) + [link3](/recovered/___packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx___/___dir/link3.md?query#hash) [link 4](/link/4) " diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts index facd1a7742e1..4171ea2804ae 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts @@ -5,10 +5,10 @@ * LICENSE file in the root directory of this source tree. */ -import path from 'path'; import { parseLocalURLPath, serializeURLPath, + toMessageRelativeFilePath, type URLPath, } from '@docusaurus/utils'; import logger from '@docusaurus/logger'; @@ -36,7 +36,6 @@ export type ResolveMarkdownLink = ( ) => string | null; export interface PluginOptions { - siteDir: string; resolveMarkdownLink: ResolveMarkdownLink; onBrokenMarkdownLinks: MarkdownConfig['hooks']['onBrokenMarkdownLinks']; } @@ -64,12 +63,17 @@ function asFunction( ): OnBrokenMarkdownLinksFunction { if (typeof onBrokenMarkdownLinks === 'string') { return ({sourceFilePath, url}) => { + const relativePath = toMessageRelativeFilePath(sourceFilePath); logger.report( onBrokenMarkdownLinks, - )`Markdown link couldn't be resolved: (url=${url}) in source file path=${sourceFilePath} `; + )`Markdown link couldn't be resolved: (url=${url}) in source file path=${relativePath} `; }; } else { - return onBrokenMarkdownLinks; + return (params) => + onBrokenMarkdownLinks({ + ...params, + sourceFilePath: toMessageRelativeFilePath(params.sourceFilePath), + }); } } @@ -81,7 +85,7 @@ function asFunction( const plugin: Plugin = function plugin( options, ): Transformer { - const {resolveMarkdownLink, siteDir} = options; + const {resolveMarkdownLink} = options; const onBrokenMarkdownLinks = asFunction(options.onBrokenMarkdownLinks); @@ -109,13 +113,11 @@ const plugin: Plugin = function plugin( pathname: permalink, }); } else { - const recoverUrl = onBrokenMarkdownLinks({ - url: link.url, - sourceFilePath: path.relative(siteDir, sourceFilePath), - }); - if (typeof recoverUrl !== 'undefined') { - link.url = recoverUrl; - } + link.url = + onBrokenMarkdownLinks({ + url: link.url, + sourceFilePath, + }) ?? link.url; } }); }; From e3462f8fca11449c215923426c35798d90ba8892 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 15:57:40 +0200 Subject: [PATCH 25/37] improve error message --- .../transformImage/__tests__/index.test.ts | 20 ++++++++----------- .../src/remark/transformImage/index.ts | 9 ++++++--- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index 57cb0e961dae..a221b0bff764 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -87,7 +87,7 @@ describe('transformImage plugin', () => { await expect(processContent(fixtures.doesNotExistAbsolute)).rejects .toThrowErrorMatchingInlineSnapshot(` "Markdown image with URL \`/img/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. - To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs." + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownImages\` option, or apply the \`pathname://\` protocol to the broken image URLs." `); }); @@ -95,7 +95,7 @@ describe('transformImage plugin', () => { await expect(processContent(fixtures.doesNotExistRelative)).rejects .toThrowErrorMatchingInlineSnapshot(` "Markdown image with URL \`./doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. - To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs." + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownImages\` option, or apply the \`pathname://\` protocol to the broken image URLs." `); }); @@ -103,7 +103,7 @@ describe('transformImage plugin', () => { await expect(processContent(fixtures.doesNotExistSiteAlias)).rejects .toThrowErrorMatchingInlineSnapshot(` "Markdown image with URL \`@site/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. - To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs." + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownImages\` option, or apply the \`pathname://\` protocol to the broken image URLs." `); }); @@ -111,7 +111,7 @@ describe('transformImage plugin', () => { await expect(processContent(fixtures.urlEmpty)).rejects .toThrowErrorMatchingInlineSnapshot(` "Markdown image with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx". - To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs." + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownImages\` option, or apply the \`pathname://\` protocol to the broken image URLs." `); }); }); @@ -136,8 +136,7 @@ describe('transformImage plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown image with URL \`/img/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. - To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs.", + "[WARNING] Markdown image with URL \`/img/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file.", ], ] `); @@ -153,8 +152,7 @@ describe('transformImage plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown image with URL \`./doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. - To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs.", + "[WARNING] Markdown image with URL \`./doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file.", ], ] `); @@ -170,8 +168,7 @@ describe('transformImage plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown image with URL \`@site/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. - To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs.", + "[WARNING] Markdown image with URL \`@site/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file.", ], ] `); @@ -187,8 +184,7 @@ describe('transformImage plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown image with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx". - To ignore this error, use the \`onBrokenMarkdownImages\` site config option, or apply the \`pathname://\` protocol to the broken image URLs.", + "[WARNING] Markdown image with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx".", ], ] `); diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts index 6b56de323855..fb940bd66cd8 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts @@ -47,17 +47,20 @@ function asFunction( onBrokenMarkdownImages: PluginOptions['onBrokenMarkdownImages'], ): OnBrokenMarkdownImagesFunction { if (typeof onBrokenMarkdownImages === 'string') { + const extraHelp = + onBrokenMarkdownImages === 'throw' + ? logger.interpolate`\nTo ignore this error, use the code=${'siteConfig.markdown.hooks.onBrokenMarkdownImages'} option, or apply the code=${'pathname://'} protocol to the broken image URLs.` + : ''; return ({sourceFilePath, url: imageUrl}) => { const relativePath = toMessageRelativeFilePath(sourceFilePath); - const help = logger.interpolate`To ignore this error, use the code=${'onBrokenMarkdownImages'} site config option, or apply the code=${'pathname://'} protocol to the broken image URLs.`; if (imageUrl) { logger.report( onBrokenMarkdownImages, - )`Markdown image with URL code=${imageUrl} in source file path=${relativePath} couldn't be resolved to an existing local image file.\n${help}`; + )`Markdown image with URL code=${imageUrl} in source file path=${relativePath} couldn't be resolved to an existing local image file.${extraHelp}`; } else { logger.report( onBrokenMarkdownImages, - )`Markdown image with empty URL found in source file path=${relativePath}.\n${help}`; + )`Markdown image with empty URL found in source file path=${relativePath}.${extraHelp}`; } }; } else { From 3e61fab13e5db8e26137e3047268525f3525f56e Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 16:14:46 +0200 Subject: [PATCH 26/37] improve onBrokenMarkdownLinks error message --- .../__tests__/index.test.ts | 24 +++++++++---------- .../src/remark/resolveMarkdownLinks/index.ts | 8 ++++++- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts index f207091fc470..e8477da04fda 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts @@ -203,22 +203,22 @@ this is a code block /* language=markdown */ const content = `[link1](link1.mdx)`; - await expect(() => - processResolutionErrors(content), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Markdown link couldn't be resolved: (link1.mdx) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" "`, - ); + await expect(() => processResolutionErrors(content)).rejects + .toThrowErrorMatchingInlineSnapshot(` + "Markdown link couldn't be resolved: (link1.mdx) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx". + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." + `); }); it('throws by default for unresolvable md link', async () => { /* language=markdown */ const content = `[link1](link1.md)`; - await expect(() => - processResolutionErrors(content), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Markdown link couldn't be resolved: (link1.md) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" "`, - ); + await expect(() => processResolutionErrors(content)).rejects + .toThrowErrorMatchingInlineSnapshot(` + "Markdown link couldn't be resolved: (link1.md) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx". + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." + `); }); it('warns for unresolvable md and mdx link', async () => { @@ -250,10 +250,10 @@ this is a code block expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown link couldn't be resolved: (link1.mdx) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" ", + "[WARNING] Markdown link couldn't be resolved: (link1.mdx) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx".", ], [ - "[WARNING] Markdown link couldn't be resolved: (dir/link3.md) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" ", + "[WARNING] Markdown link couldn't be resolved: (dir/link3.md) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx".", ], ] `); diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts index 4171ea2804ae..05f859aa7200 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts @@ -62,11 +62,15 @@ function asFunction( onBrokenMarkdownLinks: PluginOptions['onBrokenMarkdownLinks'], ): OnBrokenMarkdownLinksFunction { if (typeof onBrokenMarkdownLinks === 'string') { + const extraHelp = + onBrokenMarkdownLinks === 'throw' + ? logger.interpolate`\nTo ignore this error, use the code=${'siteConfig.markdown.hooks.onBrokenMarkdownLinks'} option, or apply the code=${'pathname://'} protocol to the broken link URLs.` + : ''; return ({sourceFilePath, url}) => { const relativePath = toMessageRelativeFilePath(sourceFilePath); logger.report( onBrokenMarkdownLinks, - )`Markdown link couldn't be resolved: (url=${url}) in source file path=${relativePath} `; + )`Markdown link couldn't be resolved: (url=${url}) in source file path=${relativePath}.${extraHelp}`; }; } else { return (params) => @@ -82,6 +86,8 @@ function asFunction( * This is exposed as "data.contentTitle" to the processed vfile * Also gives the ability to strip that content title (used for the blog plugin) */ +// TODO merge this plugin with "transformLinks" +// in general we'd want to avoid traversing multiple times the same AST const plugin: Plugin = function plugin( options, ): Transformer { From e7bfd55427d436ad15043f776efdb896337888a5 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 16:27:22 +0200 Subject: [PATCH 27/37] refactor transformLinks tests --- .../src/remark/resolveMarkdownLinks/index.ts | 31 +------ .../__tests__/__fixtures__/noUrl.md | 1 - .../__fixtures__/nonexistentSiteAlias.md | 1 - .../__tests__/__fixtures__/pathname.md | 1 - .../__snapshots__/index.test.ts.snap | 12 +-- .../transformLinks/__tests__/index.test.ts | 92 +++++++++++++------ .../src/remark/transformLinks/index.ts | 29 ++++++ 7 files changed, 96 insertions(+), 71 deletions(-) delete mode 100644 packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/noUrl.md delete mode 100644 packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/nonexistentSiteAlias.md delete mode 100644 packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/pathname.md diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts index 05f859aa7200..81227f2fd208 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts @@ -8,16 +8,12 @@ import { parseLocalURLPath, serializeURLPath, - toMessageRelativeFilePath, type URLPath, } from '@docusaurus/utils'; -import logger from '@docusaurus/logger'; +import {asFunction} from '../transformLinks'; import type {Plugin, Transformer} from 'unified'; import type {Definition, Link, Root} from 'mdast'; -import type { - MarkdownConfig, - OnBrokenMarkdownLinksFunction, -} from '@docusaurus/types'; +import type {MarkdownConfig} from '@docusaurus/types'; type ResolveMarkdownLinkParams = { /** @@ -58,29 +54,6 @@ function parseMarkdownLinkURLPath(link: string): URLPath | null { return urlPath; } -function asFunction( - onBrokenMarkdownLinks: PluginOptions['onBrokenMarkdownLinks'], -): OnBrokenMarkdownLinksFunction { - if (typeof onBrokenMarkdownLinks === 'string') { - const extraHelp = - onBrokenMarkdownLinks === 'throw' - ? logger.interpolate`\nTo ignore this error, use the code=${'siteConfig.markdown.hooks.onBrokenMarkdownLinks'} option, or apply the code=${'pathname://'} protocol to the broken link URLs.` - : ''; - return ({sourceFilePath, url}) => { - const relativePath = toMessageRelativeFilePath(sourceFilePath); - logger.report( - onBrokenMarkdownLinks, - )`Markdown link couldn't be resolved: (url=${url}) in source file path=${relativePath}.${extraHelp}`; - }; - } else { - return (params) => - onBrokenMarkdownLinks({ - ...params, - sourceFilePath: toMessageRelativeFilePath(params.sourceFilePath), - }); - } -} - /** * A remark plugin to extract the h1 heading found in Markdown files * This is exposed as "data.contentTitle" to the processed vfile diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/noUrl.md b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/noUrl.md deleted file mode 100644 index a35d39ef4547..000000000000 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/noUrl.md +++ /dev/null @@ -1 +0,0 @@ -[asset]() diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/nonexistentSiteAlias.md b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/nonexistentSiteAlias.md deleted file mode 100644 index 34247e144066..000000000000 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/nonexistentSiteAlias.md +++ /dev/null @@ -1 +0,0 @@ -[nonexistent](@site/foo.pdf) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/pathname.md b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/pathname.md deleted file mode 100644 index 6e20bcf3d384..000000000000 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/pathname.md +++ /dev/null @@ -1 +0,0 @@ -[asset](pathname:///asset/unchecked.pdf) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap index a0186db7b10b..f7fd51dce57d 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap @@ -1,14 +1,5 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`transformAsset plugin fail if asset url is absent 1`] = `"Markdown link URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/noUrl.md" file (title: asset, line: 1)."`; - -exports[`transformAsset plugin fail if asset with site alias does not exist 1`] = `"Asset packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/foo.pdf used in packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/nonexistentSiteAlias.md not found."`; - -exports[`transformAsset plugin pathname protocol 1`] = ` -"[asset](pathname:///asset/unchecked.pdf) -" -`; - exports[`transformAsset plugin transform md links to 1`] = ` "[asset](https://example.com/asset.pdf) @@ -54,6 +45,5 @@ in paragraph /node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./data.json").default}>JSON -/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/static-json.json").default}>static JSON -" +/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/static-json.json").default}>static JSON" `; diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts index 346c46e599e8..df737c965484 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts @@ -5,53 +5,89 @@ * LICENSE file in the root directory of this source tree. */ -import path from 'path'; +import * as path from 'path'; import vfile from 'to-vfile'; import plugin from '..'; import transformImage, {type PluginOptions} from '../../transformImage'; -const processFixture = async (name: string, options?: PluginOptions) => { +const siteDir = path.join(__dirname, `__fixtures__`); + +const staticDirs = [ + path.join(siteDir, 'static'), + path.join(siteDir, 'static2'), +]; + +const getProcessor = async (options?: Partial) => { const {remark} = await import('remark'); const {default: mdx} = await import('remark-mdx'); - const siteDir = path.join(__dirname, `__fixtures__`); - const staticDirs = [ - path.join(siteDir, 'static'), - path.join(siteDir, 'static2'), - ]; - const file = await vfile.read(path.join(siteDir, `${name}.md`)); - const result = await remark() + return remark() .use(mdx) - .use(transformImage, {...options, siteDir, staticDirs}) - .use(plugin, { - ...options, + .use(transformImage, { + siteDir, staticDirs, - siteDir: path.join(__dirname, '__fixtures__'), + onBrokenMarkdownImages: 'throw', }) - .process(file); - - return result.value; + .use(plugin, { + staticDirs, + siteDir, + onBrokenMarkdownLinks: 'throw', + ...options, + }); }; -describe('transformAsset plugin', () => { - it('fail if asset url is absent', async () => { - await expect( - processFixture('noUrl'), - ).rejects.toThrowErrorMatchingSnapshot(); - }); +const processFixture = async ( + name: string, + options?: Partial, +) => { + const processor = await getProcessor(options); + const file = await vfile.read(path.join(siteDir, `${name}.md`)); + const result = await processor.process(file); + return result.value.toString().trim(); +}; - it('fail if asset with site alias does not exist', async () => { - await expect( - processFixture('nonexistentSiteAlias'), - ).rejects.toThrowErrorMatchingSnapshot(); +const processContent = async ( + content: string, + options?: Partial, +) => { + const processor = await getProcessor(options); + const result = await processor.process({ + value: content, + path: path.posix.join(siteDir, 'docs', 'myFile.mdx'), }); + return result.value.toString().trim(); +}; +describe('transformAsset plugin', () => { it('transform md links to ', async () => { + // TODO split fixture in many smaller test cases const result = await processFixture('asset'); expect(result).toMatchSnapshot(); }); it('pathname protocol', async () => { - const result = await processFixture('pathname'); - expect(result).toMatchSnapshot(); + const result = await processContent( + `[asset](pathname:///asset/unchecked.pdf)`, + ); + expect(result).toMatchInlineSnapshot( + `"[asset](pathname:///asset/unchecked.pdf)"`, + ); + }); + + describe('throws', () => { + it('fail if asset url is absent', async () => { + await expect( + processContent(`[asset]()`), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Markdown link URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" file (title: asset, line: 1)."`, + ); + }); + + it('fail if asset with site alias does not exist', async () => { + await expect( + processContent(`[nonexistent](@site/foo.pdf)`), + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Asset packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/foo.pdf used in packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx not found."`, + ); + }); }); }); diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts index 625d83843397..1271b405872b 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts @@ -17,15 +17,21 @@ import { parseURLOrPath, } from '@docusaurus/utils'; import escapeHtml from 'escape-html'; +import logger from '@docusaurus/logger'; import {assetRequireAttributeValue, transformNode} from '../utils'; import type {Plugin, Transformer} from 'unified'; import type {MdxJsxTextElement} from 'mdast-util-mdx'; import type {Parent} from 'unist'; import type {Link, Literal, Root} from 'mdast'; +import type { + MarkdownConfig, + OnBrokenMarkdownLinksFunction, +} from '@docusaurus/types'; type PluginOptions = { staticDirs: string[]; siteDir: string; + onBrokenMarkdownLinks: MarkdownConfig['hooks']['onBrokenMarkdownLinks']; }; type Context = PluginOptions & { @@ -35,6 +41,29 @@ type Context = PluginOptions & { type Target = [node: Link, index: number, parent: Parent]; +export function asFunction( + onBrokenMarkdownLinks: PluginOptions['onBrokenMarkdownLinks'], +): OnBrokenMarkdownLinksFunction { + if (typeof onBrokenMarkdownLinks === 'string') { + const extraHelp = + onBrokenMarkdownLinks === 'throw' + ? logger.interpolate`\nTo ignore this error, use the code=${'siteConfig.markdown.hooks.onBrokenMarkdownLinks'} option, or apply the code=${'pathname://'} protocol to the broken link URLs.` + : ''; + return ({sourceFilePath, url: linkUrl}) => { + const relativePath = toMessageRelativeFilePath(sourceFilePath); + logger.report( + onBrokenMarkdownLinks, + )`Markdown link couldn't be resolved: (url=${linkUrl}) in source file path=${relativePath}.${extraHelp}`; + }; + } else { + return (params) => + onBrokenMarkdownLinks({ + ...params, + sourceFilePath: toMessageRelativeFilePath(params.sourceFilePath), + }); + } +} + /** * Transforms the link node to a JSX `` element with a `require()` call. */ From fff0d961deecc06795b462cf470d2394745d8dfe Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 16:31:52 +0200 Subject: [PATCH 28/37] improve resolveMarkdownLink error --- .../__tests__/index.test.ts | 12 ++++--- .../src/remark/resolveMarkdownLinks/index.ts | 32 +++++++++++++++++-- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts index e8477da04fda..72420596b35a 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts @@ -205,7 +205,8 @@ this is a code block await expect(() => processResolutionErrors(content)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown link couldn't be resolved: (link1.mdx) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx". + "Markdown link with URL $\`link1.mdx\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." `); }); @@ -216,7 +217,8 @@ this is a code block await expect(() => processResolutionErrors(content)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown link couldn't be resolved: (link1.md) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx". + "Markdown link with URL $\`link1.md\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." `); }); @@ -250,10 +252,12 @@ this is a code block expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown link couldn't be resolved: (link1.mdx) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx".", + "[WARNING] Markdown link with URL $\`link1.mdx\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin.", ], [ - "[WARNING] Markdown link couldn't be resolved: (dir/link3.md) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx".", + "[WARNING] Markdown link with URL $\`dir/link3.md\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin.", ], ] `); diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts index 81227f2fd208..828737c6fc22 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts @@ -8,12 +8,16 @@ import { parseLocalURLPath, serializeURLPath, + toMessageRelativeFilePath, type URLPath, } from '@docusaurus/utils'; -import {asFunction} from '../transformLinks'; +import logger from '@docusaurus/logger'; import type {Plugin, Transformer} from 'unified'; import type {Definition, Link, Root} from 'mdast'; -import type {MarkdownConfig} from '@docusaurus/types'; +import type { + MarkdownConfig, + OnBrokenMarkdownLinksFunction, +} from '@docusaurus/types'; type ResolveMarkdownLinkParams = { /** @@ -36,6 +40,30 @@ export interface PluginOptions { onBrokenMarkdownLinks: MarkdownConfig['hooks']['onBrokenMarkdownLinks']; } +function asFunction( + onBrokenMarkdownLinks: PluginOptions['onBrokenMarkdownLinks'], +): OnBrokenMarkdownLinksFunction { + if (typeof onBrokenMarkdownLinks === 'string') { + const extraHelp = + onBrokenMarkdownLinks === 'throw' + ? logger.interpolate`\nTo ignore this error, use the code=${'siteConfig.markdown.hooks.onBrokenMarkdownLinks'} option, or apply the code=${'pathname://'} protocol to the broken link URLs.` + : ''; + return ({sourceFilePath, url: linkUrl}) => { + const relativePath = toMessageRelativeFilePath(sourceFilePath); + logger.report( + onBrokenMarkdownLinks, + )`Markdown link with URL $code=${linkUrl}) in source file path=${relativePath} couldn't be resolved. +Make sure it references a local Markdown file that exists within the current plugin.${extraHelp}`; + }; + } else { + return (params) => + onBrokenMarkdownLinks({ + ...params, + sourceFilePath: toMessageRelativeFilePath(params.sourceFilePath), + }); + } +} + const HAS_MARKDOWN_EXTENSION = /\.mdx?$/i; function parseMarkdownLinkURLPath(link: string): URLPath | null { From adccdddc03ca4a5cfef0edb0dad1c8af9a53b259 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 16:36:52 +0200 Subject: [PATCH 29/37] improve resolveMarkdownLink tests --- .../__tests__/index.test.ts | 90 ++++++++++--------- 1 file changed, 47 insertions(+), 43 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts index 72420596b35a..3520eb550dd0 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts @@ -36,6 +36,16 @@ async function process(content: string, optionsInput?: Partial) { } describe('resolveMarkdownLinks remark plugin', () => { + it('accepts non-md link', async () => { + /* language=markdown */ + const content = `[link1](link1)`; + const result = await process(content); + expect(result).toMatchInlineSnapshot(` + "[link1](link1) + " + `); + }); + it('resolves Markdown and MDX links', async () => { /* language=markdown */ const content = `[link1](link1.mdx) @@ -173,7 +183,7 @@ this is a code block `); }); - describe('resolution errors', () => { + describe('onBrokenMarkdownLinks', () => { const warnMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); beforeEach(() => { warnMock.mockClear(); @@ -189,43 +199,36 @@ this is a code block }); } - it('accepts non-md link', async () => { - /* language=markdown */ - const content = `[link1](link1)`; - const result = await processResolutionErrors(content); - expect(result).toMatchInlineSnapshot(` - "[link1](link1) - " - `); - }); - - it('throws by default for unresolvable mdx link', async () => { - /* language=markdown */ - const content = `[link1](link1.mdx)`; + describe('throws', () => { + it('for unresolvable mdx link', async () => { + /* language=markdown */ + const content = `[link1](link1.mdx)`; - await expect(() => processResolutionErrors(content)).rejects - .toThrowErrorMatchingInlineSnapshot(` + await expect(() => processResolutionErrors(content)).rejects + .toThrowErrorMatchingInlineSnapshot(` "Markdown link with URL $\`link1.mdx\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." `); - }); + }); - it('throws by default for unresolvable md link', async () => { - /* language=markdown */ - const content = `[link1](link1.md)`; + it('for unresolvable md link', async () => { + /* language=markdown */ + const content = `[link1](link1.md)`; - await expect(() => processResolutionErrors(content)).rejects - .toThrowErrorMatchingInlineSnapshot(` + await expect(() => processResolutionErrors(content)).rejects + .toThrowErrorMatchingInlineSnapshot(` "Markdown link with URL $\`link1.md\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." `); + }); }); - it('warns for unresolvable md and mdx link', async () => { - /* language=markdown */ - const content = ` + describe('warns', () => { + it('for unresolvable md and mdx link', async () => { + /* language=markdown */ + const content = ` [link1](link1.mdx) [link2](link2) @@ -235,9 +238,9 @@ this is a code block [link 4](/link/4) `; - const result = await processResolutionErrors(content, 'warn'); + const result = await processResolutionErrors(content, 'warn'); - expect(result).toMatchInlineSnapshot(` + expect(result).toMatchInlineSnapshot(` "[link1](link1.mdx) [link2](link2) @@ -248,8 +251,8 @@ this is a code block " `); - expect(warnMock).toHaveBeenCalledTimes(2); - expect(warnMock.mock.calls).toMatchInlineSnapshot(` + expect(warnMock).toHaveBeenCalledTimes(2); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ "[WARNING] Markdown link with URL $\`link1.mdx\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. @@ -261,11 +264,11 @@ this is a code block ], ] `); - }); + }); - it('can from recover unresolvable md and mdx link', async () => { - /* language=markdown */ - const content = ` + it('for unresolvable md and mdx link - with recovery', async () => { + /* language=markdown */ + const content = ` [link1](link1.mdx) [link2](link2) @@ -275,15 +278,15 @@ this is a code block [link 4](/link/4) `; - const result = await processResolutionErrors( - content, - ({sourceFilePath, url}) => { - console.warn(`recovering broken markdown link ${url}`); - return `/recovered/___${sourceFilePath}___/___${url}`; - }, - ); + const result = await processResolutionErrors( + content, + ({sourceFilePath, url}) => { + console.warn(`recovering broken markdown link ${url}`); + return `/recovered/___${sourceFilePath}___/___${url}`; + }, + ); - expect(result).toMatchInlineSnapshot(` + expect(result).toMatchInlineSnapshot(` "[link1](/recovered/___packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx___/___link1.mdx) [link2](link2) @@ -294,8 +297,8 @@ this is a code block " `); - expect(warnMock).toHaveBeenCalledTimes(2); - expect(warnMock.mock.calls).toMatchInlineSnapshot(` + expect(warnMock).toHaveBeenCalledTimes(2); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ "recovering broken markdown link link1.mdx", @@ -305,6 +308,7 @@ this is a code block ], ] `); + }); }); }); }); From 52dff042620bf34d14e53c039796368bf71fa135 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 16:58:00 +0200 Subject: [PATCH 30/37] error message typo --- .../__tests__/index.test.ts | 78 +++++++++---------- .../src/remark/resolveMarkdownLinks/index.ts | 2 +- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts index 3520eb550dd0..41e5b174845a 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts @@ -206,10 +206,10 @@ this is a code block await expect(() => processResolutionErrors(content)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown link with URL $\`link1.mdx\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. - Make sure it references a local Markdown file that exists within the current plugin. - To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." - `); + "Markdown link with URL \`link1.mdx\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin. + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." + `); }); it('for unresolvable md link', async () => { @@ -218,10 +218,10 @@ this is a code block await expect(() => processResolutionErrors(content)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown link with URL $\`link1.md\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. - Make sure it references a local Markdown file that exists within the current plugin. - To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." - `); + "Markdown link with URL \`link1.md\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin. + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." + `); }); }); @@ -241,29 +241,29 @@ this is a code block const result = await processResolutionErrors(content, 'warn'); expect(result).toMatchInlineSnapshot(` - "[link1](link1.mdx) + "[link1](link1.mdx) - [link2](link2) + [link2](link2) - [link3](dir/link3.md) + [link3](dir/link3.md) - [link 4](/link/4) - " - `); + [link 4](/link/4) + " + `); expect(warnMock).toHaveBeenCalledTimes(2); expect(warnMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "[WARNING] Markdown link with URL $\`link1.mdx\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. - Make sure it references a local Markdown file that exists within the current plugin.", - ], [ - "[WARNING] Markdown link with URL $\`dir/link3.md\`) in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. - Make sure it references a local Markdown file that exists within the current plugin.", - ], - ] - `); + [ + "[WARNING] Markdown link with URL \`link1.mdx\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin.", + ], + [ + "[WARNING] Markdown link with URL \`dir/link3.md\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin.", + ], + ] + `); }); it('for unresolvable md and mdx link - with recovery', async () => { @@ -287,27 +287,27 @@ this is a code block ); expect(result).toMatchInlineSnapshot(` - "[link1](/recovered/___packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx___/___link1.mdx) + "[link1](/recovered/___packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx___/___link1.mdx) - [link2](link2) + [link2](link2) - [link3](/recovered/___packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx___/___dir/link3.md?query#hash) + [link3](/recovered/___packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx___/___dir/link3.md?query#hash) - [link 4](/link/4) - " - `); + [link 4](/link/4) + " + `); expect(warnMock).toHaveBeenCalledTimes(2); expect(warnMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "recovering broken markdown link link1.mdx", - ], - [ - "recovering broken markdown link dir/link3.md?query#hash", - ], - ] - `); + [ + [ + "recovering broken markdown link link1.mdx", + ], + [ + "recovering broken markdown link dir/link3.md?query#hash", + ], + ] + `); }); }); }); diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts index 828737c6fc22..e33f1e109919 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts @@ -52,7 +52,7 @@ function asFunction( const relativePath = toMessageRelativeFilePath(sourceFilePath); logger.report( onBrokenMarkdownLinks, - )`Markdown link with URL $code=${linkUrl}) in source file path=${relativePath} couldn't be resolved. + )`Markdown link with URL code=${linkUrl} in source file path=${relativePath} couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin.${extraHelp}`; }; } else { From 402ff1c2991db0af6874d4a9ee36250febe77540 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 17:09:26 +0200 Subject: [PATCH 31/37] proper onBrokenMarkdownLinks tests --- .../transformImage/__tests__/index.test.ts | 7 +- .../__snapshots__/index.test.ts.snap | 2 +- .../transformLinks/__tests__/index.test.ts | 147 +++++++++++++++--- .../src/remark/transformLinks/index.ts | 82 +++++----- 4 files changed, 175 insertions(+), 63 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index a221b0bff764..6a2a656df0e2 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -194,11 +194,8 @@ describe('transformImage plugin', () => { describe('function form', () => { function processWarn(content: string) { return processContent(content, { - onBrokenMarkdownImages: ({sourceFilePath, url}) => { - console.log('onBrokenMarkdownImages called for ', { - sourceFilePath, - url, - }); + onBrokenMarkdownImages: (params) => { + console.log('onBrokenMarkdownImages called for ', params); return '/404.png'; }, }); diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap index f7fd51dce57d..9d18044775fd 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`transformAsset plugin transform md links to 1`] = ` +exports[`transformLinks plugin transform md links to 1`] = ` "[asset](https://example.com/asset.pdf) /node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./asset.pdf").default} /> diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts index df737c965484..28bf8d1b0abb 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts @@ -5,10 +5,11 @@ * LICENSE file in the root directory of this source tree. */ +import {jest} from '@jest/globals'; import * as path from 'path'; import vfile from 'to-vfile'; -import plugin from '..'; -import transformImage, {type PluginOptions} from '../../transformImage'; +import plugin, {type PluginOptions} from '..'; +import transformImage from '../../transformImage'; const siteDir = path.join(__dirname, `__fixtures__`); @@ -57,7 +58,7 @@ const processContent = async ( return result.value.toString().trim(); }; -describe('transformAsset plugin', () => { +describe('transformLinks plugin', () => { it('transform md links to ', async () => { // TODO split fixture in many smaller test cases const result = await processFixture('asset'); @@ -65,29 +66,131 @@ describe('transformAsset plugin', () => { }); it('pathname protocol', async () => { - const result = await processContent( - `[asset](pathname:///asset/unchecked.pdf)`, - ); - expect(result).toMatchInlineSnapshot( - `"[asset](pathname:///asset/unchecked.pdf)"`, - ); + const result = await processContent(`pathname:///unchecked.pdf)`); + expect(result).toMatchInlineSnapshot(`"pathname:///unchecked.pdf)"`); }); - describe('throws', () => { - it('fail if asset url is absent', async () => { - await expect( - processContent(`[asset]()`), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Markdown link URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" file (title: asset, line: 1)."`, - ); + it('accepts absolute file that does not exist', async () => { + const result = await processContent(`[file](/dir/file.zip)`); + expect(result).toMatchInlineSnapshot(`"[file](/dir/file.zip)"`); + }); + + it('accepts relative file that does not exist', async () => { + const result = await processContent(`[file](dir/file.zip)`); + expect(result).toMatchInlineSnapshot(`"[file](dir/file.zip)"`); + }); + + describe('onBrokenMarkdownLinks', () => { + const fixtures = { + urlEmpty: `[empty]()`, + fileDoesNotExistSiteAlias: `[file](@site/file.zip)`, + }; + + describe('throws', () => { + it('if url is empty', async () => { + await expect(processContent(fixtures.urlEmpty)).rejects + .toThrowErrorMatchingInlineSnapshot(` + "Markdown link with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx". + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." + `); + }); + + it('if file with site alias does not exist', async () => { + await expect(processContent(fixtures.fileDoesNotExistSiteAlias)).rejects + .toThrowErrorMatchingInlineSnapshot(` + "Markdown link with URL \`@site/file.zip\` in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin. + To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." + `); + }); + }); + + describe('warns', () => { + function processWarn(content: string) { + return processContent(content, {onBrokenMarkdownLinks: 'warn'}); + } + + const warnMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); + beforeEach(() => { + warnMock.mockClear(); + }); + + it('if url is empty', async () => { + const result = await processWarn(fixtures.urlEmpty); + expect(result).toMatchInlineSnapshot(`"[empty]()"`); + expect(warnMock).toHaveBeenCalledTimes(1); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "[WARNING] Markdown link with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx".", + ], + ] + `); + }); + + it('if file with site alias does not exist', async () => { + const result = await processWarn(fixtures.fileDoesNotExistSiteAlias); + expect(result).toMatchInlineSnapshot(`"[file](@site/file.zip)"`); + expect(warnMock).toHaveBeenCalledTimes(1); + expect(warnMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "[WARNING] Markdown link with URL \`@site/file.zip\` in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved. + Make sure it references a local Markdown file that exists within the current plugin.", + ], + ] + `); + }); }); - it('fail if asset with site alias does not exist', async () => { - await expect( - processContent(`[nonexistent](@site/foo.pdf)`), - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Asset packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/foo.pdf used in packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx not found."`, - ); + describe('function form', () => { + function processWarn(content: string) { + return processContent(content, { + onBrokenMarkdownLinks: (params) => { + console.log('onBrokenMarkdownLinks called with', params); + return '/404'; + }, + }); + } + + const logMock = jest.spyOn(console, 'log').mockImplementation(() => {}); + beforeEach(() => { + logMock.mockClear(); + }); + + it('if url is empty', async () => { + const result = await processWarn(fixtures.urlEmpty); + expect(result).toMatchInlineSnapshot(`"[empty](/404)"`); + expect(logMock).toHaveBeenCalledTimes(1); + expect(logMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "onBrokenMarkdownLinks called with", + { + "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx", + "url": "", + }, + ], + ] + `); + }); + + it('if file with site alias does not exist', async () => { + const result = await processWarn(fixtures.fileDoesNotExistSiteAlias); + expect(result).toMatchInlineSnapshot(`"[file](/404)"`); + expect(logMock).toHaveBeenCalledTimes(1); + expect(logMock.mock.calls).toMatchInlineSnapshot(` + [ + [ + "onBrokenMarkdownLinks called with", + { + "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx", + "url": "@site/file.zip", + }, + ], + ] + `); + }); }); }); }); diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts index 1271b405872b..8b45c328b9b2 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts @@ -22,26 +22,29 @@ import {assetRequireAttributeValue, transformNode} from '../utils'; import type {Plugin, Transformer} from 'unified'; import type {MdxJsxTextElement} from 'mdast-util-mdx'; import type {Parent} from 'unist'; -import type {Link, Literal, Root} from 'mdast'; +import type {Link, Root} from 'mdast'; import type { MarkdownConfig, OnBrokenMarkdownLinksFunction, } from '@docusaurus/types'; -type PluginOptions = { +export type PluginOptions = { staticDirs: string[]; siteDir: string; onBrokenMarkdownLinks: MarkdownConfig['hooks']['onBrokenMarkdownLinks']; }; type Context = PluginOptions & { + staticDirs: string[]; + siteDir: string; + onBrokenMarkdownLinks: OnBrokenMarkdownLinksFunction; filePath: string; inlineMarkdownLinkFileLoader: string; }; type Target = [node: Link, index: number, parent: Parent]; -export function asFunction( +function asFunction( onBrokenMarkdownLinks: PluginOptions['onBrokenMarkdownLinks'], ): OnBrokenMarkdownLinksFunction { if (typeof onBrokenMarkdownLinks === 'string') { @@ -51,9 +54,16 @@ export function asFunction( : ''; return ({sourceFilePath, url: linkUrl}) => { const relativePath = toMessageRelativeFilePath(sourceFilePath); - logger.report( - onBrokenMarkdownLinks, - )`Markdown link couldn't be resolved: (url=${linkUrl}) in source file path=${relativePath}.${extraHelp}`; + if (linkUrl) { + logger.report( + onBrokenMarkdownLinks, + )`Markdown link with URL code=${linkUrl} in source file path=${relativePath} couldn't be resolved. +Make sure it references a local Markdown file that exists within the current plugin.${extraHelp}`; + } else { + logger.report( + onBrokenMarkdownLinks, + )`Markdown link with empty URL found in source file path=${relativePath}.${extraHelp}`; + } }; } else { return (params) => @@ -152,27 +162,15 @@ async function toAssetRequireNode( }); } -async function ensureAssetFileExist(assetPath: string, sourceFilePath: string) { - const assetExists = await fs.pathExists(assetPath); - if (!assetExists) { - throw new Error( - `Asset ${toMessageRelativeFilePath( - assetPath, - )} used in ${toMessageRelativeFilePath(sourceFilePath)} not found.`, - ); - } -} - -async function getAssetAbsolutePath( +async function getLocalFileAbsolutePath( assetPath: string, {siteDir, filePath, staticDirs}: Context, ) { if (assetPath.startsWith('@site/')) { const assetFilePath = path.join(siteDir, assetPath.replace('@site/', '')); - // The @site alias is the only way to believe that the user wants an asset. - // Everything else can just be a link URL - await ensureAssetFileExist(assetFilePath, filePath); - return assetFilePath; + if (await fs.pathExists(assetFilePath)) { + return assetFilePath; + } } else if (path.isAbsolute(assetPath)) { const assetFilePath = await findAsyncSequential( staticDirs.map((dir) => path.join(dir, assetPath)), @@ -193,16 +191,12 @@ async function getAssetAbsolutePath( async function processLinkNode(target: Target, context: Context) { const [node] = target; if (!node.url) { - // Try to improve error feedback - // see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675 - const title = - node.title ?? (node.children[0] as Literal | undefined)?.value ?? '?'; - const line = node.position?.start.line ?? '?'; - throw new Error( - `Markdown link URL is mandatory in "${toMessageRelativeFilePath( - context.filePath, - )}" file (title: ${title}, line: ${line}).`, - ); + node.url = + context.onBrokenMarkdownLinks({ + url: node.url, + sourceFilePath: context.filePath, + }) ?? node.url; + return; } const parsedUrl = url.parse(node.url); @@ -218,29 +212,47 @@ async function processLinkNode(target: Target, context: Context) { return; } - const assetPath = await getAssetAbsolutePath( + const localFilePath = await getLocalFileAbsolutePath( decodeURIComponent(parsedUrl.pathname), context, ); - if (assetPath) { - await toAssetRequireNode(target, assetPath, context); + + if (localFilePath) { + await toAssetRequireNode(target, localFilePath, context); + } else { + // The @site alias is the only way to believe that the user wants an asset. + if (hasSiteAlias) { + node.url = + context.onBrokenMarkdownLinks({ + url: node.url, + sourceFilePath: context.filePath, + }) ?? node.url; + } else { + // Even if the url has a dot, and it looks like a file extension + // it can be risky to throw and fail fast by default + // It's perfectly valid for a route path segment to look like a filename + } } } const plugin: Plugin = function plugin( options, ): Transformer { + const onBrokenMarkdownLinks = asFunction(options.onBrokenMarkdownLinks); + return async (root, vfile) => { const {visit} = await import('unist-util-visit'); const fileLoaderUtils = getFileLoaderUtils( vfile.data.compilerName === 'server', ); + const context: Context = { ...options, filePath: vfile.path!, inlineMarkdownLinkFileLoader: fileLoaderUtils.loaders.inlineMarkdownLinkFileLoader, + onBrokenMarkdownLinks, }; const promises: Promise[] = []; From 745cd464463a49921405e4e91e75c01f19b22a40 Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 18:30:03 +0200 Subject: [PATCH 32/37] update snapshots --- packages/docusaurus-mdx-loader/src/processor.ts | 1 - .../server/__tests__/__snapshots__/config.test.ts.snap | 10 ++++++++++ .../server/__tests__/__snapshots__/site.test.ts.snap | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/docusaurus-mdx-loader/src/processor.ts b/packages/docusaurus-mdx-loader/src/processor.ts index 3912c6f5c5ba..5a53bc5cce69 100644 --- a/packages/docusaurus-mdx-loader/src/processor.ts +++ b/packages/docusaurus-mdx-loader/src/processor.ts @@ -132,7 +132,6 @@ async function createProcessorFactory() { ? [ resolveMarkdownLinks, { - siteDir: options.siteDir, resolveMarkdownLink: options.resolveMarkdownLink, onBrokenMarkdownLinks: options.markdownConfig.hooks.onBrokenMarkdownLinks, diff --git a/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap b/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap index e565adc3f11f..29b20ea9e97f 100644 --- a/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap +++ b/packages/docusaurus/src/server/__tests__/__snapshots__/config.test.ts.snap @@ -43,6 +43,7 @@ exports[`loadSiteConfig website with .cjs siteConfig 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { @@ -120,6 +121,7 @@ exports[`loadSiteConfig website with ts + js config 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { @@ -197,6 +199,7 @@ exports[`loadSiteConfig website with valid JS CJS config 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { @@ -274,6 +277,7 @@ exports[`loadSiteConfig website with valid JS ESM config 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { @@ -351,6 +355,7 @@ exports[`loadSiteConfig website with valid TypeScript CJS config 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { @@ -428,6 +433,7 @@ exports[`loadSiteConfig website with valid TypeScript ESM config 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { @@ -505,6 +511,7 @@ exports[`loadSiteConfig website with valid async config 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { @@ -584,6 +591,7 @@ exports[`loadSiteConfig website with valid async config creator function 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { @@ -663,6 +671,7 @@ exports[`loadSiteConfig website with valid config creator function 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { @@ -745,6 +754,7 @@ exports[`loadSiteConfig website with valid siteConfig 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { diff --git a/packages/docusaurus/src/server/__tests__/__snapshots__/site.test.ts.snap b/packages/docusaurus/src/server/__tests__/__snapshots__/site.test.ts.snap index 7e3fb1f7dd6f..696ef93444cf 100644 --- a/packages/docusaurus/src/server/__tests__/__snapshots__/site.test.ts.snap +++ b/packages/docusaurus/src/server/__tests__/__snapshots__/site.test.ts.snap @@ -127,6 +127,7 @@ exports[`load loads props for site with custom i18n path 1`] = ` }, "format": "mdx", "hooks": { + "onBrokenMarkdownImages": "throw", "onBrokenMarkdownLinks": "warn", }, "mdx1Compat": { From e6efe415150926d3bcb794c31f9f067af0270d0a Mon Sep 17 00:00:00 2001 From: sebastien Date: Mon, 23 Jun 2025 18:52:13 +0200 Subject: [PATCH 33/37] fix wiring of onBrokenMarkdownLinks option --- packages/docusaurus-mdx-loader/src/processor.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/docusaurus-mdx-loader/src/processor.ts b/packages/docusaurus-mdx-loader/src/processor.ts index 5a53bc5cce69..29b0f8170a44 100644 --- a/packages/docusaurus-mdx-loader/src/processor.ts +++ b/packages/docusaurus-mdx-loader/src/processor.ts @@ -23,6 +23,7 @@ import type {MDXFrontMatter} from './frontMatter'; import type {Options} from './options'; import type {AdmonitionOptions} from './remark/admonitions'; import type {PluginOptions as ResolveMarkdownLinksOptions} from './remark/resolveMarkdownLinks'; +import type {PluginOptions as TransformLinksOptions} from './remark/transformLinks'; import type {PluginOptions as TransformImageOptions} from './remark/transformImage'; import type {ProcessorOptions} from '@mdx-js/mdx'; @@ -143,7 +144,9 @@ async function createProcessorFactory() { { staticDirs: options.staticDirs, siteDir: options.siteDir, - }, + onBrokenMarkdownLinks: + options.markdownConfig.hooks.onBrokenMarkdownLinks, + } satisfies TransformLinksOptions, ], gfm, options.markdownConfig.mdx1Compat.comments ? comment : null, From 5b0240d1604dded6640c0d8443105ff7e509ccf0 Mon Sep 17 00:00:00 2001 From: sebastien Date: Tue, 24 Jun 2025 15:06:08 +0200 Subject: [PATCH 34/37] Add AST node to API + line numbering in error message --- .../src/remark/resolveMarkdownLinks/index.ts | 2 + .../transformImage/__tests__/index.test.ts | 99 ++++++++++++++++--- .../src/remark/transformImage/index.ts | 18 +++- .../src/remark/transformLinks/index.ts | 2 + .../src/remark/unusedDirectives/index.ts | 12 +-- .../src/remark/utils/index.ts | 14 +++ packages/docusaurus-types/package.json | 1 + packages/docusaurus-types/src/markdown.d.ts | 10 ++ 8 files changed, 132 insertions(+), 26 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts index e33f1e109919..a4917b476823 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts @@ -12,6 +12,7 @@ import { type URLPath, } from '@docusaurus/utils'; import logger from '@docusaurus/logger'; + import type {Plugin, Transformer} from 'unified'; import type {Definition, Link, Root} from 'mdast'; import type { @@ -124,6 +125,7 @@ const plugin: Plugin = function plugin( onBrokenMarkdownLinks({ url: link.url, sourceFilePath, + node: link, }) ?? link.url; } }); diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index 6a2a656df0e2..2c7c75d73119 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -86,7 +86,7 @@ describe('transformImage plugin', () => { it('if image absolute path does not exist', async () => { await expect(processContent(fixtures.doesNotExistAbsolute)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown image with URL \`/img/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. + "Markdown image with URL \`/img/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" (1:1) couldn't be resolved to an existing local image file. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownImages\` option, or apply the \`pathname://\` protocol to the broken image URLs." `); }); @@ -94,7 +94,7 @@ describe('transformImage plugin', () => { it('if image relative path does not exist', async () => { await expect(processContent(fixtures.doesNotExistRelative)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown image with URL \`./doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. + "Markdown image with URL \`./doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" (1:1) couldn't be resolved to an existing local image file. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownImages\` option, or apply the \`pathname://\` protocol to the broken image URLs." `); }); @@ -102,7 +102,7 @@ describe('transformImage plugin', () => { it('if image @site path does not exist', async () => { await expect(processContent(fixtures.doesNotExistSiteAlias)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown image with URL \`@site/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file. + "Markdown image with URL \`@site/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" (1:1) couldn't be resolved to an existing local image file. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownImages\` option, or apply the \`pathname://\` protocol to the broken image URLs." `); }); @@ -110,7 +110,7 @@ describe('transformImage plugin', () => { it('if image url empty', async () => { await expect(processContent(fixtures.urlEmpty)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown image with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx". + "Markdown image with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" (1:1). To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownImages\` option, or apply the \`pathname://\` protocol to the broken image URLs." `); }); @@ -136,7 +136,7 @@ describe('transformImage plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown image with URL \`/img/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file.", + "[WARNING] Markdown image with URL \`/img/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" (1:1) couldn't be resolved to an existing local image file.", ], ] `); @@ -152,7 +152,7 @@ describe('transformImage plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown image with URL \`./doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file.", + "[WARNING] Markdown image with URL \`./doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" (1:1) couldn't be resolved to an existing local image file.", ], ] `); @@ -168,7 +168,7 @@ describe('transformImage plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown image with URL \`@site/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved to an existing local image file.", + "[WARNING] Markdown image with URL \`@site/doesNotExist.png\` in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" (1:1) couldn't be resolved to an existing local image file.", ], ] `); @@ -184,7 +184,7 @@ describe('transformImage plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown image with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx".", + "[WARNING] Markdown image with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx" (1:1).", ], ] `); @@ -196,6 +196,9 @@ describe('transformImage plugin', () => { return processContent(content, { onBrokenMarkdownImages: (params) => { console.log('onBrokenMarkdownImages called for ', params); + // We can alter the AST Node + params.node.alt = 'new 404 alt'; + // Or return a new URL return '/404.png'; }, }); @@ -209,7 +212,7 @@ describe('transformImage plugin', () => { it('if image absolute path does not exist', async () => { const result = await processWarn(fixtures.doesNotExistAbsolute); expect(result).toMatchInlineSnapshot(` - "![img](/404.png) + "![new 404 alt](/404.png) " `); expect(logMock).toHaveBeenCalledTimes(1); @@ -218,6 +221,24 @@ describe('transformImage plugin', () => { [ "onBrokenMarkdownImages called for ", { + "node": { + "alt": "new 404 alt", + "position": { + "end": { + "column": 30, + "line": 1, + "offset": 29, + }, + "start": { + "column": 1, + "line": 1, + "offset": 0, + }, + }, + "title": null, + "type": "image", + "url": "/404.png", + }, "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx", "url": "/img/doesNotExist.png", }, @@ -229,7 +250,7 @@ describe('transformImage plugin', () => { it('if image relative path does not exist', async () => { const result = await processWarn(fixtures.doesNotExistRelative); expect(result).toMatchInlineSnapshot(` - "![img](/404.png) + "![new 404 alt](/404.png) " `); expect(logMock).toHaveBeenCalledTimes(1); @@ -238,6 +259,24 @@ describe('transformImage plugin', () => { [ "onBrokenMarkdownImages called for ", { + "node": { + "alt": "new 404 alt", + "position": { + "end": { + "column": 27, + "line": 1, + "offset": 26, + }, + "start": { + "column": 1, + "line": 1, + "offset": 0, + }, + }, + "title": null, + "type": "image", + "url": "/404.png", + }, "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx", "url": "./doesNotExist.png", }, @@ -249,7 +288,7 @@ describe('transformImage plugin', () => { it('if image @site path does not exist', async () => { const result = await processWarn(fixtures.doesNotExistSiteAlias); expect(result).toMatchInlineSnapshot(` - "![img](/404.png) + "![new 404 alt](/404.png) " `); expect(logMock).toHaveBeenCalledTimes(1); @@ -258,6 +297,24 @@ describe('transformImage plugin', () => { [ "onBrokenMarkdownImages called for ", { + "node": { + "alt": "new 404 alt", + "position": { + "end": { + "column": 31, + "line": 1, + "offset": 30, + }, + "start": { + "column": 1, + "line": 1, + "offset": 0, + }, + }, + "title": null, + "type": "image", + "url": "/404.png", + }, "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx", "url": "@site/doesNotExist.png", }, @@ -269,7 +326,7 @@ describe('transformImage plugin', () => { it('if image url empty', async () => { const result = await processWarn(fixtures.urlEmpty); expect(result).toMatchInlineSnapshot(` - "![img](/404.png) + "![new 404 alt](/404.png) " `); expect(logMock).toHaveBeenCalledTimes(1); @@ -278,6 +335,24 @@ describe('transformImage plugin', () => { [ "onBrokenMarkdownImages called for ", { + "node": { + "alt": "new 404 alt", + "position": { + "end": { + "column": 9, + "line": 1, + "offset": 8, + }, + "start": { + "column": 1, + "line": 1, + "offset": 0, + }, + }, + "title": null, + "type": "image", + "url": "/404.png", + }, "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/docs/myFile.mdx", "url": "", }, diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts index fb940bd66cd8..1dc00aa89457 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts @@ -19,7 +19,11 @@ import { import escapeHtml from 'escape-html'; import {imageSizeFromFile} from 'image-size/fromFile'; import logger from '@docusaurus/logger'; -import {assetRequireAttributeValue, transformNode} from '../utils'; +import { + assetRequireAttributeValue, + formatNodePositionExtraMessage, + transformNode, +} from '../utils'; import type {Plugin, Transformer} from 'unified'; import type {MdxJsxTextElement} from 'mdast-util-mdx'; import type {Image, Root} from 'mdast'; @@ -51,16 +55,20 @@ function asFunction( onBrokenMarkdownImages === 'throw' ? logger.interpolate`\nTo ignore this error, use the code=${'siteConfig.markdown.hooks.onBrokenMarkdownImages'} option, or apply the code=${'pathname://'} protocol to the broken image URLs.` : ''; - return ({sourceFilePath, url: imageUrl}) => { + return ({sourceFilePath, url: imageUrl, node}) => { const relativePath = toMessageRelativeFilePath(sourceFilePath); if (imageUrl) { logger.report( onBrokenMarkdownImages, - )`Markdown image with URL code=${imageUrl} in source file path=${relativePath} couldn't be resolved to an existing local image file.${extraHelp}`; + )`Markdown image with URL code=${imageUrl} in source file path=${relativePath}${formatNodePositionExtraMessage( + node, + )} couldn't be resolved to an existing local image file.${extraHelp}`; } else { logger.report( onBrokenMarkdownImages, - )`Markdown image with empty URL found in source file path=${relativePath}.${extraHelp}`; + )`Markdown image with empty URL found in source file path=${relativePath}${formatNodePositionExtraMessage( + node, + )}.${extraHelp}`; } }; } else { @@ -194,6 +202,7 @@ async function processImageNode(target: Target, context: Context) { context.onBrokenMarkdownImages({ url: node.url, sourceFilePath: context.filePath, + node, }) ?? node.url; return; } @@ -224,6 +233,7 @@ async function processImageNode(target: Target, context: Context) { context.onBrokenMarkdownImages({ url: node.url, sourceFilePath: context.filePath, + node, }) ?? node.url; } else { await toImageRequireNode(target, localImagePath, context); diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts index 8b45c328b9b2..8d0cd711eef2 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts @@ -195,6 +195,7 @@ async function processLinkNode(target: Target, context: Context) { context.onBrokenMarkdownLinks({ url: node.url, sourceFilePath: context.filePath, + node, }) ?? node.url; return; } @@ -226,6 +227,7 @@ async function processLinkNode(target: Target, context: Context) { context.onBrokenMarkdownLinks({ url: node.url, sourceFilePath: context.filePath, + node, }) ?? node.url; } else { // Even if the url has a dot, and it looks like a file extension diff --git a/packages/docusaurus-mdx-loader/src/remark/unusedDirectives/index.ts b/packages/docusaurus-mdx-loader/src/remark/unusedDirectives/index.ts index 0e0afa14fbe3..29b458b19ce9 100644 --- a/packages/docusaurus-mdx-loader/src/remark/unusedDirectives/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/unusedDirectives/index.ts @@ -8,7 +8,7 @@ import path from 'path'; import process from 'process'; import logger from '@docusaurus/logger'; import {posixPath} from '@docusaurus/utils'; -import {transformNode} from '../utils'; +import {formatNodePositionExtraMessage, transformNode} from '../utils'; import type {Root} from 'mdast'; import type {Parent} from 'unist'; import type {Transformer, Processor, Plugin} from 'unified'; @@ -39,17 +39,9 @@ function formatDirectiveName(directive: Directives) { return `${prefix}${directive.name}`; } -function formatDirectivePosition(directive: Directives): string | undefined { - return directive.position?.start - ? logger.interpolate`number=${directive.position.start.line}:number=${directive.position.start.column}` - : undefined; -} - function formatUnusedDirectiveMessage(directive: Directives) { const name = formatDirectiveName(directive); - const position = formatDirectivePosition(directive); - - return `- ${name} ${position ? `(${position})` : ''}`; + return `- ${name}${formatNodePositionExtraMessage(directive)}`; } function formatUnusedDirectivesMessage({ diff --git a/packages/docusaurus-mdx-loader/src/remark/utils/index.ts b/packages/docusaurus-mdx-loader/src/remark/utils/index.ts index 898f0617a4d2..3b0c215ec98f 100644 --- a/packages/docusaurus-mdx-loader/src/remark/utils/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/utils/index.ts @@ -5,6 +5,7 @@ * LICENSE file in the root directory of this source tree. */ +import logger from '@docusaurus/logger'; import type {Node} from 'unist'; import type {MdxJsxAttributeValueExpression} from 'mdast-util-mdx'; @@ -83,3 +84,16 @@ export function assetRequireAttributeValue( }, }; } + +function formatNodePosition(node: Node): string | undefined { + return node.position?.start + ? logger.interpolate`number=${node.position.start.line}:number=${node.position.start.column}` + : undefined; +} + +// Returns " (line:column)" when position info is available +// The initial space is useful to append easily to any existing message +export function formatNodePositionExtraMessage(node: Node): string { + const position = formatNodePosition(node); + return `${position ? ` (${position})` : ''}`; +} diff --git a/packages/docusaurus-types/package.json b/packages/docusaurus-types/package.json index db8872ca42df..6636f2592dca 100644 --- a/packages/docusaurus-types/package.json +++ b/packages/docusaurus-types/package.json @@ -15,6 +15,7 @@ "dependencies": { "@mdx-js/mdx": "^3.0.0", "@types/history": "^4.7.11", + "@types/mdast": "^4.0.2", "@types/react": "*", "commander": "^5.1.0", "joi": "^17.9.2", diff --git a/packages/docusaurus-types/src/markdown.d.ts b/packages/docusaurus-types/src/markdown.d.ts index d2ac1d173738..fe5e1c36946a 100644 --- a/packages/docusaurus-types/src/markdown.d.ts +++ b/packages/docusaurus-types/src/markdown.d.ts @@ -6,6 +6,8 @@ */ import type {ProcessorOptions} from '@mdx-js/mdx'; +import type {Image, Definition, Link} from 'mdast'; + import type {ReportingSeverity} from './reporting'; export type RemarkRehypeOptions = ProcessorOptions['remarkRehypeOptions']; @@ -57,6 +59,10 @@ export type OnBrokenMarkdownLinksFunction = (params: { * Example: "relative/dir/myTargetDoc.mdx?query#hash" */ url: string; + /** + * The Markdown Link AST node. + */ + node: Link | Definition; }) => void | string; export type OnBrokenMarkdownImagesFunction = (params: { @@ -74,6 +80,10 @@ export type OnBrokenMarkdownImagesFunction = (params: { * Example: "relative/dir/myImage.png" */ url: string; + /** + * The Markdown Image AST node. + */ + node: Image; }) => void | string; export type MarkdownHooks = { From c73998b8201c43ad9b7ab4209e56781686317496 Mon Sep 17 00:00:00 2001 From: sebastien Date: Tue, 24 Jun 2025 15:13:52 +0200 Subject: [PATCH 35/37] Add AST node to API + line numbering in error message --- .../__tests__/index.test.ts | 131 ++++++++++++++---- .../src/remark/resolveMarkdownLinks/index.ts | 7 +- .../transformImage/__tests__/index.test.ts | 1 + 3 files changed, 111 insertions(+), 28 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts index 41e5b174845a..903ac9bf123f 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/index.test.ts @@ -206,7 +206,7 @@ this is a code block await expect(() => processResolutionErrors(content)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown link with URL \`link1.mdx\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + "Markdown link with URL \`link1.mdx\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" (1:1) couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." `); @@ -218,7 +218,7 @@ this is a code block await expect(() => processResolutionErrors(content)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown link with URL \`link1.md\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + "Markdown link with URL \`link1.md\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" (1:1) couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." `); @@ -255,11 +255,11 @@ this is a code block expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown link with URL \`link1.mdx\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + "[WARNING] Markdown link with URL \`link1.mdx\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" (2:1) couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin.", ], [ - "[WARNING] Markdown link with URL \`dir/link3.md\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" couldn't be resolved. + "[WARNING] Markdown link with URL \`dir/link3.md\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" (6:1) couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin.", ], ] @@ -278,36 +278,115 @@ this is a code block [link 4](/link/4) `; - const result = await processResolutionErrors( - content, - ({sourceFilePath, url}) => { - console.warn(`recovering broken markdown link ${url}`); - return `/recovered/___${sourceFilePath}___/___${url}`; - }, - ); + const result = await processResolutionErrors(content, (params) => { + console.warn(`onBrokenMarkdownLinks called with`, params); + // We can alter the AST Node + params.node.title = 'fixed link title'; + params.node.url = 'ignored, less important than returned value'; + // Or return a new URL + return `/recovered-link`; + }); expect(result).toMatchInlineSnapshot(` - "[link1](/recovered/___packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx___/___link1.mdx) + "[link1](/recovered-link "fixed link title") - [link2](link2) + [link2](link2) - [link3](/recovered/___packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx___/___dir/link3.md?query#hash) + [link3](/recovered-link "fixed link title") - [link 4](/link/4) - " - `); + [link 4](/link/4) + " + `); expect(warnMock).toHaveBeenCalledTimes(2); expect(warnMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "recovering broken markdown link link1.mdx", - ], - [ - "recovering broken markdown link dir/link3.md?query#hash", - ], - ] - `); + [ + [ + "onBrokenMarkdownLinks called with", + { + "node": { + "children": [ + { + "position": { + "end": { + "column": 7, + "line": 2, + "offset": 7, + }, + "start": { + "column": 2, + "line": 2, + "offset": 2, + }, + }, + "type": "text", + "value": "link1", + }, + ], + "position": { + "end": { + "column": 19, + "line": 2, + "offset": 19, + }, + "start": { + "column": 1, + "line": 2, + "offset": 1, + }, + }, + "title": "fixed link title", + "type": "link", + "url": "/recovered-link", + }, + "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx", + "url": "link1.mdx", + }, + ], + [ + "onBrokenMarkdownLinks called with", + { + "node": { + "children": [ + { + "position": { + "end": { + "column": 7, + "line": 6, + "offset": 43, + }, + "start": { + "column": 2, + "line": 6, + "offset": 38, + }, + }, + "type": "text", + "value": "link3", + }, + ], + "position": { + "end": { + "column": 33, + "line": 6, + "offset": 69, + }, + "start": { + "column": 1, + "line": 6, + "offset": 37, + }, + }, + "title": "fixed link title", + "type": "link", + "url": "/recovered-link", + }, + "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx", + "url": "dir/link3.md?query#hash", + }, + ], + ] + `); }); }); }); diff --git a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts index a4917b476823..326c0d831dae 100644 --- a/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/index.ts @@ -13,6 +13,7 @@ import { } from '@docusaurus/utils'; import logger from '@docusaurus/logger'; +import {formatNodePositionExtraMessage} from '../utils'; import type {Plugin, Transformer} from 'unified'; import type {Definition, Link, Root} from 'mdast'; import type { @@ -49,11 +50,13 @@ function asFunction( onBrokenMarkdownLinks === 'throw' ? logger.interpolate`\nTo ignore this error, use the code=${'siteConfig.markdown.hooks.onBrokenMarkdownLinks'} option, or apply the code=${'pathname://'} protocol to the broken link URLs.` : ''; - return ({sourceFilePath, url: linkUrl}) => { + return ({sourceFilePath, url: linkUrl, node}) => { const relativePath = toMessageRelativeFilePath(sourceFilePath); logger.report( onBrokenMarkdownLinks, - )`Markdown link with URL code=${linkUrl} in source file path=${relativePath} couldn't be resolved. + )`Markdown link with URL code=${linkUrl} in source file path=${relativePath}${formatNodePositionExtraMessage( + node, + )} couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin.${extraHelp}`; }; } else { diff --git a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts index 2c7c75d73119..1b6b82c41376 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts @@ -198,6 +198,7 @@ describe('transformImage plugin', () => { console.log('onBrokenMarkdownImages called for ', params); // We can alter the AST Node params.node.alt = 'new 404 alt'; + params.node.url = 'ignored, less important than returned value'; // Or return a new URL return '/404.png'; }, From f0e9aded5771a4ac41305d62ad9dc88cb95ee3f0 Mon Sep 17 00:00:00 2001 From: sebastien Date: Tue, 24 Jun 2025 15:16:45 +0200 Subject: [PATCH 36/37] Add AST node to API + line numbering in error message --- .../transformLinks/__tests__/index.test.ts | 90 +++++++++++++++++-- .../src/remark/transformLinks/index.ts | 17 +++- 2 files changed, 97 insertions(+), 10 deletions(-) diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts index 28bf8d1b0abb..7dee411e4084 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts @@ -90,7 +90,7 @@ describe('transformLinks plugin', () => { it('if url is empty', async () => { await expect(processContent(fixtures.urlEmpty)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown link with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx". + "Markdown link with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" (1:1). To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." `); }); @@ -98,7 +98,7 @@ describe('transformLinks plugin', () => { it('if file with site alias does not exist', async () => { await expect(processContent(fixtures.fileDoesNotExistSiteAlias)).rejects .toThrowErrorMatchingInlineSnapshot(` - "Markdown link with URL \`@site/file.zip\` in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved. + "Markdown link with URL \`@site/file.zip\` in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" (1:1) couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin. To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs." `); @@ -122,7 +122,7 @@ describe('transformLinks plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown link with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx".", + "[WARNING] Markdown link with empty URL found in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" (1:1).", ], ] `); @@ -135,7 +135,7 @@ describe('transformLinks plugin', () => { expect(warnMock.mock.calls).toMatchInlineSnapshot(` [ [ - "[WARNING] Markdown link with URL \`@site/file.zip\` in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" couldn't be resolved. + "[WARNING] Markdown link with URL \`@site/file.zip\` in source file "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx" (1:1) couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin.", ], ] @@ -148,6 +148,10 @@ describe('transformLinks plugin', () => { return processContent(content, { onBrokenMarkdownLinks: (params) => { console.log('onBrokenMarkdownLinks called with', params); + // We can alter the AST Node + params.node.title = 'fixed link title'; + params.node.url = 'ignored, less important than returned value'; + // Or return a new URL return '/404'; }, }); @@ -160,13 +164,50 @@ describe('transformLinks plugin', () => { it('if url is empty', async () => { const result = await processWarn(fixtures.urlEmpty); - expect(result).toMatchInlineSnapshot(`"[empty](/404)"`); + expect(result).toMatchInlineSnapshot( + `"[empty](/404 "fixed link title")"`, + ); expect(logMock).toHaveBeenCalledTimes(1); expect(logMock.mock.calls).toMatchInlineSnapshot(` [ [ "onBrokenMarkdownLinks called with", { + "node": { + "children": [ + { + "position": { + "end": { + "column": 7, + "line": 1, + "offset": 6, + }, + "start": { + "column": 2, + "line": 1, + "offset": 1, + }, + }, + "type": "text", + "value": "empty", + }, + ], + "position": { + "end": { + "column": 10, + "line": 1, + "offset": 9, + }, + "start": { + "column": 1, + "line": 1, + "offset": 0, + }, + }, + "title": "fixed link title", + "type": "link", + "url": "/404", + }, "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx", "url": "", }, @@ -177,13 +218,50 @@ describe('transformLinks plugin', () => { it('if file with site alias does not exist', async () => { const result = await processWarn(fixtures.fileDoesNotExistSiteAlias); - expect(result).toMatchInlineSnapshot(`"[file](/404)"`); + expect(result).toMatchInlineSnapshot( + `"[file](/404 "fixed link title")"`, + ); expect(logMock).toHaveBeenCalledTimes(1); expect(logMock.mock.calls).toMatchInlineSnapshot(` [ [ "onBrokenMarkdownLinks called with", { + "node": { + "children": [ + { + "position": { + "end": { + "column": 6, + "line": 1, + "offset": 5, + }, + "start": { + "column": 2, + "line": 1, + "offset": 1, + }, + }, + "type": "text", + "value": "file", + }, + ], + "position": { + "end": { + "column": 23, + "line": 1, + "offset": 22, + }, + "start": { + "column": 1, + "line": 1, + "offset": 0, + }, + }, + "title": "fixed link title", + "type": "link", + "url": "/404", + }, "sourceFilePath": "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/docs/myFile.mdx", "url": "@site/file.zip", }, diff --git a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts index 8d0cd711eef2..5d2d2d2d953f 100644 --- a/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts +++ b/packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts @@ -18,7 +18,11 @@ import { } from '@docusaurus/utils'; import escapeHtml from 'escape-html'; import logger from '@docusaurus/logger'; -import {assetRequireAttributeValue, transformNode} from '../utils'; +import { + assetRequireAttributeValue, + formatNodePositionExtraMessage, + transformNode, +} from '../utils'; import type {Plugin, Transformer} from 'unified'; import type {MdxJsxTextElement} from 'mdast-util-mdx'; import type {Parent} from 'unist'; @@ -52,17 +56,22 @@ function asFunction( onBrokenMarkdownLinks === 'throw' ? logger.interpolate`\nTo ignore this error, use the code=${'siteConfig.markdown.hooks.onBrokenMarkdownLinks'} option, or apply the code=${'pathname://'} protocol to the broken link URLs.` : ''; - return ({sourceFilePath, url: linkUrl}) => { + + return ({sourceFilePath, url: linkUrl, node}) => { const relativePath = toMessageRelativeFilePath(sourceFilePath); if (linkUrl) { logger.report( onBrokenMarkdownLinks, - )`Markdown link with URL code=${linkUrl} in source file path=${relativePath} couldn't be resolved. + )`Markdown link with URL code=${linkUrl} in source file path=${relativePath}${formatNodePositionExtraMessage( + node, + )} couldn't be resolved. Make sure it references a local Markdown file that exists within the current plugin.${extraHelp}`; } else { logger.report( onBrokenMarkdownLinks, - )`Markdown link with empty URL found in source file path=${relativePath}.${extraHelp}`; + )`Markdown link with empty URL found in source file path=${relativePath}${formatNodePositionExtraMessage( + node, + )}.${extraHelp}`; } }; } else { From 4496b59bc638ac04eb49f0d385d5bf18c531bb48 Mon Sep 17 00:00:00 2001 From: sebastien Date: Tue, 24 Jun 2025 15:36:23 +0200 Subject: [PATCH 37/37] Add docs --- website/docs/api/docusaurus.config.js.mdx | 35 +++++++++++++++++++++++ website/docusaurus.config-blog-only.js | 1 - 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/website/docs/api/docusaurus.config.js.mdx b/website/docs/api/docusaurus.config.js.mdx index e746377ba782..8cdbe3080e7e 100644 --- a/website/docs/api/docusaurus.config.js.mdx +++ b/website/docs/api/docusaurus.config.js.mdx @@ -275,6 +275,14 @@ By default, it prints a warning, to let you know about your broken anchors. ### `onBrokenMarkdownLinks` {#onBrokenMarkdownLinks} +:::warning Deprecated + +Deprecated in Docusaurus v3.9, and will be removed in Docusaurus v4. + +Replaced by [`siteConfig.markdown.hooks.onBrokenMarkdownLinks`](#hooks.onBrokenMarkdownLinks) + +::: + - Type: `'ignore' | 'log' | 'warn' | 'throw'` The behavior of Docusaurus when it detects any broken Markdown link. @@ -511,6 +519,25 @@ type MarkdownAnchorsConfig = { maintainCase: boolean; }; +type OnBrokenMarkdownLinksFunction = (params: { + sourceFilePath: string; // MD/MDX source file relative to cwd + url: string; // Link url + node: Link | Definition; // mdast Node +}) => void | string; + +type OnBrokenMarkdownImagesFunction = (params: { + sourceFilePath: string; // MD/MDX source file relative to cwd + url: string; // Image url + node: Image; // mdast node +}) => void | string; + +type ReportingSeverity = 'ignore' | 'log' | 'warn' | 'throw'; + +type MarkdownHooks = { + onBrokenMarkdownLinks: ReportingSeverity | OnBrokenMarkdownLinksFunction; + onBrokenMarkdownImages: ReportingSeverity | OnBrokenMarkdownImagesFunction; +}; + type MarkdownConfig = { format: 'mdx' | 'md' | 'detect'; mermaid: boolean; @@ -519,6 +546,7 @@ type MarkdownConfig = { mdx1Compat: MDX1CompatOptions; remarkRehypeOptions: object; // see https://github.com/remarkjs/remark-rehype#options anchors: MarkdownAnchorsConfig; + hooks: MarkdownHooks; }; ``` @@ -546,6 +574,10 @@ export default { anchors: { maintainCase: true, }, + hooks: { + onBrokenMarkdownLinks: 'warn', + onBrokenMarkdownImages: 'throw', + }, }, }; ``` @@ -563,6 +595,9 @@ export default { | `mdx1Compat` | `MDX1CompatOptions` | `{comments: true, admonitions: true, headingIds: true}` | Compatibility options to make it easier to upgrade to Docusaurus v3+. | | `anchors` | `MarkdownAnchorsConfig` | `{maintainCase: false}` | Options to control the behavior of anchors generated from Markdown headings | | `remarkRehypeOptions` | `object` | `undefined` | Makes it possible to pass custom [`remark-rehype` options](https://github.com/remarkjs/remark-rehype#options). | +| `hooks` | `MarkdownHooks` | `object` | Make it possible to customize the MDX loader behavior with callbacks or built-in options. | +| `hooks.onBrokenMarkdownLinks` | `ReportingSeverity \| OnBrokenMarkdownLinksFunction` | `'warn'` | Hook to customize the behavior when encountering a broken Markdown link URL. With the callback function, you can return a new link URL, or alter the link [mdast node](https://github.com/syntax-tree/mdast). | +| `hooks.onBrokenMarkdownLinks` | `ReportingSeverity \| OnBrokenMarkdownImagesFunction` | `'throw'` | Hook to customize the behavior when encountering a broken Markdown image URL. With the callback function, you can return a new image URL, or alter the image [mdast node](https://github.com/syntax-tree/mdast). | ```mdx-code-block diff --git a/website/docusaurus.config-blog-only.js b/website/docusaurus.config-blog-only.js index af7a53bd0096..fb434ffa7b93 100644 --- a/website/docusaurus.config-blog-only.js +++ b/website/docusaurus.config-blog-only.js @@ -15,7 +15,6 @@ export default { url: 'https://docusaurus.io', // We can only warn now, since we have blog pages linking to non-blog pages... onBrokenLinks: 'warn', - onBrokenMarkdownLinks: 'warn', favicon: 'img/docusaurus.ico', themes: ['live-codeblock'], plugins: ['ideal-image'],