Skip to content

Commit

Permalink
fix(core): escape all angle brackets with "santizeComments" (#612)
Browse files Browse the repository at this point in the history
  • Loading branch information
tgreyuk committed May 11, 2024
1 parent 5b412fb commit 91978aa
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { sanitizeComments } from './sanitize-comments';

describe('sanitizeComments', () => {
it('should escape special characters correctly', () => {
const input = 'Comments <tag></tag>, {braces}, >= 5, < 5, `code`';
const output =
'Comments \\<tag\\>\\</tag\\>, \\{braces\\}, \\>= 5, \\< 5, `code`';
const result = sanitizeComments(input);
expect(result).toEqual(output);
});

it('should not escape blockquotes', () => {
const input = '> Blockquote with <tag>';
const output = '> Blockquote with \\<tag\\>';
const result = sanitizeComments(input);
expect(result).toEqual(output);
});

it('should not escape inline code', () => {
const input = 'Comment with <tag> `code with <tag> and {braces}`';
const output = 'Comment with \\<tag\\> `code with <tag> and {braces}`';
const result = sanitizeComments(input);
expect(result).toEqual(output);
});

it('should not escape code block', () => {
const input = `
<tag>
\`\`\`html
<div>x</div>
\`\`\``;
const expectedOutput = `
\\<tag\\>
\`\`\`html
<div>x</div>
\`\`\``;
const result = sanitizeComments(input);
expect(result).toEqual(expectedOutput);
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
export function sanitizeComments(str: string) {
const re = /<(?=(?:[^`]*`[^`]*`)*[^`]*$)[^<]+?>/gi;
const codeBlocks: string[] = [];
const placeholder = '___CODEBLOCKPLACEHOLDER___';

Expand All @@ -9,9 +8,11 @@ export function sanitizeComments(str: string) {
return placeholder;
});

// Perform escaping outside of code blocks
// If line starts with a > treat it as a blockquote
// Otherwise escape all <, >, {, and } characters
str = str
.replace(re, (tags) => tags.replace(/>/g, '\\>').replace(/</g, '\\<'))
.replace(/(?!^)>/gm, '\\>')
.replace(/</g, '\\<')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}');

Expand Down

0 comments on commit 91978aa

Please sign in to comment.