11import { codeFrameColumns } from '@babel/code-frame' ;
22import * as babelParser from '@babel/parser' ;
3+ import { LinesAndColumns } from 'lines-and-columns' ;
34import { wrap } from 'jest-snapshot-serializer-raw' ;
45
56const babelParserOptions : babelParser . ParserOptions = {
67 plugins : [
78 'typescript' , // NonNullAssert
89 ] ,
10+ ranges : true ,
911} ;
1012
1113export function parseBabelExpression ( input : string ) {
1214 return babelParser . parseExpression ( input , babelParserOptions ) ;
1315}
1416
1517export function parseBabel ( input : string ) {
16- return babelParser . parse ( input , babelParserOptions ) ;
18+ const ast = babelParser . parse ( input , babelParserOptions ) ;
19+ // https://github.com/babel/babel/issues/15115
20+ for ( const comment of ast . comments ! ) {
21+ // @ts -expect-error -- missing types
22+ comment . range ??= [ comment . start , comment . end ] ;
23+ }
24+ return ast ;
1725}
1826
1927export function massageAst ( ast : any ) : any {
@@ -35,18 +43,13 @@ export function massageAst(ast: any): any {
3543 delete ast . method ;
3644 }
3745
46+ delete ast . loc ;
47+
3848 const massaged = Object . keys ( ast ) . reduce ( ( reduced : any , key ) => {
3949 switch ( key ) {
4050 case 'trailingComments' :
4151 // do nothing
4252 break ;
43- case 'loc' : {
44- const loc = massageAst ( ast [ key ] ) ;
45- delete loc . filename ;
46- delete loc . identifierName ;
47- reduced [ key ] = loc ;
48- break ;
49- }
5053 case 'extra' : {
5154 const extra = massageAst ( ast [ key ] ) ;
5255 if ( extra ) {
@@ -75,12 +78,13 @@ export function massageAst(ast: any): any {
7578export function snapshotAst ( ast : any , source : string ) {
7679 const snapshots : string [ ] = [ ] ;
7780 const isNode = ( x : any ) => x && x . type ;
81+ const linesAndColumns = new LinesAndColumns ( source ) ;
7882 visitAst ( ast , ( node ) => {
7983 const props = Object . keys ( node ) . reduce ( ( reduced : any , key ) => {
8084 const value = node [ key ] ;
8185 switch ( key ) {
8286 case 'type' :
83- case 'loc ' :
87+ case 'range ' :
8488 case 'start' :
8589 case 'end' :
8690 break ;
@@ -96,13 +100,13 @@ export function snapshotAst(ast: any, source: string) {
96100 return reduced ;
97101 } , { } ) ;
98102 const fixColumn = ( p : { line : number ; column : number } ) => ( {
99- line : p . line ,
103+ line : p . line + 1 ,
100104 column : p . column + 1 ,
101105 } ) ;
102- const codeFrame = codeFrameColumns ( source , {
103- start : fixColumn ( node . loc . start ) ,
104- end : fixColumn ( node . loc . end ) ,
105- } ) ;
106+ const [ start , end ] = [ node . start , node . end ] . map ( ( index ) =>
107+ fixColumn ( linesAndColumns . locationForIndex ( index ) ! ) ,
108+ ) ;
109+ const codeFrame = codeFrameColumns ( source , { start , end } ) ;
106110 const propsString = JSON . stringify ( props , undefined , 2 ) ;
107111 snapshots . push ( `${ node . type } ${ propsString } \n${ codeFrame } ` ) ;
108112 } ) ;
0 commit comments