11import { ILoader } from "../_types" ;
22import { createLoader } from "../_utils" ;
3- import { PlaceholderedMdx , RawMdx } from "./_types" ;
43import { md5 } from "../../utils/md5" ;
5- import { unified } from "unified" ;
6- import remarkParse from "remark-parse" ;
7- import remarkGfm from "remark-gfm" ;
8- import { VFile } from "vfile" ;
9- import remarkMdx from "remark-mdx" ;
4+ import _ from "lodash" ;
105
11- function parseMdast ( content : string ) {
12- const file = new VFile ( content ) ;
6+ const unindentedFenceRegex = / (?< ! \n \n ) ` ` ` ( [ \s \S ] * ? ) ` ` ` (? ! \n \n ) / g ;
7+ const indentedFenceRegex = / ` ` ` ( [ \s \S ] * ? ) ` ` ` / g ;
138
14- const parser = unified ( ) . use ( remarkParse ) . use ( remarkGfm ) . use ( remarkMdx ) ;
9+ function ensureTrailingFenceNewline ( _content : string ) {
10+ let found = false ;
11+ let content = _content ;
1512
16- const result = parser . parse ( file ) ;
13+ do {
14+ found = false ;
15+ const matches = content . match ( unindentedFenceRegex ) ;
16+ if ( matches ) {
17+ const match = matches [ 0 ] ;
18+ content = content . replace ( match , `\n\n${ match } \n\n` ) ;
19+ found = true ;
20+ }
21+ } while ( found ) ;
1722
18- return result ;
23+ content = _ . chain ( content ) . split ( "\n\n" ) . filter ( Boolean ) . join ( "\n\n" ) . value ( ) ;
24+
25+ return content ;
1926}
2027
2128// Helper that replaces code (block & inline) with stable placeholders and returns
@@ -27,10 +34,11 @@ function extractCodePlaceholders(content: string): {
2734 codePlaceholders : Record < string , string > ;
2835} {
2936 let finalContent = content ;
37+ finalContent = ensureTrailingFenceNewline ( finalContent ) ;
38+
3039 const codePlaceholders : Record < string , string > = { } ;
3140
32- const codeBlockRegex = / ^ ` ` ` .* \n ( [ \s \S ] * ?) ^ ` ` ` $ / gm;
33- const codeBlockMatches = finalContent . matchAll ( codeBlockRegex ) ;
41+ const codeBlockMatches = finalContent . matchAll ( indentedFenceRegex ) ;
3442
3543 for ( const match of codeBlockMatches ) {
3644 const codeBlock = match [ 0 ] ;
0 commit comments