@@ -104,23 +104,43 @@ function get_comment_handlers(source) {
104
104
next ( ) ;
105
105
106
106
if ( comments [ 0 ] ) {
107
- const parent = path . at ( - 1 ) ;
107
+ const parent = /** @type { any } */ ( path . at ( - 1 ) ) ;
108
108
109
109
if ( parent === undefined || node . end !== parent . end ) {
110
110
const slice = source . slice ( node . end , comments [ 0 ] . start ) ;
111
-
112
- if ( node . end <= comments [ 0 ] . start && / ^ [ , ) \t ] * $ / . test ( slice ) ) {
111
+ const is_last_in_body =
112
+ // BlockStatement and Program nodes have a body property
113
+ parent ?. body ?. length &&
114
+ Array . isArray ( parent ?. body ) &&
115
+ parent . body . indexOf ( node ) === parent . body . length - 1 ;
116
+
117
+ if ( is_last_in_body ) {
118
+ // Special case: There can be multiple trailing comments after the last node in a block,
119
+ // and they can be separated by newlines
120
+ let end = node . end ;
121
+
122
+ while ( comments . length ) {
123
+ const comment = comments [ 0 ] ;
124
+ if ( parent && comment . start > parent . end ) break ;
125
+
126
+ const slice = source . slice ( end , comment . start ) ;
127
+ if ( node . end === end ? ! / ^ [ , ) \s ] * $ / . test ( slice ) : slice . trim ( ) !== '' ) break ;
128
+
129
+ ( node . trailingComments ||= [ ] ) . push ( comment ) ;
130
+ comments . shift ( ) ;
131
+ end = comment . end ;
132
+ }
133
+ } else if ( node . end <= comments [ 0 ] . start && / ^ [ , ) \t ] * $ / . test ( slice ) ) {
113
134
node . trailingComments = [ /** @type {CommentWithLocation } */ ( comments . shift ( ) ) ] ;
114
135
}
115
136
}
116
137
}
117
138
}
118
139
} ) ;
119
140
120
- // Special case: Trailing comments after the root node (which can only happen for expression tags) get added
121
- // regardless of line breaks between the root node and the comments. This ensures that we can later detect
122
- // the end of the expression tag correctly.
123
- if ( comments . length > 0 && comments [ 0 ] . start >= ast . end ) {
141
+ // Special case: Trailing comments after the root node (which can only happen for expression tags or for Program nodes).
142
+ // Adding them ensures that we can later detect the end of the expression tag correctly.
143
+ if ( comments . length > 0 && ( comments [ 0 ] . start >= ast . end || ast . type === 'Program' ) ) {
124
144
( ast . trailingComments ||= [ ] ) . push ( ...comments . splice ( 0 ) ) ;
125
145
}
126
146
}
0 commit comments