Skip to content

Commit 4fa1608

Browse files
committed
fix(markdown): respect escape parity when repairing file links
1 parent b83d9a8 commit 4fa1608

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

‎packages/client-runtime/src/repairMarkdownFileLinks.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,25 @@ describe("repairMarkdownFileLinks", () => {
3232
).toBe("Files:\n\n- [**one**](<./one.md>)\n- [two](<./two.md>)\n\nDone.");
3333
});
3434

35+
it.each([
36+
["", true],
37+
["\\", false],
38+
["\\\\", true],
39+
["\\\\\\", false],
40+
["!", false],
41+
["\\!", true],
42+
["\\\\!", false],
43+
["\\\\\\!", true],
44+
])("respects CommonMark escape parity after %j", (prefix, isLink) => {
45+
const source = `${prefix}[file](<./file.md)`;
46+
const repaired = repairMarkdownFileLinks(source);
47+
expect(repaired).toBe(isLink ? `${prefix}[file](<./file.md>)` : source);
48+
const paragraph = unified().use(remarkParse).parse(repaired).children[0];
49+
expect(
50+
paragraph?.type === "paragraph" && paragraph.children.some((node) => node.type === "link"),
51+
).toBe(isLink);
52+
});
53+
3554
it.each([
3655
"[file](<local/path/file.md>)",
3756
"[file](local/path/file.md)",

‎packages/client-runtime/src/repairMarkdownFileLinks.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,19 @@ const UNCLOSED_FILE_LINK = /\[[^[\]\\\r\n]*\]\([ \t]*<([^<>()[\]\r\n"']+)\)/g;
1212
export function repairMarkdownFileLinks(markdown: string): string {
1313
if (!markdown.includes("](")) return markdown;
1414

15+
function isEscaped(index: number): boolean {
16+
let start = index;
17+
while (markdown[start - 1] === "\\") start -= 1;
18+
return (index - start) % 2 === 1;
19+
}
20+
1521
const matches = Array.from(markdown.matchAll(UNCLOSED_FILE_LINK)).filter((match) => {
1622
const previous = markdown[match.index - 1];
17-
return previous !== "!" && previous !== "\\" && parseMarkdownFileLink(match[1] ?? "");
23+
return (
24+
!isEscaped(match.index) &&
25+
(previous !== "!" || isEscaped(match.index - 1)) &&
26+
parseMarkdownFileLink(match[1] ?? "")
27+
);
1828
});
1929
if (matches.length === 0) return markdown;
2030

0 commit comments

Comments
 (0)