All files coverage-mapper.ts

91.46% Statements 75/82
83.33% Branches 60/72
100% Functions 8/8
93.58% Lines 73/78

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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266                                            908x 908x 908x 908x 908x 908x 908x 908x             908x 908x   908x           908x                                     5826x       5826x 5826x   5754x 5754x   5754x               5754x 16x 16x   16x             4x       5750x                     41307x 8x     41299x 41299x   41065x               41307x 32x 32x   32x             4x       41061x                 20254x 4x     20250x 20250x   20250x 20250x   20250x 43769x 11378x         11378x             11378x 11378x   11378x     32391x 32391x 32391x     32391x   43769x                     20250x 12909x 12872x       20250x 41x     20209x                           20209x                     908x 908x             67068x   67068x       67068x 8x     67060x       67387x 67311x     76x   76x 8x     76x      
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { TraceMap } from "@jridgewell/trace-mapping";
import { type Node } from "estree";
 
import { type FunctionNodes, getFunctionName, type getWalker } from "./ast";
import {
  addBranch,
  addFunction,
  addStatement,
  type Branch,
  type CoverageMapData,
  createCoverageMapData,
} from "./coverage-map";
import { createEmptySourceMap, getInlineSourceMap, Locator } from "./location";
import { getCount, normalize } from "./script-coverage";
import type { Options } from "./types";
 
type Normalized = ReturnType<typeof normalize>;
 
export class CoverageMapper<T = Node> {
  private constructor(
    private locator: Locator,
    private coverageMapData: CoverageMapData,
    private ranges: Normalized,
    private wrapperLength: number,
    private directory: string,
    private onIgnoreNode: ReturnType<typeof getWalker>["onIgnore"],
    private ignoreNode?: Options<T>["ignoreNode"],
    private ignoreSourceCode?: Options<T>["ignoreSourceCode"],
  ) {}
 
  static async create<T = Node, Program = T & { type: "Program" }>(
    options: Options<T, Program>,
    onIgnoreNode: ReturnType<typeof getWalker>["onIgnore"],
  ): Promise<CoverageMapper<T>> {
    const filename = fileURLToPath(options.coverage.url);
    const directory = dirname(filename);
 
    const map = new TraceMap(
      (options.sourceMap as typeof options.sourceMap & { version: 3 }) ||
        (await getInlineSourceMap(filename, options.code)) ||
        createEmptySourceMap(filename, options.code),
    );
 
    return new CoverageMapper<T>(
      new Locator(options.code, map, directory),
      createCoverageMapData(filename, map),
      normalize(options.coverage),
      options.wrapperLength || 0,
      directory,
      onIgnoreNode,
      options.ignoreNode,
      options.ignoreSourceCode,
    );
  }
 
