Skip to content

Commit

Permalink
Fix escaping for Slack
Browse files Browse the repository at this point in the history
  • Loading branch information
Joe Burianek committed Sep 8, 2023
1 parent 2d8fe99 commit a3281ca
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 a3281ca

Please sign in to comment.