Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Install Node
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: 18.x
node-version: 20.x
- uses: pnpm/action-setup@v2
with:
version: 9
Expand Down
142 changes: 140 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,153 @@ Steps:
```
## ember-template-imports integration

* in `ember-cli-build.js
```
* in `ember-cli-build.js`
```js
const app = new EmberApp(defaults, {
'ember-template-imports': {
inline_source_map: true,
},
});
```

## Template Coverage

This addon supports branch coverage for Glimmer/Handlebars templates (`.hbs` files and `<template>` tags in `.gjs`/`.gts` files). When `COVERAGE=true`, templates are automatically instrumented during compilation to track which branches are executed.

### What is tracked

- **Block conditionals**: `{{#if}}`, `{{#unless}}` (with and without `{{else}}`)
- **Inline conditionals**: `{{if condition "yes" "no"}}`, `(if condition "a" "b")`, and the `unless` equivalents
- **List branches**: `{{#each}}`/`{{#each-in}}` with `{{else}}` (items vs empty list)
- **Chained conditionals**: `{{else if}}` chains
- **Named blocks (slots)**: `<:header>`, `<:body>`, `<:footer>`, etc. -- tracks whether each named block was rendered
- **Default blocks**: `<MyComponent>content</MyComponent>` -- tracks whether the implicit default block content was rendered. Components are detected by uppercase tags, dotted paths (`<foo.bar>`), `@`-prefixed arguments (`<my-thing @value={{1}}>`), or block params (`<my-thing as |item|>`)

### How it works

A Glimmer AST plugin runs at build time and:
1. Injects `{{coverageInit}}` at the template root to register an Istanbul-compatible coverage object in `window.__coverage__`
2. Injects `{{coverageMark}}` at the start of each block branch body to record block branch hits
3. Wraps inline conditional conditions with `(coverageCond)` to record inline branch hits reactively

The coverage data integrates seamlessly with the existing Istanbul pipeline, appearing in the same HTML/LCOV/JSON reports alongside JavaScript coverage.

### Setup for .hbs files

No additional setup is needed. The AST plugin is registered automatically via `setupPreprocessorRegistry` when the addon is installed. Branch coverage for `.hbs` files works out of the box.

### Setup for .gjs/.gts files (strict mode)

For `.gjs`/`.gts` files using `<template>` tags, coverage helpers need to be in JavaScript scope. The `buildBabelPlugin()` method already includes a Babel plugin that injects the necessary imports automatically. No extra configuration is required if you already have `buildBabelPlugin()` in your `ember-cli-build.js`.

### Manual setup for babel-plugin-ember-template-compilation

If you configure `babel-plugin-ember-template-compilation` directly (e.g., in Embroider v2 apps), you can add the AST plugin as a transform:

```js
// babel.config.js or similar
const coverage = require('ember-cli-code-coverage');

module.exports = {
plugins: [
// Coverage babel plugins (includes import injection for .gjs/.gts)
...coverage.buildBabelPlugin({ embroider: true }),

// Template compilation with coverage AST transform
['babel-plugin-ember-template-compilation', {
transforms: [
...coverage.buildTemplateCoveragePlugin(),
// ...other transforms
],
}],
],
};
```

### Example

Given this template:
```hbs
{{#if @isLoggedIn}}
<p>Welcome, {{@user.name}}!</p>
{{else}}
<p>Please log in.</p>
{{/if}}

<div class={{if @isActive "active" "inactive"}}>
{{#each @items as |item|}}
{{item.name}}
{{else}}
No items found.
{{/each}}
</div>

<PageLayout>
<:header>My App</:header>
<:sidebar>Navigation</:sidebar>
<:body>Main content</:body>
</PageLayout>

<Modal @isOpen={{@showModal}}>
<p>This is the default block content</p>
</Modal>
```

The coverage report will show:
- Branch 0 (`if`): whether `@isLoggedIn` was truthy and/or falsy
- Branch 1 (`cond`): whether `@isActive` was truthy and/or falsy (inline conditional)
- Branch 2 (`each`): whether `@items` had items and/or was empty
- Branch 3 (`named-block`): whether `<:header>` was rendered
- Branch 4 (`named-block`): whether `<:sidebar>` was rendered
- Branch 5 (`named-block`): whether `<:body>` was rendered
- Branch 6 (`default-block`): whether `<Modal>` rendered its default block content

## V8 Compat Mode

By default, this addon uses `babel-plugin-istanbul` to instrument all JS/TS files at build time. As an alternative, you can use **V8 compat mode** to skip Istanbul instrumentation entirely and rely on Chrome's built-in V8 code coverage for JS/TS files, while still using the template AST plugin for `.hbs` branch coverage.

This is useful when you pair this addon with a V8 coverage collector like [`testem-code-coverage`](https://github.com/NullVoxPopuli/testem-code-coverage).

### Benefits

- **Faster builds** -- no Babel instrumentation pass for JS/TS files
- **More accurate JS coverage** -- V8 bytecode-level coverage has no instrumentation side effects
- **Template branch coverage preserved** -- the Glimmer AST plugin still instruments `{{#if}}`, `{{#unless}}`, inline `(if)`, named blocks, etc.

### Setup

1. Install a V8 coverage collector (e.g., `testem-code-coverage`)
2. Pass `v8: true` to `buildBabelPlugin()`:

```js
// ember-cli-build.js
let app = new EmberApp(defaults, {
babel: {
plugins: [
...require('ember-cli-code-coverage').buildBabelPlugin({ v8: true }),
],
},
});
```

3. Configure your V8 collector (see its docs for Testem integration)

### How it works

In V8 compat mode, `buildBabelPlugin({ v8: true })` returns only the template coverage import plugin (for `.gjs`/`.gts` strict-mode support). It does **not** include `babel-plugin-istanbul` or the Istanbul ignore plugin.

The coverage data flows from two sources:
- **JS/TS files**: V8/CDP coverage collected externally, converted to Istanbul format by your V8 collector
- **Template files** (`.hbs`, `<template>` in `.gjs`/`.gts`): Branch coverage from the AST plugin, written to `window.__coverage__` and sent via `/write-coverage`

Both produce Istanbul-format output keyed by file path, so they merge cleanly in the final report.

### Limitations

- V8 coverage only works in **Chromium-based browsers** (Chrome, Edge). Firefox and Safari are not supported.
- V8 coverage reports against compiled/bundled JS. Source map quality affects accuracy.
- Template branch coverage still requires this addon's AST plugin and runtime helpers.

## Configuration

Configuration is optional. It should be put in a file at `config/coverage.js` (`configPath` configuration in package.json is honored). In addition to this you can configure Istanbul by adding a `.istanbul.yml` file to the root directory of your app (See https://github.com/gotwarlost/istanbul#configuring)
Expand Down
38 changes: 38 additions & 0 deletions packages/ember-cli-code-coverage/addon/helpers/coverage-cond.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { helper } from '@ember/component/helper';
import recordBranchHit from 'ember-cli-code-coverage/utils/record-branch-hit';

/**
* Template helper that records a branch hit for inline conditionals and
* returns the condition value as-is (pass-through).
*
* Unlike coverageMark which uses constant args (and is thus memoized by
* Glimmer), this helper receives a tracked condition argument. When the
* condition changes, Glimmer re-evaluates this helper, correctly recording
* both true and false branches over the component's lifecycle.
*
* Usage (injected by AST plugin, not meant for manual use):
* {{if (coverageCond "file" 0 false condition) "yes" "no"}}
* {{unless (coverageCond "file" 1 true condition) "no"}}
*
* @param {string} filePath - the module name / file path of the template
* @param {number} branchId - the branch index within the file
* @param {boolean} reversed - true for {{unless}} (falsy=location 0, truthy=location 1)
* @param {*} condition - the original condition value (passed through unchanged)
*/
export default helper(function coverageCond([
filePath,
branchId,
reversed,
condition,
]) {
if (typeof window === 'undefined') {
return condition;
}

// For `if`: truthy → location 0 (consequent), falsy → location 1 (alternate)
// For `unless` (reversed): falsy → location 0 (body), truthy → location 1 (skip)
let locationId = reversed ? (condition ? 1 : 0) : condition ? 0 : 1;
recordBranchHit(filePath, branchId, locationId);

return condition;
});
126 changes: 126 additions & 0 deletions packages/ember-cli-code-coverage/addon/helpers/coverage-init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { helper } from '@ember/component/helper';

/**
* Template helper that registers an Istanbul-compatible coverage object
* for a template file in window.__coverage__.
*
* Injected automatically by the template coverage AST plugin at the root
* of each template that contains branch points.
*
* Usage (injected by AST plugin, not meant for manual use):
* {{coverageInit "my-app/templates/application.hbs" "{...branchMapJSON}"}}
*
* NOTE: This helper uses constant arguments, so Glimmer's autotracking will
* only invoke it once per component instance. This is intentional -- we only
* need to register the coverage map once per template file.
*
* Handles .gts files with multiple <template> blocks that share the same
* module name: subsequent calls merge new branches into the existing entry
* instead of skipping.
*
* @param {string} filePath - the module name / file path of the template
* @param {string} branchMapJson - JSON-encoded Istanbul branchMap object
*/
export default helper(function coverageInit([filePath, branchMapJson]) {
if (typeof window === 'undefined') {
return '';
}

// Ensure __coverage__ exists. Istanbul's babel plugin normally creates this,
// but templates may render before any instrumented JS executes.
if (!window.__coverage__) {
window.__coverage__ = {};
}

let branchMap;
try {
branchMap = JSON.parse(branchMapJson);
} catch (e) {
return '';
}

// If coverage already exists for this file, merge new branches.
// This handles .gts files with multiple <template> blocks that share
// the same module name but have separate branch maps with unique IDs
// (assigned by the AST plugin's per-module counter).
if (window.__coverage__[filePath]) {
let existing = window.__coverage__[filePath];
if (!window.__templateCoverageStmtMap__) {
window.__templateCoverageStmtMap__ = {};
}
let branchStmtMap = window.__templateCoverageStmtMap__[filePath] || {};
let stmtKeys = Object.keys(existing.statementMap);
let stmtId =
stmtKeys.length > 0 ? Math.max.apply(null, stmtKeys.map(Number)) + 1 : 0;

let ids = Object.keys(branchMap);
for (let i = 0; i < ids.length; i++) {
let id = ids[i];
// Skip if this branch ID was already registered (e.g., component re-render)
if (existing.branchMap[id]) {
continue;
}
let branch = branchMap[id];
existing.branchMap[id] = branch;
existing.b[id] = branch.locations.map(function () {
return 0;
});
for (let j = 0; j < branch.locations.length; j++) {
branchStmtMap[id + ':' + j] = stmtId;
existing.statementMap[stmtId] = branch.locations[j];
existing.s[stmtId] = 0;
stmtId++;
}
}
window.__templateCoverageStmtMap__[filePath] = branchStmtMap;
return '';
}

// First template for this file — create the coverage entry.
// Build Istanbul branch counters and synthetic statement entries.
// Each branch location gets a corresponding statement so that Istanbul's
// line/statement coverage metrics reflect whether branch bodies were reached,
// instead of being vacuously 100% from an empty statementMap.
let b = {};
let statementMap = {};
let s = {};
let branchStmtMap = {};
let stmtId = 0;
let ids = Object.keys(branchMap);
for (let i = 0; i < ids.length; i++) {
let id = ids[i];
let branch = branchMap[id];
b[id] = branch.locations.map(function () {
return 0;
});
// Create a synthetic statement for each branch location and record
// the mapping so coverageMark/coverageCond can increment both b[] and s[].
for (let j = 0; j < branch.locations.length; j++) {
branchStmtMap[id + ':' + j] = stmtId;
statementMap[stmtId] = branch.locations[j];
s[stmtId] = 0;
stmtId++;
}
}

// Register Istanbul-compatible coverage object (only standard keys).
window.__coverage__[filePath] = {
path: filePath,
statementMap: statementMap,
s: s,
branchMap: branchMap,
b: b,
fnMap: {},
f: {},
};

// Store the branch-to-statement mapping separately so it doesn't
// leak into Istanbul JSON output. coverageMark/coverageCond use this
// to keep statement counters in sync with branch counters.
if (!window.__templateCoverageStmtMap__) {
window.__templateCoverageStmtMap__ = {};
}
window.__templateCoverageStmtMap__[filePath] = branchStmtMap;

return '';
});
31 changes: 31 additions & 0 deletions packages/ember-cli-code-coverage/addon/helpers/coverage-mark.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { helper } from '@ember/component/helper';
import recordBranchHit from 'ember-cli-code-coverage/utils/record-branch-hit';

/**
* Template helper that increments an Istanbul branch coverage counter
* and its corresponding synthetic statement counter.
*
* Injected automatically by the template coverage AST plugin at the
* beginning of each branch body (if/else, unless, each with else,
* curly/angle-bracket component default blocks).
*
* Usage (injected by AST plugin, not meant for manual use):
* {{coverageMark "my-app/templates/application.hbs" 0 1}}
*
* NOTE: This helper uses constant arguments, so Glimmer's autotracking will
* only invoke it once per component instance. For block-level branch coverage,
* a single invocation is sufficient to record that the branch was taken.
*
* @param {string} filePath - the module name / file path of the template
* @param {number} branchId - the branch index within the file
* @param {number} locationId - the location index within the branch (0=consequent, 1=alternate)
*/
export default helper(function coverageMark([filePath, branchId, locationId]) {
if (typeof window === 'undefined') {
return '';
}

recordBranchHit(filePath, branchId, locationId);

return '';
});
30 changes: 30 additions & 0 deletions packages/ember-cli-code-coverage/addon/utils/record-branch-hit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Records a branch hit in the Istanbul coverage object and increments
* the corresponding synthetic statement counter for line coverage.
*
* Shared by coverageMark and coverageCond helpers to avoid duplication.
*
* @param {string} filePath - the template module name / file path
* @param {number} branchId - the branch index within the file
* @param {number} locationId - the location index within the branch
*/
export default function recordBranchHit(filePath, branchId, locationId) {
let coverage = window.__coverage__ && window.__coverage__[filePath];
if (!coverage || !coverage.b || !coverage.b[branchId]) {
return;
}

coverage.b[branchId][locationId] =
(coverage.b[branchId][locationId] || 0) + 1;

// Increment the synthetic statement counter for line coverage.
// The mapping is stored separately from the Istanbul coverage object
// to avoid polluting Istanbul JSON output.
let stmtMap =
window.__templateCoverageStmtMap__ &&
window.__templateCoverageStmtMap__[filePath];
let stmtId = stmtMap && stmtMap[branchId + ':' + locationId];
if (stmtId !== undefined && coverage.s) {
coverage.s[stmtId] = (coverage.s[stmtId] || 0) + 1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from 'ember-cli-code-coverage/helpers/coverage-cond';
Loading
Loading