fix: Avoid O(n^2) masked source rebuild in inline tokenizer (#4017)

This commit is contained in:
Anh Hong
2026-07-14 21:05:11 -06:00
committed by GitHub
parent f945fc5e10
commit 9154f8f3cb
2 changed files with 23 additions and 16 deletions
+9 -16
View File
@@ -304,33 +304,26 @@ export class _Lexer<ParserOutput = string, RendererOutput = string> {
this.tokenizer.lexer = this;
// String with links masked to avoid interference with em and strong
let maskedSrc = src;
let match: RegExpExecArray | null = null;
// Mask out reflinks
if (this.tokens.links) {
const links = Object.keys(this.tokens.links);
if (links.length > 0) {
while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) !== null) {
if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
maskedSrc = maskedSrc.slice(0, match.index)
+ '[' + 'a'.repeat(match[0].length - 2) + ']'
+ maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
}
}
maskedSrc = maskedSrc.replace(this.tokenizer.rules.inline.reflinkSearch, match0 =>
links.includes(match0.slice(match0.lastIndexOf('[') + 1, -1))
? '[' + 'a'.repeat(match0.length - 2) + ']'
: match0);
}
}
// Mask out escaped characters
while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) !== null) {
maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
}
maskedSrc = maskedSrc.replace(this.tokenizer.rules.inline.anyPunctuation, '++');
// Mask out other blocks
let offset;
while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) !== null) {
offset = match[2] ? match[2].length : 0;
maskedSrc = maskedSrc.slice(0, match.index + offset) + '[' + 'a'.repeat(match[0].length - offset - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
}
maskedSrc = maskedSrc.replace(this.tokenizer.rules.inline.blockSkip, (match0, _link, context) => {
const offset = context ? context.length : 0;
return match0.slice(0, offset) + '[' + 'a'.repeat(match0.length - offset - 2) + ']';
});
// Mask out blocks from extensions
maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;
@@ -0,0 +1,14 @@
module.exports = [
{
markdown: '\\.'.repeat(100000),
html: `<p>${'.'.repeat(100000)}</p>`,
},
{
markdown: '`x` '.repeat(60000),
html: `<p>${'<code>x</code> '.repeat(60000)}</p>`,
},
{
markdown: '[a]: x\n\n' + '[a] '.repeat(100000),
html: `<p>${'<a href="x">a</a> '.repeat(100000)}</p>`,
},
];