@@ -44,11 +44,16 @@ export const parser = (html: string, options: Options = {}): Node[] => {
4444 const locationTracker = new LocationTracker ( html ) ;
4545 const bufArray : Node [ ] = [ ] ;
4646 const results : Node [ ] = [ ] ;
47+ let lastIndices : [ number , number ] ;
4748
48- function bufferArrayLast ( ) : Node {
49+ function bufferArrayLast ( ) : Node | undefined {
4950 return bufArray [ bufArray . length - 1 ] ;
5051 }
5152
53+ function resultsLast ( ) : Node | undefined {
54+ return results [ results . length - 1 ] ;
55+ }
56+
5257 function isDirective ( directive : Directive , tag : string ) : boolean {
5358 if ( directive . name instanceof RegExp ) {
5459 const regex = new RegExp ( directive . name . source , 'i' ) ;
@@ -122,10 +127,20 @@ export const parser = (html: string, options: Options = {}): Node[] => {
122127 }
123128
124129 function onopentag ( tag : string , attrs : Attributes ) {
125- const start = locationTracker . getPosition ( parser . startIndex ) ;
126130 const buf : NodeTag = { tag } ;
127131
128132 if ( options . sourceLocations ) {
133+ if ( lastIndices ?. [ 0 ] === parser . startIndex && lastIndices ?. [ 1 ] === parser . endIndex ) {
134+ // The last closing tag was inferred, so we need to update its end location
135+ const last = bufferArrayLast ( ) || resultsLast ( ) ;
136+
137+ if ( typeof last === 'object' && Array . isArray ( last . content ) && last . location ) {
138+ last . location . end = locationTracker . getPosition ( parser . startIndex - 1 )
139+ }
140+ }
141+
142+ const start = locationTracker . getPosition ( parser . startIndex ) ;
143+
129144 buf . location = {
130145 start,
131146 end : start
@@ -142,8 +157,9 @@ export const parser = (html: string, options: Options = {}): Node[] => {
142157 function onclosetag ( ) {
143158 const buf : Node | undefined = bufArray . pop ( ) ;
144159
145- if ( buf && typeof buf === 'object' && buf . location && parser . endIndex !== null ) {
146- buf . location . end = locationTracker . getPosition ( ( ! parser . tagname || parser . tagname === buf . tag ) ? parser . endIndex : parser . startIndex - 1 ) ;
160+ if ( buf && typeof buf === 'object' && buf . location && buf . location . end === buf . location . start && parser . endIndex !== null ) {
161+ lastIndices = [ parser . startIndex , parser . endIndex ] ;
162+ buf . location . end = locationTracker . getPosition ( parser . endIndex ) ;
147163 }
148164
149165 if ( buf ) {
@@ -167,7 +183,7 @@ export const parser = (html: string, options: Options = {}): Node[] => {
167183 }
168184
169185 function ontext ( text : string ) {
170- const last : Node = bufferArrayLast ( ) ;
186+ const last = bufferArrayLast ( ) ;
171187
172188 if ( last === undefined ) {
173189 results . push ( text ) ;
0 commit comments