1
- import fallback from 'json-parse-even-better-errors' ;
2
1
import { codeFrameColumns } from '@babel/code-frame' ;
3
2
import indexToPosition from 'index-to-position' ;
4
3
4
+ const getCodePoint = character => `\\u{${ character . codePointAt ( 0 ) . toString ( 16 ) } }` ;
5
+
5
6
export class JSONError extends Error {
6
7
name = 'JSONError' ;
7
8
fileName ;
@@ -32,7 +33,7 @@ const generateCodeFrame = (string, location, highlightCode = true) =>
32
33
codeFrameColumns ( string , { start : location } , { highlightCode} ) ;
33
34
34
35
const getErrorLocation = ( string , message ) => {
35
- const match = message . match ( / i n J S O N a t p o s i t i o n (?< index > \d + ) (?: \( l i n e (?< line > \d + ) c o l u m n (?< column > \d + ) \) ) ? w h i l e p a r s i n g / ) ;
36
+ const match = message . match ( / i n J S O N a t p o s i t i o n (?< index > \d + ) (?: \( l i n e (?< line > \d + ) c o l u m n (?< column > \d + ) \) ) ? $ / ) ;
36
37
37
38
if ( ! match ) {
38
39
return ;
@@ -55,9 +56,15 @@ const getErrorLocation = (string, message) => {
55
56
return indexToPosition ( string , index , { oneBased : true } ) ;
56
57
} ;
57
58
58
- export default function parseJson ( string , reviver , filename ) {
59
+ const addCodePointToUnexpectedToken = message => message . replace (
60
+ // TODO[engine:node@>=20]: The token always quoted after Node.js 20
61
+ / (?< = ^ U n e x p e c t e d t o k e n ) (?< quote > ' ) ? ( .) \k<quote > / ,
62
+ ( _ , _quote , token ) => `"${ token } "(${ getCodePoint ( token ) } )` ,
63
+ ) ;
64
+
65
+ export default function parseJson ( string , reviver , fileName ) {
59
66
if ( typeof reviver === 'string' ) {
60
- filename = reviver ;
67
+ fileName = reviver ;
61
68
reviver = undefined ;
62
69
}
63
70
@@ -68,20 +75,18 @@ export default function parseJson(string, reviver, filename) {
68
75
message = error . message ;
69
76
}
70
77
71
- try {
72
- fallback ( string , reviver ) ;
73
- } catch ( error ) {
74
- message = error . message ;
78
+ let location ;
79
+ if ( string ) {
80
+ location = getErrorLocation ( string , message ) ;
81
+ message = addCodePointToUnexpectedToken ( message ) ;
82
+ } else {
83
+ message += ' while parsing empty string' ;
75
84
}
76
85
77
- message = message . replaceAll ( '\n' , '' ) ;
78
86
const jsonError = new JSONError ( message ) ;
79
87
80
- if ( filename ) {
81
- jsonError . fileName = filename ;
82
- }
88
+ jsonError . fileName = fileName ;
83
89
84
- const location = getErrorLocation ( string , message ) ;
85
90
if ( location ) {
86
91
jsonError . codeFrame = generateCodeFrame ( string , location ) ;
87
92
jsonError . rawCodeFrame = generateCodeFrame ( string , location , /* highlightCode */ false ) ;
0 commit comments