Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(utils): make Markdown link replacement much more rigorous #8927

Merged
merged 2 commits into from
Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,27 @@ exports[`replaceMarkdownLinks does basic replace 1`] = `
}
`;

exports[`replaceMarkdownLinks handles link titles 1`] = `
{
"brokenMarkdownLinks": [],
"newContent": "
[URL](/docs/file "title")
[URL](/docs/file 'title')
[URL](/docs/file (title))
",
}
`;

exports[`replaceMarkdownLinks handles stray spaces 1`] = `
{
"brokenMarkdownLinks": [],
"newContent": "
[URL]( /docs/file )
[ref]: /docs/file
",
}
`;

exports[`replaceMarkdownLinks ignores links in HTML comments 1`] = `
{
"brokenMarkdownLinks": [
Expand Down Expand Up @@ -110,16 +131,26 @@ exports[`replaceMarkdownLinks ignores links in inline code 1`] = `
}
`;

exports[`replaceMarkdownLinks preserves query/hash 1`] = `
{
"brokenMarkdownLinks": [],
"newContent": "
[URL](/docs/file?foo=bar#baz)
[URL](/docs/file#a)
[URL](/docs/file?c)
",
}
`;

exports[`replaceMarkdownLinks replaces Markdown links with spaces 1`] = `
{
"brokenMarkdownLinks": [],
"newContent": "
[doc a](/docs/doc%20a)
[doc a](</docs/doc%20a>)
[doc a](/docs/doc%20a)
[doc b](/docs/my%20docs/doc%20b)
[doc b](</docs/my%20docs/doc%20b>)
[doc b](/docs/my%20docs/doc%20b)
[doc]: </docs/my%20docs/doc%20b>
",
}
`;
Expand Down
94 changes: 92 additions & 2 deletions packages/docusaurus-utils/src/__tests__/markdownLinks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,10 +277,100 @@ The following operations are defined for [URI]s:
fileString: `
[doc a](./doc%20a.md)
[doc a](<./doc a.md>)
[doc a](./doc a.md)
slorber marked this conversation as resolved.
Show resolved Hide resolved
[doc b](./my%20docs/doc%20b.md)
[doc b](<./my docs/doc b.md>)
[doc b](./my docs/doc b.md)
[doc]: <./my docs/doc b.md>
`,
}),
).toMatchSnapshot();
});

it('does not replace non-Markdown links', () => {
const input = `
[asset](./file.md_asset/1.png)
[URL](<https://example.com/file_(1).md>)
[not a link]((foo)
[not a link](foo bar)
[not a link]: foo bar
[not a link]: (foo
[not a link]: bar)
`;
expect(
replaceMarkdownLinks({
siteDir: '.',
filePath: 'docs/file.md',
contentPaths: {
contentPath: 'docs',
contentPathLocalized: 'i18n/docs-localized',
},
sourceToPermalink: {
'@site/docs/file.md': '/docs/file',
},
fileString: input,
}),
).toEqual({
newContent: input,
brokenMarkdownLinks: [],
});
});

it('handles stray spaces', () => {
expect(
replaceMarkdownLinks({
siteDir: '.',
filePath: 'docs/file.md',
contentPaths: {
contentPath: 'docs',
contentPathLocalized: 'i18n/docs-localized',
},
sourceToPermalink: {
'@site/docs/file.md': '/docs/file',
},
fileString: `
[URL]( ./file.md )
[ref]: ./file.md
`,
}),
).toMatchSnapshot();
});

it('handles link titles', () => {
expect(
replaceMarkdownLinks({
siteDir: '.',
filePath: 'docs/file.md',
contentPaths: {
contentPath: 'docs',
contentPathLocalized: 'i18n/docs-localized',
},
sourceToPermalink: {
'@site/docs/file.md': '/docs/file',
},
fileString: `
[URL](./file.md "title")
[URL](./file.md 'title')
[URL](./file.md (title))
`,
}),
).toMatchSnapshot();
});

it('preserves query/hash', () => {
expect(
replaceMarkdownLinks({
siteDir: '.',
filePath: 'docs/file.md',
contentPaths: {
contentPath: 'docs',
contentPathLocalized: 'i18n/docs-localized',
},
sourceToPermalink: {
'@site/docs/file.md': '/docs/file',
},
fileString: `
[URL](./file.md?foo=bar#baz)
[URL](./file.md#a)
[URL](./file.md?c)
`,
}),
).toMatchSnapshot();
Expand Down
34 changes: 24 additions & 10 deletions packages/docusaurus-utils/src/markdownLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,26 @@ export function replaceMarkdownLinks<T extends ContentPaths>({
// Replace inline-style links or reference-style links e.g:
// This is [Document 1](doc1.md)
// [doc1]: doc1.md
const mdRegex =
/(?:\]\(|\]:\s*)(?!https?:\/\/|@site\/)<?(?<filename>[^'"\]\s>]+(?:\s[^'"\]\s>]+)*\.mdx?)>?/g;
let mdMatch = mdRegex.exec(modifiedLine);
const linkTitlePattern = '(?:\\s+(?:\'.*?\'|".*?"|\\(.*?\\)))?';
const linkSuffixPattern = '(?:\\?[^#>\\s]+)?(?:#[^>\\s]+)?';
const linkCapture = (forbidden: string) =>
`((?!https?://|@site/)[^${forbidden}#?]+)`;
const linkURLPattern = `(?:${linkCapture(
'()\\s',
)}${linkSuffixPattern}|<${linkCapture('>')}${linkSuffixPattern}>)`;
const linkPattern = new RegExp(
`\\[(?:(?!\\]\\().)*\\]\\(\\s*${linkURLPattern}${linkTitlePattern}\\s*\\)|^\\s*\\[[^[\\]]*[^[\\]\\s][^[\\]]*\\]:\\s*${linkURLPattern}${linkTitlePattern}$`,
'dgm',
);
let mdMatch = linkPattern.exec(modifiedLine);
while (mdMatch !== null) {
// Replace it to correct html link.
const mdLink = mdMatch.groups!.filename!;
const mdLink = mdMatch.slice(1, 5).find(Boolean)!;
const mdLinkRange = mdMatch.indices!.slice(1, 5).find(Boolean)!;
if (!/\.mdx?$/.test(mdLink)) {
mdMatch = linkPattern.exec(modifiedLine);
continue;
}
Comment on lines +105 to +124
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


const sourcesToTry: string[] = [];
// ./file.md and ../file.md are always relative to the current file
Expand Down Expand Up @@ -135,13 +149,13 @@ export function replaceMarkdownLinks<T extends ContentPaths>({
.split('/')
.map((part) => part.replace(/\s/g, '%20'))
.join('/');
modifiedLine = modifiedLine.replace(
mdMatch[0]!,
mdMatch[0]!.replace(mdLink, encodedPermalink),
);
modifiedLine = `${modifiedLine.slice(
0,
mdLinkRange[0],
)}${encodedPermalink}${modifiedLine.slice(mdLinkRange[1])}`;
// Adjust the lastIndex to avoid passing over the next link if the
// newly replaced URL is shorter.
mdRegex.lastIndex += encodedPermalink.length - mdLink.length;
linkPattern.lastIndex += encodedPermalink.length - mdLink.length;
} else {
const brokenMarkdownLink: BrokenMarkdownLink<T> = {
contentPaths,
Expand All @@ -151,7 +165,7 @@ export function replaceMarkdownLinks<T extends ContentPaths>({

brokenMarkdownLinks.push(brokenMarkdownLink);
}
mdMatch = mdRegex.exec(modifiedLine);
mdMatch = linkPattern.exec(modifiedLine);
}
return modifiedLine;
});
Expand Down
Loading