UNPKG

@stryke/json

Version:

A package containing JSON parsing/stringify utilities used by Storm Software.

78 lines (76 loc) 2.5 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); //#region src/utils/code-frames.ts /** * RegExp to test for newlines in terminal. */ const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; /** * Extract what lines should be marked and highlighted. */ function getMarkerLines(loc, source, opts = {}) { const startLoc = { column: 0, line: -1, ...loc.start }; const endLoc = { ...startLoc, ...loc.end }; const { linesAbove = 2, linesBelow = 3 } = opts || {}; const startLine = startLoc.line; const startColumn = startLoc.column; const endLine = endLoc.line; const endColumn = endLoc.column; let start = Math.max(startLine - (linesAbove + 1), 0); let end = Math.min(source.length, endLine + linesBelow); if (startLine === -1) start = 0; if (endLine === -1) end = source.length; const lineDiff = endLine - startLine; const markerLines = {}; if (lineDiff) for (let i = 0; i <= lineDiff; i++) { const lineNumber = i + startLine; if (!startColumn) markerLines[lineNumber] = true; else if (i === 0) markerLines[lineNumber] = [startColumn, (source[lineNumber - 1]?.length ?? 0) - startColumn + 1]; else if (i === lineDiff) markerLines[lineNumber] = [0, endColumn]; else markerLines[lineNumber] = [0, source[lineNumber - i]?.length ?? 0]; } else if (startColumn === endColumn) markerLines[startLine] = startColumn ? [startColumn, 0] : true; else markerLines[startLine] = [startColumn, endColumn - startColumn]; return { start, end, markerLines }; } function codeFrameColumns(rawLines, loc, opts = {}) { const { start, end, markerLines } = getMarkerLines(loc, rawLines.split(NEWLINE), opts); const numberMaxWidth = String(end).length; return (opts.highlight ? opts.highlight(rawLines) : rawLines).split(NEWLINE).slice(start, end).map((line, index) => { const number = start + 1 + index; const gutter = ` ${` ${number}`.slice(-numberMaxWidth)} | `; const hasMarker = Boolean(markerLines[number] ?? false); if (hasMarker) { let markerLine = ""; if (Array.isArray(hasMarker)) { const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); const numberOfMarkers = hasMarker[1] || 1; markerLine = [ "\n ", gutter.replace(/\d/g, " "), markerSpacing, "^".repeat(numberOfMarkers) ].join(""); } return [ ">", gutter, line, markerLine ].join(""); } return ` ${gutter}${line}`; }).join("\n"); } //#endregion exports.codeFrameColumns = codeFrameColumns;