'f'
mh-two-thousand-and-two
2024-04-12 26f2711ef9461961fb953e2b497bd314ef95e345
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
 Copyright 2012-2015, Yahoo Inc.
 Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */
'use strict';
 
const percent = require('./percent');
const dataProperties = require('./data-properties');
const { CoverageSummary } = require('./coverage-summary');
 
// returns a data object that represents empty coverage
function emptyCoverage(filePath, reportLogic) {
    const cov = {
        path: filePath,
        statementMap: {},
        fnMap: {},
        branchMap: {},
        s: {},
        f: {},
        b: {}
    };
    if (reportLogic) cov.bT = {};
    return cov;
}
 
// asserts that a data object "looks like" a coverage object
function assertValidObject(obj) {
    const valid =
        obj &&
        obj.path &&
        obj.statementMap &&
        obj.fnMap &&
        obj.branchMap &&
        obj.s &&
        obj.f &&
        obj.b;
    if (!valid) {
        throw new Error(
            'Invalid file coverage object, missing keys, found:' +
                Object.keys(obj).join(',')
        );
    }
}
 
const keyFromLoc = ({ start, end }) =>
    `${start.line}|${start.column}|${end.line}|${end.column}`;
 
const isObj = o => !!o && typeof o === 'object';
const isLineCol = o =>
    isObj(o) && typeof o.line === 'number' && typeof o.column === 'number';
const isLoc = o => isObj(o) && isLineCol(o.start) && isLineCol(o.end);
const getLoc = o => (isLoc(o) ? o : isLoc(o.loc) ? o.loc : null);
 
// When merging, we can have a case where two ranges cover
// the same block of code with `hits=1`, and each carve out a
// different range with `hits=0` to indicate it's uncovered.
// Find the nearest container so that we can properly indicate
// that both sections are hit.
// Returns null if no containing item is found.
const findNearestContainer = (item, map) => {
    const itemLoc = getLoc(item);
    if (!itemLoc) return null;
    // the B item is not an identified range in the A set, BUT
    // it may be contained by an identified A range. If so, then
    // any hit of that containing A range counts as a hit of this
    // B range as well. We have to find the *narrowest* containing
    // range to be accurate, since ranges can be hit and un-hit
    // in a nested fashion.
    let nearestContainingItem = null;
    let containerDistance = null;
    let containerKey = null;
    for (const [i, mapItem] of Object.entries(map)) {
        const mapLoc = getLoc(mapItem);
        if (!mapLoc) continue;
        // contained if all of line distances are > 0
        // or line distance is 0 and col dist is >= 0
        const distance = [
            itemLoc.start.line - mapLoc.start.line,
            itemLoc.start.column - mapLoc.start.column,
            mapLoc.end.line - itemLoc.end.line,
            mapLoc.end.column - itemLoc.end.column
        ];
        if (
            distance[0] < 0 ||
            distance[2] < 0 ||
            (distance[0] === 0 && distance[1] < 0) ||
            (distance[2] === 0 && distance[3] < 0)
        ) {
            continue;
        }
        if (nearestContainingItem === null) {
            containerDistance = distance;
            nearestContainingItem = mapItem;
            containerKey = i;
            continue;
        }
        // closer line more relevant than closer column
        const closerBefore =
            distance[0] < containerDistance[0] ||
            (distance[0] === 0 && distance[1] < containerDistance[1]);
        const closerAfter =
            distance[2] < containerDistance[2] ||
            (distance[2] === 0 && distance[3] < containerDistance[3]);
        if (closerBefore || closerAfter) {
            // closer
            containerDistance = distance;
            nearestContainingItem = mapItem;
            containerKey = i;
        }
    }
    return containerKey;
};
 
// either add two numbers, or all matching entries in a number[]
const addHits = (aHits, bHits) => {
    if (typeof aHits === 'number' && typeof bHits === 'number') {
        return aHits + bHits;
    } else if (Array.isArray(aHits) && Array.isArray(bHits)) {
        return aHits.map((a, i) => (a || 0) + (bHits[i] || 0));
    }
    return null;
};
 
const addNearestContainerHits = (item, itemHits, map, mapHits) => {
    const container = findNearestContainer(item, map);
    if (container) {
        return addHits(itemHits, mapHits[container]);
    } else {
        return itemHits;
    }
};
 
