printLocation.js 2.3 KB

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