Fix double-escaping of non-highlighted code blocks in Astro-flavored markdown (#4169)

This commit is contained in:
hippotastic 2022-08-05 16:23:16 +02:00 committed by GitHub
parent 9315ce65dd
commit 16034f0dd5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 6 deletions

View file

@ -0,0 +1,5 @@
---
'@astrojs/markdown-remark': patch
---
Fix double-escaping of non-highlighted code blocks in Astro-flavored markdown

View file

@ -1,4 +1,4 @@
import { visit } from 'unist-util-visit';
import { visit, SKIP } from 'unist-util-visit';
export function escapeEntities(value: string): string {
return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@ -14,8 +14,9 @@ export default function rehypeEscape(): any {
visit(el, 'raw', (raw) => {
raw.value = escapeEntities(raw.value);
});
// Do not visit children to prevent double escaping
return SKIP;
}
return el;
});
};
}

View file

@ -2,11 +2,25 @@ import { renderMarkdown } from '../dist/index.js';
import { expect } from 'chai';
describe('entities', () => {
const renderAstroMd = (text) => renderMarkdown(text, { isAstroFlavoredMd: false });
it('should not unescape entities', async () => {
const { code } = await renderAstroMd(`&lt;i&gt;This should NOT be italic&lt;/i&gt;`);
it('should not unescape entities in regular Markdown', async () => {
const { code } = await renderMarkdown(`&lt;i&gt;This should NOT be italic&lt;/i&gt;`, {
isAstroFlavoredMd: false,
});
expect(code).to.equal(`<p>&#x3C;i>This should NOT be italic&#x3C;/i></p>`);
});
it('should not escape entities in code blocks twice in Astro-flavored markdown', async () => {
const { code } = await renderMarkdown(
`\`\`\`astro\n<h1>{x && x.name || ''}!</h1>\n\`\`\``,
{
isAstroFlavoredMd: true,
syntaxHighlight: false,
}
);
expect(code).to.equal(
`<pre is:raw><code class="language-astro">&lt;h1&gt;{x &amp;&amp; x.name || ''}!&lt;/h1&gt;\n</code></pre>`
);
});
});