All files location.ts

95.83% Statements 92/96
85% Branches 34/40
100% Functions 10/10
97.8% Lines 89/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229                                  54x 54x 54x   54x           936x     936x     936x 3794924x 79016x     936x 936x       920x 920x       212092x 212092x   212092x 2992167x   2992167x 1540879x   1451288x       212092x       106148x 106148x   106148x   252x       105896x 105896x   105896x   105896x     28x 92x     28x     105896x   105896x             105896x 5591x   100305x 100305x   100305x 100305x 100305x 100305x         105896x 105896x   105896x 912x 912x   912x       105896x 18x     105878x       48x 48x   48x   48x       48x   48x     48x   48x         212136x   212136x 523x             212136x 344x     211792x               804x     804x 4280x 4280x 4280x   4280x 48536x 48536x     4280x     804x                     796x 796x   796x   8x 8x 4x 4x 4x     4x 4x 4x             28x 28x   28x      
import { readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import {
  allGeneratedPositionsFor,
  LEAST_UPPER_BOUND,
  originalPositionFor,
  type TraceMap,
  type Needle,
  type SourceMapSegment,
  type DecodedSourceMap,
  type SourceMap,
  sourceContentFor,
} from "@jridgewell/trace-mapping";
import { type Node } from "estree";
import { getIgnoredLines } from "./ignore-hints";
 
const WORD_PATTERN = /(\w+|\s|[^\w\s])/g;
const INLINE_MAP_PATTERN = /#\s*sourceMappingURL=(.*)\s*$/m;
const BASE_64_PREFIX = "data:application/json;base64,";
 
const NEW_LINE_CHAR_CODE = "\n".charCodeAt(0);
 
type Filename = string;
 
export class Locator {
  /** Offsets of each line's first character */
  #lineStarts: number[] = [0];
  #map: TraceMap;
  #directory: string;
  #ignoredLines = new Map<Filename, ReturnType<typeof getIgnoredLines>>();
 
  constructor(code: string, map: TraceMap, directory: string) {
    for (let offset = 0; offset < code.length; offset++) {
      if (code.charCodeAt(offset) === NEW_LINE_CHAR_CODE) {
        this.#lineStarts.push(offset + 1);
      }
    }
    this.#map = map;
    this.#directory = directory;
  }
 
  reset() {
    this.#ignoredLines.clear();
    this.#lineStarts = [0];
  }
 
  offsetToNeedle(offset: number): Needle {
    let low = 0;
    let high = this.#lineStarts.length - 1;
 
    while (low <= high) {
      const mid = (low + high) >> 1;
 
      if (this.#lineStarts[mid] <= offset) {
        low = mid + 1;
      } else {
        high = mid - 1;
      }
    }
 
    return { line: high + 1, column: offset - this.#lineStarts[high] };
  }
 
  getLoc(node: Pick<Node, "start" | "end">) {
    const startNeedle = this.offsetToNeedle(node.start);
    const start = getPosition(startNeedle, this.#map);
 
    if (start === null) {
      // Does not exist in source maps, e.g. generated code
      return null;
    }
 
    // End-mapping tracing logic from istanbul-lib-source-maps
    const endNeedle = this.offsetToNeedle(node.end);
    endNeedle.column -= 1;
 
    let end = getPosition(endNeedle, this.#map);
 
    if (end === null) {
      // search the previous lines as the mapping was not found on the same line
      // e.g. tsc that doesnt include } in source maps
      for (let line = endNeedle.line; line >= startNeedle.line && end === null; line--) {
        end = getPosition({ line, column: Infinity }, this.#map);
      }
      // Does not exist in source maps, e.g. generated code
      Iif (end === null) return null;
    }
 
    const loc = { start, end };
 
    const afterEndMappings = allGeneratedPositionsFor(this.#map, {
      source: loc.end.filename,
      line: loc.end.line,
      column: loc.end.column + 1,
      bias: LEAST_UPPER_BOUND,
    });
 
    if (afterEndMappings.length === 0) {
      loc.end.column = Infinity;
    } else {
      for (const mapping of afterEndMappings) {
        Iif (mapping.line === null) continue;
 
        const original = originalPositionFor(this.#map, mapping);
        Eif (original.line === loc.end.line) {
          loc.end = { ...original, filename: original.source! };
          break;
        }
      }
    }
 
    const filename = loc.start.filename;
    let ignoredLines = this.#ignoredLines.get(filename);
 
    if (!ignoredLines) {
      const sources = sourceContentFor(this.#map, filename);
      ignoredLines = getIgnoredLines(sources ?? tryReadFileSync(filename));
 
      this.#ignoredLines.set(filename, ignoredLines);
    }
 
    // Anything that starts between the line ignore hints is ignored
    if (ignoredLines.has(loc.start.line)) {
      return null;
    }
 
    return loc;
  }
 
  getSourceLines(loc: { start: Needle; end: Needle }, filename: string) {
    const index = this.#map.resolvedSources.findIndex(
      (source) => source === filename || resolve(this.#directory, source) === filename,
    );
    const sourcesContent = this.#map.sourcesContent?.[index];
 
    Iif (sourcesContent == null) {
      return null;
    }
 
    const lines = sourcesContent.split("\n").slice(loc.start.line - 1, loc.end.line);
 
    lines[0] = lines[0].slice(loc.start.column);
 
    // eslint-disable-next-line e18e/prefer-array-at -- https://github.com/e18e/eslint-plugin/issues/27
    lines[lines.length - 1] = lines[lines.length - 1].slice(0, loc.end.column);
 
    return lines.join("\n");
  }
}
 
function getPosition(needle: Needle, map: TraceMap) {
  let position = originalPositionFor(map, needle);
 
  if (position.source == null) {
    position = originalPositionFor(map, {
      column: needle.column,
      line: needle.line,
      bias: LEAST_UPPER_BOUND,
    });
  }
 
  if (position.source == null) {
    return null;
  }
 
  return {
    line: position.line,
    column: position.column,
    filename: position.source,
  };
}
 
export function createEmptySourceMap(filename: string, code: string): DecodedSourceMap {
  const mappings: SourceMapSegment[][] = [];
 
  // Identical mappings as "magic-string"'s { hires: "boundary" }
  for (const [line, content] of code.split("\n").entries()) {
    const parts = content.match(WORD_PATTERN) || [];
    const segments: SourceMapSegment[] = [];
    let column = 0;
 
    for (const part of parts) {
      segments.push([column, 0, line, column]);
      column += part.length;
    }
 
    mappings.push(segments);
  }
 
  return {
    version: 3,
    mappings,
    file: filename,
    sources: [filename],
    sourcesContent: [code],
    names: [],
  };
}
 
export async function getInlineSourceMap(filename: string, code: string) {
  const matches = code.match(INLINE_MAP_PATTERN);
  const match = matches?.[1];
 
  if (!match) return null;
 
  try {
    if (match.includes(BASE_64_PREFIX)) {
      const encoded = match.split(BASE_64_PREFIX).at(-1) || "";
      const decoded = atob(encoded);
      return JSON.parse(decoded) as SourceMap;
    }
 
    const directory = dirname(filename);
    const content = await readFile(resolve(directory, match), "utf-8");
    return JSON.parse(content) as SourceMap;
  } catch {
    return null;
  }
}
 
function tryReadFileSync(filename: string) {
  try {
    return readFileSync(filename, "utf8");
  } catch {
    return undefined;
  }
}