UNPKG

1.9 kBJavaScriptView Raw
1"use strict";
2
3var ToloframeworkPermissiveJson = require("toloframework-permissive-json");
4
5
6module.exports = function( xjsFileContent ) {
7 try {
8 return ToloframeworkPermissiveJson.parse( xjsFileContent );
9 }
10 catch( ex ) {
11 throw "Invalid permissive JSON syntax:\n" + ex.message + "\n\n"
12 + getFewLinesOfCode( xjsFileContent, ex.index, 3 );
13 }
14}
15
16function getFewLinesOfCode( code, issuePosition, linesToDisplay ) {
17 if( typeof issuePosition === 'undefined' ) issuePosition = 0;
18 if( typeof linesToDisplay === 'undefined' ) linesToDisplay = 3;
19
20 var lineCount = 1;
21 var currentIndex = 0;
22 var previousIndex = 0;
23 var lines = [];
24 issuePosition = Math.min( issuePosition, code.length -1 );
25 while( currentIndex < code.length ) {
26 if( code.charAt( currentIndex ) === '\n' ) {
27 lines.push({ line: lineCount, begin: previousIndex, end: currentIndex });
28 if( lines.length > linesToDisplay )
29 lines.shift();
30 previousIndex = currentIndex + 1;
31 lineCount++;
32 if( currentIndex >= issuePosition ) break;
33 }
34 currentIndex++;
35 }
36
37 var columnsSeparator = ": ";
38 var lineNumbersLengths = lines.map(x => ("" + x.line).length);
39 var spaceForLineNumbers = lineNumbersLengths.reduce((a,v) => Math.max(a, v), 0);
40 var output = lines.map(
41 x => padStart(x.line, spaceForLineNumbers)
42 + columnsSeparator + code.substring(x.begin, x.end) ).join("\n");
43 var lastLineBegin = lines.length > 0 ? lines.pop().begin : code.length;
44 output += "\n" + padStart("^",
45 spaceForLineNumbers + columnsSeparator.length + issuePosition - lastLineBegin - 1);
46 return output;
47}
48
49function padStart( text, targetLength, padString ) {
50 if( typeof padString === 'undefined' ) padString = ' ';
51 text = "" + text;
52 while( text.length < targetLength )
53 text = padString + text;
54 return text;
55}
56