const mergeProp = (aHits, aMap, bHits, bMap, itemKey = keyFromLoc) => {
    const aItems = {};
    for (const [key, itemHits] of Object.entries(aHits)) {
        const item = aMap[key];
        aItems[itemKey(item)] = [itemHits, item];
    }
    const bItems = {};
    for (const [key, itemHits] of Object.entries(bHits)) {
        const item = bMap[key];
        bItems[itemKey(item)] = [itemHits, item];
    }
    const mergedItems = {};
    for (const [key, aValue] of Object.entries(aItems)) {
        let aItemHits = aValue[0];
        const aItem = aValue[1];
        const bValue = bItems[key];
        if (!bValue) {
            // not an identified range in b, but might be contained by one
            aItemHits = addNearestContainerHits(aItem, aItemHits, bMap, bHits);
        } else {
            // is an identified range in b, so add the hits together
            aItemHits = addHits(aItemHits, bValue[0]);
        }
        mergedItems[key] = [aItemHits, aItem];
    }
    // now find the items in b that are not in a. already added matches.
    for (const [key, bValue] of Object.entries(bItems)) {
        let bItemHits = bValue[0];
        const bItem = bValue[1];
        if (mergedItems[key]) continue;
        // not an identified range in b, but might be contained by one
        bItemHits = addNearestContainerHits(bItem, bItemHits, aMap, aHits);
        mergedItems[key] = [bItemHits, bItem];
    }
 
    const hits = {};
    const map = {};
 
    Object.values(mergedItems).forEach(([itemHits, item], i) => {
        hits[i] = itemHits;
        map[i] = item;
    });
 
    return [hits, map];
};
 
/**
 * provides a read-only view of coverage for a single file.
 * The deep structure of this object is documented elsewhere. It has the following
 * properties:
 *
 * * `path` - the file path for which coverage is being tracked
 * * `statementMap` - map of statement locations keyed by statement index
 * * `fnMap` - map of function metadata keyed by function index
 * * `branchMap` - map of branch metadata keyed by branch index
 * * `s` - hit counts for statements
 * * `f` - hit count for functions
 * * `b` - hit count for branches
 */
class FileCoverage {
    /**
     * @constructor
     * @param {Object|FileCoverage|String} pathOrObj is a string that initializes
     * and empty coverage object with the specified file path or a data object that
     * has all the required properties for a file coverage object.
     */
    constructor(pathOrObj, reportLogic = false) {
        if (!pathOrObj) {
            throw new Error(
                'Coverage must be initialized with a path or an object'
            );
        }
        if (typeof pathOrObj === 'string') {
            this.data = emptyCoverage(pathOrObj, reportLogic);
        } else if (pathOrObj instanceof FileCoverage) {
            this.data = pathOrObj.data;
        } else if (typeof pathOrObj === 'object') {
            this.data = pathOrObj;
        } else {
            throw new Error('Invalid argument to coverage constructor');
        }
        assertValidObject(this.data);
    }
 
    /**
     * returns computed line coverage from statement coverage.
     * This is a map of hits keyed by line number in the source.
     */
    getLineCoverage() {
        const statementMap = this.data.statementMap;
        const statements = this.data.s;
        const lineMap = Object.create(null);
 
        Object.entries(statements).forEach(([st, count]) => {
            /* istanbul ignore if: is this even possible? */
            if (!statementMap[st]) {
                return;
            }
            const { line } = statementMap[st].start;
            const prevVal = lineMap[line];
            if (prevVal === undefined || prevVal < count) {
                lineMap[line] = count;
            }
        });
        return lineMap;
    }
 
    /**
     * returns an array of uncovered line numbers.
     * @returns {Array} an array of line numbers for which no hits have been
     *  collected.
     */
    getUncoveredLines() {
        const lc = this.getLineCoverage();
        const ret = [];
        Object.entries(lc).forEach(([l, hits]) => {
            if (hits === 0) {
                ret.push(l);
            }
        });
        return ret;
    }
 
    /**
     * returns a map of branch coverage by source line number.
     * @returns {Object} an object keyed by line number. Each object
     * has a `covered`, `total` and `coverage` (percentage) property.
     */
    getBranchCoverageByLine() {
        const branchMap = this.branchMap;
        const branches = this.b;
        const ret = {};
        Object.entries(branchMap).forEach(([k, map]) => {
            const line = map.line || map.loc.start.line;
            const branchData = branches[k];
            ret[line] = ret[line] || [];
            ret[line].push(...branchData);
        });
        Object.entries(ret).forEach(([k, dataArray]) => {
            const covered = dataArray.filter(item => item > 0);
            const coverage = (covered.length / dataArray.length) * 100;
            ret[k] = {
                covered: covered.length,
                total: dataArray.length,
                coverage
            };
        });
        return ret;
    }
 
