@graphql-tools/graphql
Version:
Fork of GraphQL.js
57 lines (56 loc) • 2.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.printSourceLocation = exports.printLocation = void 0;
const location_js_1 = require("./location.js");
/**
* Render a helpful description of the location in the GraphQL Source document.
*/
function printLocation(location) {
return printSourceLocation(location.source, (0, location_js_1.getLocation)(location.source, location.start));
}
exports.printLocation = printLocation;
/**
* Render a helpful description of the location in the GraphQL Source document.
*/
function printSourceLocation(source, sourceLocation) {
const firstLineColumnOffset = source.locationOffset.column - 1;
const body = ''.padStart(firstLineColumnOffset) + source.body;
const lineIndex = sourceLocation.line - 1;
const lineOffset = source.locationOffset.line - 1;
const lineNum = sourceLocation.line + lineOffset;
const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
const columnNum = sourceLocation.column + columnOffset;
const locationStr = `${source.name}:${lineNum}:${columnNum}\n`;
const lines = body.split(/\r\n|[\n\r]/g);
const locationLine = lines[lineIndex];
// Special case for minified documents
if (locationLine.length > 120) {
const subLineIndex = Math.floor(columnNum / 80);
const subLineColumnNum = columnNum % 80;
const subLines = [];
for (let i = 0; i < locationLine.length; i += 80) {
subLines.push(locationLine.slice(i, i + 80));
}
return (locationStr +
printPrefixedLines([
[`${lineNum} |`, subLines[0]],
...subLines.slice(1, subLineIndex + 1).map(subLine => ['|', subLine]),
['|', '^'.padStart(subLineColumnNum)],
['|', subLines[subLineIndex + 1]],
]));
}
return (locationStr +
printPrefixedLines([
// Lines specified like this: ["prefix", "string"],
[`${lineNum - 1} |`, lines[lineIndex - 1]],
[`${lineNum} |`, locationLine],
['|', '^'.padStart(columnNum)],
[`${lineNum + 1} |`, lines[lineIndex + 1]],
]));
}
exports.printSourceLocation = printSourceLocation;
function printPrefixedLines(lines) {
const existingLines = lines.filter(([_, line]) => line !== undefined);
const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));
return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : '')).join('\n');
}