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

Encode ampersands in markdown code blocks #3630

Merged
merged 5 commits into from
Jun 20, 2022
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
5 changes: 5 additions & 0 deletions .changeset/pink-pugs-beg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/markdown-remark': patch
---

Encodes ampersand characters in code blocks
2 changes: 1 addition & 1 deletion packages/markdown/remark/src/rehype-escape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default function rehypeEscape(): any {
// Visit all raw children and escape HTML tags to prevent Markdown code
// like "This is a `<script>` tag" from actually opening a script tag
visit(el, 'raw', (raw) => {
raw.value = raw.value.replace(/</g, '&lt;').replace(/>/g, '&gt;');
raw.value = raw.value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
});
}
return el;
Expand Down
29 changes: 28 additions & 1 deletion packages/markdown/remark/test/expressions.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { renderMarkdown } from '../dist/index.js';
import chai from 'chai';
import chai, { expect } from 'chai';

describe('expressions', () => {
it('should be able to serialize bare expression', async () => {
Expand Down Expand Up @@ -71,6 +71,33 @@ describe('expressions', () => {
);
});

it('should be able to encode ampersand characters in code blocks', async () => {
const { code } = await renderMarkdown(
'The ampersand in `&nbsp;` must be encoded in code blocks.',
{}
);

chai
.expect(code)
.to.equal(
'<p>The ampersand in <code is:raw>&amp;nbsp;</code> must be encoded in code blocks.</p>'
)
});

it('should be able to encode ampersand characters in fenced code blocks', async () => {
const { code } = await renderMarkdown(`
\`\`\`md
The ampersand in \`&nbsp;\` must be encoded in code blocks.
\`\`\`
`);

chai
.expect(code)
.to.match(
/^<pre is:raw.*<code>.*The ampersand in `&amp;nbsp;`/
);
})

it('should be able to serialize function expression', async () => {
const { code } = await renderMarkdown(
`{frontmatter.list.map(item => <p id={item}>{item}</p>)}`,
Expand Down