Skip to content

Commit

Permalink
Merge pull request #21 from jburianek/fix-escaping
Browse files Browse the repository at this point in the history
Fix escaping for Slack
  • Loading branch information
marissamarym authored Sep 24, 2023
2 parents 2d8fe99 + a3281ca commit 5dc0226
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,29 @@ export async function markdownToBlocks(
body: string,
options: ParsingOptions = {}
): Promise<KnownBlock[]> {
const tokens = marked.lexer(body);
// Slack only wants &, <, and > escaped
// https://api.slack.com/reference/surfaces/formatting#escaping
const replacements: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
};

const lexer = new marked.Lexer();
lexer.options.tokenizer = new marked.Tokenizer();
lexer.options.tokenizer.inlineText = src => {
const text = src.replace(/[&<>]/g, char => {
return replacements[char];
});

return {
type: 'text',
raw: src,
text: text,
};
};

const tokens = lexer.lex(body);

return parseBlocks(tokens, options);
}
6 changes: 6 additions & 0 deletions test/integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,10 @@ if (a === 'hi') {
expect(actual).toStrictEqual(expected);
});
});

it('should correctly escape text', async () => {
const actual = await markdownToBlocks('<>&\'""\'&><');
const expected = [slack.section('&lt;&gt;&amp;\'""\'&amp;&gt;&lt;')];
expect(actual).toStrictEqual(expected);
});
});

0 comments on commit 5dc0226

Please sign in to comment.