1 | 'use strict';
|
---|
2 | const errorEx = require('error-ex');
|
---|
3 | const fallback = require('json-parse-even-better-errors');
|
---|
4 | const {default: LinesAndColumns} = require('lines-and-columns');
|
---|
5 | const {codeFrameColumns} = require('@babel/code-frame');
|
---|
6 |
|
---|
7 | const JSONError = errorEx('JSONError', {
|
---|
8 | fileName: errorEx.append('in %s'),
|
---|
9 | codeFrame: errorEx.append('\n\n%s\n')
|
---|
10 | });
|
---|
11 |
|
---|
12 | const parseJson = (string, reviver, filename) => {
|
---|
13 | if (typeof reviver === 'string') {
|
---|
14 | filename = reviver;
|
---|
15 | reviver = null;
|
---|
16 | }
|
---|
17 |
|
---|
18 | try {
|
---|
19 | try {
|
---|
20 | return JSON.parse(string, reviver);
|
---|
21 | } catch (error) {
|
---|
22 | fallback(string, reviver);
|
---|
23 | throw error;
|
---|
24 | }
|
---|
25 | } catch (error) {
|
---|
26 | error.message = error.message.replace(/\n/g, '');
|
---|
27 | const indexMatch = error.message.match(/in JSON at position (\d+) while parsing/);
|
---|
28 |
|
---|
29 | const jsonError = new JSONError(error);
|
---|
30 | if (filename) {
|
---|
31 | jsonError.fileName = filename;
|
---|
32 | }
|
---|
33 |
|
---|
34 | if (indexMatch && indexMatch.length > 0) {
|
---|
35 | const lines = new LinesAndColumns(string);
|
---|
36 | const index = Number(indexMatch[1]);
|
---|
37 | const location = lines.locationForIndex(index);
|
---|
38 |
|
---|
39 | const codeFrame = codeFrameColumns(
|
---|
40 | string,
|
---|
41 | {start: {line: location.line + 1, column: location.column + 1}},
|
---|
42 | {highlightCode: true}
|
---|
43 | );
|
---|
44 |
|
---|
45 | jsonError.codeFrame = codeFrame;
|
---|
46 | }
|
---|
47 |
|
---|
48 | throw jsonError;
|
---|
49 | }
|
---|
50 | };
|
---|
51 |
|
---|
52 | parseJson.JSONError = JSONError;
|
---|
53 |
|
---|
54 | module.exports = parseJson;
|
---|