UNPKG

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