  onFunction(
    node: FunctionNodes,
    positions: {
      loc: Pick<Node, "start" | "end">;
      decl: Pick<Node, "start" | "end">;
    },
  ) {
    Iif (this.#onIgnore(node, "function")) {
      return;
    }
 
    const loc = this.locator.getLoc(positions.loc);
    if (loc === null) return;
 
    const decl = this.locator.getLoc(positions.decl);
    Iif (decl === null) return;
 
    const covered = getCount(
      {
        startOffset: node.start + this.wrapperLength,
        endOffset: node.end + this.wrapperLength,
      },
      this.ranges,
    );
 
    if (this.ignoreSourceCode) {
      const current = this.locator.getLoc(node) || loc;
      const sources = this.locator.getSourceLines(current, this.#getSourceFilename(current));
 
      if (
        sources != null &&
        this.ignoreSourceCode(sources, "function", {
          start: { line: current.start.line, column: current.start.column },
          end: { line: current.end.line, column: current.end.column },
        })
      ) {
        return;
      }
    }
 
    addFunction({
      coverageMapData: this.coverageMapData,
      covered,
      loc,
      decl,
      filename: this.#getSourceFilename(loc),
      name: getFunctionName(node),
    });
  }
 
  onStatement(node: Node, parent?: Node) {
    if (this.#onIgnore(parent || node, "statement")) {
      return;
    }
 
    const loc = this.locator.getLoc(node);
    if (loc === null) return;
 
    const covered = getCount(
      {
        startOffset: (parent || node).start + this.wrapperLength,
        endOffset: (parent || node).end + this.wrapperLength,
      },
      this.ranges,
    );
 
    if (this.ignoreSourceCode) {
      const current = (parent && this.locator.getLoc(parent)) || loc;
      const sources = this.locator.getSourceLines(current, this.#getSourceFilename(current));
 
      if (
        sources != null &&
        this.ignoreSourceCode(sources, "statement", {
          start: { line: current.start.line, column: current.start.column },
          end: { line: current.end.line, column: current.end.column },
        })
      ) {
        return;
      }
    }
 
    addStatement({
      coverageMapData: this.coverageMapData,
      loc,
      covered,
      filename: this.#getSourceFilename(loc),
    });
  }
 
  onBranch(type: Branch, node: Node, branches: (Node | null | undefined)[]) {
    if (this.#onIgnore(node, "branch")) {
      return;
    }
 
    const loc = this.locator.getLoc(node);
    Iif (loc === null) return;
 
    const locations = [];
    const covered: number[] = [];
 
    for (const branch of branches) {
      if (!branch) {
        locations.push({
          start: { line: undefined, column: undefined },
          end: { line: undefined, column: undefined },
        });
 
        const count = getCount(
          {
            startOffset: node.start + this.wrapperLength,
            endOffset: node.end + this.wrapperLength,
          },
          this.ranges,
        );
        const previous = covered.at(-1) || 0;
        covered.push(count - previous);
 
        continue;
      }
 
      const location = this.locator.getLoc(branch);
      Eif (location !== null) {
        locations.push(location);
      }
 
      const bias = branch.type === "BlockStatement" ? 1 : 0;
 
      covered.push(
        getCount(
          {
            startOffset: branch.start + bias + this.wrapperLength,
            endOffset: branch.end - bias + this.wrapperLength,
          },
          this.ranges,
        ),
      );
    }
 
    if (type === "if") {
      if (locations.length > 0) {
        locations[0] = loc;
      }
    }
 
    if (locations.length === 0) {
      return;
    }
 
    Iif (this.ignoreSourceCode) {
      const sources = this.locator.getSourceLines(loc, this.#getSourceFilename(loc));
 
      if (
        sources != null &&
        this.ignoreSourceCode(sources, "branch", {
          start: { line: loc.start.line, column: loc.start.column },
          end: { line: loc.end.line, column: loc.end.column },
        })
      ) {
        return;
      }
    }
 
    addBranch({
      coverageMapData: this.coverageMapData,
      loc,
      locations,
      type,
      covered,
      filename: this.#getSourceFilename(loc),
    });
  }
 
  generate(): CoverageMapData {
    this.locator.reset();
    return this.coverageMapData;
  }
 
  #getSourceFilename(position: {
    start: { filename: string | null };
    end: { filename: string | null };
  }) {
    const sourceFilename = position.start.filename || position.end.filename;
 
    Iif (!sourceFilename) {
      throw new Error(`Missing original filename for ${JSON.stringify(position, null, 2)}`);
    }
 
    if (sourceFilename.startsWith("file://")) {
      return fileURLToPath(sourceFilename);
    }
 
    return resolve(this.directory, sourceFilename);
  }
 
  #onIgnore(node: Node, type: "function" | "statement" | "branch") {
    if (!this.ignoreNode) {
      return false;
    }
 
    const scope = this.ignoreNode(node as T, type);
 
    if (scope === "ignore-this-and-nested-nodes") {
      this.onIgnoreNode(node);
    }
 
    return scope;
  }
}