From f08b17b72cb993037a0a1d8973165b8c02fad380 Mon Sep 17 00:00:00 2001 From: tsushanth Date: Mon, 20 Jul 2026 13:34:49 -0700 Subject: [PATCH] fix: use filter instead of splice-during-iteration for twoslash @link comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When multiple consecutive // @link comment lines appear in a twoslash code block, the previous loop used splice(i, 1) while iterating with .entries(). After each removal, subsequent elements shift down by one index, so the iterator skips the next element. This causes alternating @link lines to be silently ignored — neither removed from the rendered code nor registered in the linkMap. Replace the mutate-in-place loop with a single filter pass that collects links and strips comment lines in one traversal. --- .../rehype/rehypeSyntaxHighlighting.ts | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/packages/mdx/src/plugins/rehype/rehypeSyntaxHighlighting.ts b/packages/mdx/src/plugins/rehype/rehypeSyntaxHighlighting.ts index 87b3d57..d1c74f6 100644 --- a/packages/mdx/src/plugins/rehype/rehypeSyntaxHighlighting.ts +++ b/packages/mdx/src/plugins/rehype/rehypeSyntaxHighlighting.ts @@ -159,17 +159,15 @@ function traverseNode({ const linkMap = options.linkMap ?? new Map(); if (shouldUseTwoslash) { - const splitCode = code.split('\n'); - - for (const [i, line] of splitCode.entries()) { - const parsedLineComment = parseLineComment(line); - if (!parsedLineComment) continue; - const { word, href } = parsedLineComment; - linkMap.set(word, href); - splitCode.splice(i, 1); - } - - code = splitCode.join('\n'); + code = code + .split('\n') + .filter((line) => { + const parsedLineComment = parseLineComment(line); + if (!parsedLineComment) return true; + linkMap.set(parsedLineComment.word, parsedLineComment.href); + return false; + }) + .join('\n'); } const twoslashOptions = getTwoslashOptions({ linkMap });