UNPKG

2.65 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.printLocation = printLocation;
7exports.printSourceLocation = printSourceLocation;
8
9var _location = require("./location.js");
10
11/**
12 * Render a helpful description of the location in the GraphQL Source document.
13 */
14function printLocation(location) {
15 return printSourceLocation(location.source, (0, _location.getLocation)(location.source, location.start));
16}
17/**
18 * Render a helpful description of the location in the GraphQL Source document.
19 */
20
21
22function printSourceLocation(source, sourceLocation) {
23 var firstLineColumnOffset = source.locationOffset.column - 1;
24 var body = whitespace(firstLineColumnOffset) + source.body;
25 var lineIndex = sourceLocation.line - 1;
26 var lineOffset = source.locationOffset.line - 1;
27 var lineNum = sourceLocation.line + lineOffset;
28 var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
29 var columnNum = sourceLocation.column + columnOffset;
30 var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");
31 var lines = body.split(/\r\n|[\n\r]/g);
32 var locationLine = lines[lineIndex]; // Special case for minified documents
33
34 if (locationLine.length > 120) {
35 var subLineIndex = Math.floor(columnNum / 80);
36 var subLineColumnNum = columnNum % 80;
37 var subLines = [];
38
39 for (var i = 0; i < locationLine.length; i += 80) {
40 subLines.push(locationLine.slice(i, i + 80));
41 }
42
43 return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) {
44 return ['', subLine];
45 }), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]]));
46 }
47
48 return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"],
49 ["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]);
50}
51
52function printPrefixedLines(lines) {
53 var existingLines = lines.filter(function (_ref) {
54 var _ = _ref[0],
55 line = _ref[1];
56 return line !== undefined;
57 });
58 var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {
59 var prefix = _ref2[0];
60 return prefix.length;
61 }));
62 return existingLines.map(function (_ref3) {
63 var prefix = _ref3[0],
64 line = _ref3[1];
65 return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |');
66 }).join('\n');
67}
68
69function whitespace(len) {
70 return Array(len + 1).join(' ');
71}
72
73function leftPad(len, str) {
74 return whitespace(len - str.length) + str;
75}