1212// See the License for the specific language governing permissions and
1313// limitations under the License.
1414
15+ // Copyright 2025 Google LLC
16+ //
17+ // Licensed under the Apache License, Version 2.0 (the "License");
18+ // you may not use this file except in compliance with the License.
19+ // You may obtain a copy of the License at
20+ //
21+ // https://www.apache.org/licenses/LICENSE-2.0
22+ //
23+ // Unless required by applicable law or agreed to in writing, software
24+ // distributed under the License is distributed on an "AS IS" BASIS,
25+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26+ // See the License for the specific language governing permissions and
27+ // limitations under the License.
28+
1529import { type Buffer } from 'node:buffer'
1630import { bufToString } from './util.ts'
1731
@@ -25,38 +39,34 @@ export function transformMarkdown(buf: Buffer | string): string {
2539 let prevEmpty = true
2640
2741 let fenceChar = ''
28- let stripRe = / ^ /
42+ let stripRe : RegExp | null = null
2943 let endRe = / ^ $ /
3044 let linePrefix = ''
3145 let closeOut = ''
32- let closeBlank = false
3346
34- const isEnd = ( s : string ) => fenceChar && endRe . test ( s )
47+ const isEnd = ( s : string ) => fenceChar !== '' && endRe . test ( s )
3548
3649 for ( const line of bufToString ( buf ) . split ( / \r ? \n / ) ) {
3750 switch ( state ) {
3851 case 'root' : {
3952 const g = line . match ( fenceRe ) ?. groups
4053 if ( g ?. fence ) {
4154 fenceChar = g . fence [ 0 ]
42- stripRe = g . indent ? new RegExp ( `^ {0,${ g . indent . length } }` ) : / ^ /
55+ stripRe = g . indent ? new RegExp ( `^ {0,${ g . indent . length } }` ) : null
4356 endRe = new RegExp ( `^ {0,3}${ fenceChar } {${ g . fence . length } ,}[ \\t]*$` )
4457
4558 if ( g . js ) {
4659 out . push ( '' )
4760 linePrefix = ''
4861 closeOut = ''
49- closeBlank = true
5062 } else if ( g . bash ) {
5163 out . push ( 'await $`' )
5264 linePrefix = ''
5365 closeOut = '`'
54- closeBlank = false
5566 } else {
5667 out . push ( '' )
5768 linePrefix = '// '
5869 closeOut = ''
59- closeBlank = true
6070 }
6171
6272 state = 'fence'
@@ -87,12 +97,13 @@ export function transformMarkdown(buf: Buffer | string): string {
8797
8898 case 'fence' :
8999 if ( isEnd ( line ) ) {
90- if ( closeOut ) out . push ( closeOut )
91- else if ( closeBlank ) out . push ( '' )
100+ out . push ( closeOut )
92101 state = 'root'
93102 prevEmpty = true
103+ fenceChar = ''
94104 } else {
95- out . push ( linePrefix + line . replace ( stripRe , '' ) )
105+ const s = stripRe ? line . replace ( stripRe , '' ) : line
106+ out . push ( linePrefix + s )
96107 prevEmpty = false
97108 }
98109 break
0 commit comments