    /**
     * return a JSON-serializable POJO for this file coverage object
     */
    toJSON() {
        return this.data;
    }
 
    /**
     * merges a second coverage object into this one, updating hit counts
     * @param {FileCoverage} other - the coverage object to be merged into this one.
     *  Note that the other object should have the same structure as this one (same file).
     */
    merge(other) {
        if (other.all === true) {
            return;
        }
 
        if (this.all === true) {
            this.data = other.data;
            return;
        }
 
        let [hits, map] = mergeProp(
            this.s,
            this.statementMap,
            other.s,
            other.statementMap
        );
        this.data.s = hits;
        this.data.statementMap = map;
 
        const keyFromLocProp = x => keyFromLoc(x.loc);
        const keyFromLocationsProp = x => keyFromLoc(x.locations[0]);
 
        [hits, map] = mergeProp(
            this.f,
            this.fnMap,
            other.f,
            other.fnMap,
            keyFromLocProp
        );
        this.data.f = hits;
        this.data.fnMap = map;
 
        [hits, map] = mergeProp(
            this.b,
            this.branchMap,
            other.b,
            other.branchMap,
            keyFromLocationsProp
        );
        this.data.b = hits;
        this.data.branchMap = map;
 
        // Tracking additional information about branch truthiness
        // can be optionally enabled:
        if (this.bT && other.bT) {
            [hits, map] = mergeProp(
                this.bT,
                this.branchMap,
                other.bT,
                other.branchMap,
                keyFromLocationsProp
            );
            this.data.bT = hits;
        }
    }
 
    computeSimpleTotals(property) {
        let stats = this[property];
 
        if (typeof stats === 'function') {
            stats = stats.call(this);
        }
 
        const ret = {
            total: Object.keys(stats).length,
            covered: Object.values(stats).filter(v => !!v).length,
            skipped: 0
        };
        ret.pct = percent(ret.covered, ret.total);
        return ret;
    }
 
    computeBranchTotals(property) {
        const stats = this[property];
        const ret = { total: 0, covered: 0, skipped: 0 };
 
        Object.values(stats).forEach(branches => {
            ret.covered += branches.filter(hits => hits > 0).length;
            ret.total += branches.length;
        });
        ret.pct = percent(ret.covered, ret.total);
        return ret;
    }
 
    /**
     * resets hit counts for all statements, functions and branches
     * in this coverage object resulting in zero coverage.
     */
    resetHits() {
        const statements = this.s;
        const functions = this.f;
        const branches = this.b;
        const branchesTrue = this.bT;
        Object.keys(statements).forEach(s => {
            statements[s] = 0;
        });
        Object.keys(functions).forEach(f => {
            functions[f] = 0;
        });
        Object.keys(branches).forEach(b => {
            branches[b].fill(0);
        });
        // Tracking additional information about branch truthiness
        // can be optionally enabled:
        if (branchesTrue) {
            Object.keys(branchesTrue).forEach(bT => {
                branchesTrue[bT].fill(0);
            });
        }
    }
 
    /**
     * returns a CoverageSummary for this file coverage object
     * @returns {CoverageSummary}
     */
    toSummary() {
        const ret = {};
        ret.lines = this.computeSimpleTotals('getLineCoverage');
        ret.functions = this.computeSimpleTotals('f', 'fnMap');
        ret.statements = this.computeSimpleTotals('s', 'statementMap');
        ret.branches = this.computeBranchTotals('b');
        // Tracking additional information about branch truthiness
        // can be optionally enabled:
        if (this.bT) {
            ret.branchesTrue = this.computeBranchTotals('bT');
        }
        return new CoverageSummary(ret);
    }
}
 
// expose coverage data attributes
dataProperties(FileCoverage, [
    'path',
    'statementMap',
    'fnMap',
    'branchMap',
    's',
    'f',
    'b',
    'bT',
    'all'
]);
 
module.exports = {
    FileCoverage,
    // exported for testing
    findNearestContainer,
    addHits,
    addNearestContainerHits
};