@magelens/magento-template-coverage 0.0.0-stage → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,113 @@
1
+ <!--
2
+ SPDX-FileCopyrightText: MageLens
3
+ SPDX-License-Identifier: MIT
4
+ License: see LICENSE in the repository root.
5
+ -->
6
+
7
+ # Changelog
8
+
9
+ ## 2.0.1
10
+
11
+ - Publish under `@magelens/magento-template-coverage` with the same CLI and exports. Existing versions remain available under the previous scope.
12
+
13
+ ## 2.0.0 - 2026-11-09
14
+
15
+ - Update parse5 to 8.1.1 to fix malformed-HTML crashes, excessive parsing time and incorrect foreign-content tree construction used during template analysis.
16
+ - Require Node.js ^20.19.0 or >=22.12.0 for synchronous loading of the ESM-only parser; CommonJS package exports remain available. Recreate manifests and instrumented copies, then regenerate coverage reports after upgrading.
17
+
18
+ ## 1.5.5 - 2026-11-07
19
+
20
+ - Update Acorn to 8.19.0 for Unicode 17/18 identifiers and expression-validation fixes in Alpine, Knockout and template parsing, preserving Node.js 18.3 compatibility.
21
+
22
+ ## 1.5.4 - 2026-11-06
23
+
24
+ - Verify Playwright 1.65 compatibility with Chrome for Testing 156.0.8078.80, including inert controls, rendered accessible names and authenticated CSP fixtures with path-scoped cookies.
25
+
26
+ ## 1.5.3 - 2026-10-29
27
+
28
+ - Verify Node.js 26 compatibility alongside Node.js 24 for template analysis, Playwright integration and TypeScript declarations.
29
+
30
+ ## 1.5.2 - 2026-10-27
31
+
32
+ - Keep unsupported-binding warnings on their original PHTML lines after multiline PHP-generated Alpine event names.
33
+
34
+ ## 1.5.1 - 2026-10-27
35
+
36
+ - Measure Alpine listeners with PHP-generated event names, including Hyvä gallery and price updates, at their original PHTML locations.
37
+ - Preserve modifier-only listeners such as `@submit.prevent` without warnings or invented expression coverage.
38
+ - Keep other Alpine bindings working when PHP omits a conditional listener.
39
+ - Recreate manifests, instrumented copies and raw records when upgrading: version 1.5.1 uses new template identities.
40
+
41
+ ## 1.5.0 - 2026-10-18
42
+
43
+ - Support Hyvä CSP Alpine bindings without dynamic code generation, preserving event arguments, model writes, loop locals and inserted templates.
44
+ - Collect DOM observations under strict CSP without requiring `unsafe-eval`, while retaining Magento Admin’s Prototype DOM extensions.
45
+ - Measure PHP-selected lexical declarations in inline scripts, including the Hyvä CSP date-option template.
46
+ - Keep auxiliary Playwright login contexts functional without adding their setup activity to measured records.
47
+ - Provide `installTemplateRuntime` for Playwright warm-up contexts that serve instrumented templates without recording coverage.
48
+ - Recreate manifests, instrumented copies and raw records when upgrading: version 1.5 uses new template identities.
49
+
50
+
51
+ ## 1.4.0
52
+
53
+ - Link PHP-rendered JavaScript fragments to instrumented child templates in HTML and JSON reports.
54
+ - Distinguish empty output, linked child sources, unresolved generated code and output not observed during the run.
55
+ - Preserve execution counts at the child source; rendering a fragment does not cover its functions or branches.
56
+ - Collect source references through Cypress and Playwright across navigation, without adding template entries to JavaScript coverage.
57
+
58
+ Recreate manifests, disposable copies, static assets and raw records when upgrading. Version 1.4 changes template identities; JSON remains schema 2.
59
+
60
+ ## 1.3.0
61
+
62
+ - Include inline classic/module scripts in HTML/PHTML template coverage, with statement, function and branch counters mapped to the original template.
63
+ - Collect script execution through the existing Cypress and Playwright adapters, including inserted fragments and consumed native templates, without adding template entries to JavaScript coverage.
64
+ - Include static PHTML browser markup in DOM coverage and detect Knockout, legacy engines and Alpine bindings in PHTML.
65
+ - Preserve PHP code and line positions; show unsupported scripts and PHP-generated fragments as explicit coverage gaps.
66
+ - Keep inline scripts and JavaScript template literals in Alpine attributes from affecting template-engine detection and retain zero counters for unused templates and handlers.
67
+
68
+ Recreate manifests, disposable copies, static assets and raw records when upgrading. Version 1.3 changes template identities and adds script/function/branch details to schema 2 reports.
69
+
70
+ ## 1.2.0
71
+
72
+ - Added a Playwright context collector and composable fixtures, including TypeScript declarations and elgentos fixture examples.
73
+ - Added Alpine directive execution coverage in HTML and Hyvä PHTML while preserving PHP code/source lines and source-copy isolation.
74
+ - Preserved mixed Knockout/Alpine HTML, two-way model updates, radio groups, unexecuted branches, and existing Cypress engine integration.
75
+ - Fixed collection for global Knockout builds that populate their exports after publishing the object.
76
+ - Added real Playwright navigation/frame/page-close and Alpine/Knockout regressions. Unsupported directive forms are reported explicitly.
77
+
78
+ ## 1.1.2
79
+
80
+ - Run DOM observation and traversal in the application window's JavaScript realm, preserving Prototype DOM extensions on Magento admin pages during Cypress coverage.
81
+ - Verify legacy Magento fieldset interaction and template markers alongside the existing rendering and execution coverage regressions.
82
+
83
+ ## 1.1.1
84
+
85
+ - Let instrumented Underscore and Magento literal templates render safely while the execution collector is unavailable.
86
+ - Restore a deleted execution helper when Cypress reconnects to a retained document.
87
+
88
+ ## 1.1.0
89
+
90
+ - Inventory all and only `.html` files under configured roots, independent of directory layout.
91
+ - Add directory reports with breadcrumbs, aggregated line/statement/DOM totals and an optional searchable file list.
92
+ - Measure Underscore/mage-template, legacy jQuery tmpl and Magento UI literal execution in HTML files.
93
+ - Support inert template bodies stored inside HTML files, bare/default Magento bindings and SVG markup.
94
+ - Keep malformed or server-only syntax visible with explicit DOM-only explanations; allow engine overrides.
95
+ - Verify real engine output, cached/nested renders, escaping, false branches, directory totals and offline links.
96
+
97
+ Recreate manifests, disposable copies and raw records. Source identities change; the JSON metric is now `template-execution` (schema 2).
98
+
99
+ ## 1.0.0
100
+
101
+ - Measure actual Knockout binding value evaluations in addition to template DOM presence.
102
+ - Map `data-bind`, virtual KO comments, and Magento shorthand to original lines and columns.
103
+ - Add source HTML reports with execution counts and uncovered/partial binding lines.
104
+ - Preserve observable identity, property writers, expression evaluation, and normal Magento rendering.
105
+ - Reset execution counters across tests and reattach across navigation and retained documents.
106
+ - Use schema version 2 and reject stale manifests, unsupported statement IDs, and invalid counts.
107
+ - Verify source mapping and merging with unit tests, plus real Magento/Knockout browser regressions.
108
+
109
+ Binding lines count declaration start lines. Callback bodies and expression branches are outside this metric.
110
+
111
+ ## 0.1.0
112
+
113
+ - Initial inventory, disposable instrumentation, Cypress DOM collection, and template presence reports.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) MageLens
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ SPDX-FileCopyrightText: MageLens
2
+ SPDX-License-Identifier: MIT
3
+ License: see LICENSE in the repository root.
package/README.md CHANGED
@@ -1,3 +1,242 @@
1
- # Temporary Holding Version
1
+ <!--
2
+ SPDX-FileCopyrightText: MageLens
3
+ SPDX-License-Identifier: MIT
4
+ License: see LICENSE in the repository root.
5
+ -->
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ # Magento 2 template coverage for Cypress and Playwright
8
+
9
+ Coverage for Magento HTML/PHTML templates, including Knockout, jQuery templates, Hyvä/Alpine bindings and inline JavaScript. Supports Cypress and Playwright collection with Luma/Knockout, Hyvä CSP and regular Hyvä/Alpine 3. Reports separate executable source lines from DOM presence. Originals stay untouched; only disposable copies are instrumented.
10
+
11
+ Use this package to find untested storefront bindings and inline scripts in Magento modules and themes. For a Docker environment that combines template, PHP and whole-file JavaScript reports, see [MageLens](https://github.com/MageLens/MageLens).
12
+
13
+ [Install](#install) · [Supported syntax](#html-template-syntax) · [Report semantics](#reading-the-numbers) · [FAQ](#faq)
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install --save-dev @magelens/magento-template-coverage@latest
19
+ ```
20
+
21
+ If you already use `@vitaliiboiko/magento-template-coverage`, remove it from your dev dependencies and change your imports to `@magelens/magento-template-coverage`. The CLI command stays `magento-template-coverage`.
22
+
23
+ Node.js 20.19+ within 20.x, or Node.js 22.12+ and an existing Cypress or Playwright installation are required. Version 2 drops Node.js 18 and older Node.js 20/22 releases to load the security-patched HTML parser synchronously. Each test runner retains its own Node/browser requirements.
24
+
25
+ For existing installations, follow the [upgrade instructions](#repeat-runs-and-upgrades) when updating the package.
26
+
27
+ ## Inventory → instrument → collect → report
28
+
29
+ Inventory every `.html` file under the selected roots, regardless of directory name.
30
+ The defaults are `app/code` and `app/design`. PHTML with browser markup is also inventoried, including script-only and static templates. PHP-only files, `.htm`, and whole `.js` files are excluded. PHP executable lines in PHTML remain in PHP coverage; the browser content belongs to template coverage.
31
+
32
+ ```sh
33
+ npx --no-install magento-template-coverage inventory \
34
+ --source src --manifest coverage/template-manifest.json
35
+
36
+ npx --no-install magento-template-coverage instrument \
37
+ --source src --manifest coverage/template-manifest.json \
38
+ --map app/code=coverage/template-copy/app-code \
39
+ --map app/design=coverage/template-copy/app-design
40
+ ```
41
+
42
+ Serve those disposable copies using your test environment and refresh Magento's
43
+ static assets and caches. The CLI rejects source-tree writes, symlinks, overlapping
44
+ destinations and changed source hashes. Repeated instrumentation starts from originals.
45
+ Use repeated `--root` and matching `--map` arguments to select other source directories.
46
+
47
+ Register the Cypress adapter before visiting the application:
48
+
49
+ ```js
50
+ const { registerTemplateCoverage } = require('@magelens/magento-template-coverage/cypress');
51
+ registerTemplateCoverage({ outputDir: '.template-coverage' });
52
+ ```
53
+
54
+ For Playwright, extend your existing test fixture before using its `page` or `context`:
55
+
56
+ ```js
57
+ const {test: base, expect} = require('@playwright/test');
58
+ const {withTemplateCoverage} = require('@magelens/magento-template-coverage/playwright');
59
+ const test = withTemplateCoverage(base, {outputDir: '.template-coverage'});
60
+ module.exports = {test, expect};
61
+ ```
62
+
63
+ Coverage starts before application navigation, including navigation in other fixtures. Records preserve hits across documents, frames and explicitly closed pages. Every test/context has independent counters; fixture teardown writes records even after assertion failures. Parallel workers write unique files that the reporter can merge.
64
+
65
+ For standalone Playwright scripts, call `await registerTemplateCoverage(context, options)` from the `/playwright` export **before creating pages**, then `await collector.stop()` in `finally`, before closing the context. `collector.flush()` drains currently open pages. Abrupt browser/process termination cannot guarantee final records.
66
+
67
+ To integrate [elgentos/magento2-playwright](https://github.com/elgentos/magento2-playwright), extend both existing fixtures in its customization layer; keep its authentication, consent and setup configuration:
68
+
69
+ ```ts
70
+ // tests/utils/fixtures.utils.ts
71
+ import {test as baseTest, guestTest as baseGuest} from '@base/utils/fixtures.utils';
72
+ import {withTemplateCoverage} from '@magelens/magento-template-coverage/playwright';
73
+ export * from '@base/utils/fixtures.utils';
74
+ export const test = withTemplateCoverage(baseTest);
75
+ export const guestTest = withTemplateCoverage(baseGuest);
76
+ ```
77
+
78
+ Instrument the Magento source served by your test environment first. Adding a fixture alone does not instrument a remote store. Do not edit elgentos's generated `base-tests` directory.
79
+
80
+ After either runner:
81
+
82
+ ```sh
83
+ npx --no-install magento-template-coverage report \
84
+ --manifest coverage/template-manifest.json \
85
+ --hits .template-coverage --output coverage/templates
86
+ ```
87
+
88
+ Open **`coverage/templates/index.html`**. Directories have aggregated totals and
89
+ breadcrumb navigation, like a PHP coverage report. Each file links to its original
90
+ source with green/red/partial lines and statement counts. `all.html` provides a
91
+ searchable flat list. Every page works offline. `coverage-summary.json` includes
92
+ file and directory totals; directory percentages use summed covered/total counts.
93
+
94
+ ## HTML template syntax
95
+
96
+ | Syntax inside `.html` / `.phtml` | Execution measured |
97
+ | --- | --- |
98
+ | Knockout `data-bind` and virtual `ko` comments | Binding value accessor evaluations; two-way property writers are preserved. |
99
+ | Magento UI shorthand | Standard renderer attributes and nodes, including `if`, `each`, `render`, `translate`, `ko-value`, and bare/default bindings. |
100
+ | Underscore / `mage/template` | `<%= … %>`, `<%- … %>`, and expressions in `<% … %>` code: conditions, loops, assignments, initializers, returns, and nested function bodies. |
101
+ | Legacy jQuery tmpl | `${…}`, `{{= …}}`, `if`, `else`, `each`, `html`, `tmpl`, and `wrap`. The normal engine still handles escaping, function invocation and nested templates. |
102
+ | Magento UI literals | `${ $.expression }`, including nested JavaScript expressions. |
103
+ | Alpine 3 / Hyvä default theme | `x-data`, `x-text`, `x-html`, `x-html-safe`, `x-show`, `x-if`, `x-bind` / `:`, `x-on` / `@`, `x-init`, `x-for` collections and assignable `x-model` expressions. Event hits count handler evaluation; inert/false template bodies stay uncovered. |
104
+ | Inline `<script>` / `<script type="module">` | Statements, functions and branch alternatives, mapped to the original HTML/PHTML file. Scripts in cached templates remain uncovered until the application executes them. |
105
+ | Plain HTML | DOM presence; static markup has no executable-line denominator. |
106
+ | Template bodies in an HTML file | Supported `<script type="text/html">`, `text/x-magento-template`, `text/x-jquery-tmpl`, `text/x-template`, and native `<template>` bodies remain unexecuted until consumed. |
107
+
108
+ The adapter installs counters before application code runs. Knockout and jQuery
109
+ integration attaches through RequireJS; application tests do not need to require
110
+ engines themselves. The legacy jQuery plugin is **not installed into your application**
111
+ by this package. The browser harness tests its pinned upstream implementation.
112
+
113
+ Automatic detection recognizes Underscore and jQuery directives. `${ $.… }` selects
114
+ Magento literals; other `${…}` outside Alpine attributes selects jQuery tmpl. JavaScript template literals inside Alpine attributes and inline scripts do not select a legacy template engine. For ambiguous syntax, override
115
+ an exact file or directory prefix during inventory; the most specific prefix wins:
116
+
117
+ ```sh
118
+ npx --no-install magento-template-coverage inventory \
119
+ --source src --manifest coverage/template-manifest.json \
120
+ --engine app/code/Example/Module/view/frontend/web/fragments=literal
121
+ ```
122
+
123
+ Available engines: `auto`, `knockout`, `underscore`, `jquery-tmpl`, `literal`, `alpine`, `html`.
124
+ Choose `html` to disable binding/engine expression instrumentation; executable inline scripts are still measured. Unrecognized/malformed binding expressions in
125
+ automatic mode are retained with a visible binding-coverage limitation; inline script coverage and DOM observation remain available. Explicit legacy engine
126
+ selections fail on syntax errors; unsupported Alpine directives remain unchanged with a report note. Server-rendered email directives also retain DOM-only
127
+ coverage; sending an email does not produce browser coverage.
128
+
129
+ Automatic detection retains legacy engine precedence in mixed HTML; Alpine attributes in those regions remain unchanged with a report note. Use an explicit engine override when the remaining template syntax is ambiguous. PHTML uses the same engine detection, with PHP tokens masked during parsing. Mixed Knockout and Alpine bindings can share a file.
130
+
131
+ Alpine support includes the Hyvä CSP evaluator and regular Alpine 3. CSP binding coverage supports the property-path syntax used by Hyvä 1.5.3 (Alpine CSP 3.14.3), retaining evaluation scope, event arguments, loop locals and getter/setter models. Other CSP evaluator expression languages are not supported. Expressions still need to be valid for the evaluator used by your application; coverage does not make regular Alpine expressions CSP-compatible. PHTML is tokenized to leave PHP code and PHP line numbers unchanged; PHP-generated event names such as `@update-gallery-<?= (int)$productId ?>.window` retain their original source locations and modifiers. Modifier-only listeners such as `@submit.prevent` preserve their behavior without adding an expression to the coverage total. Directives emitted wholly by PHP are not assigned invented source locations. Unquoted/malformed directives and dynamic or multiline `x-model` expressions remain unchanged with a visible report limitation. Dynamic input type/name bindings are also left uninstrumented for model coverage. Custom Alpine plugins are measured only through the supported directives they evaluate.
132
+
133
+ ## Inline scripts and inserted fragments
134
+
135
+ Executable scripts are instrumented in HTML/PHTML and native `<template>` bodies. The same counters work when an application inserts or executes an instrumented template fragment later. Fetching, parsing or caching a fragment alone does not count as execution. Scripts loaded through `src` belong to their separate `.js` file; JSON and `text/x-magento-init` blocks are data, not executable script bodies.
136
+
137
+ PHTML scripts support PHP values, identifier suffixes, PHP `if/else` initializer choices and PHP-selected `const`/`let` declarations that retain their shared JavaScript scope. Original newlines and source locations are preserved. PHP branch choices are not counted as JavaScript branches. Unsupported scripts remain unchanged and are listed in the report. Runtime-generated template strings, database content and arbitrary generated code are not assigned invented source locations.
138
+
139
+ Standalone PHP `echo` expressions inside scripts are traced in the disposable copy. Each expression is evaluated once in its original PHP scope. A comment records whether its output is empty or contains counters from instrumented child templates, such as Hyvä reCAPTCHA validation fragments. The report links to those child source files; their statements, functions and branches are counted there only when JavaScript executes. The parent does not receive duplicate counters.
140
+
141
+ Output without a known child source stays unresolved. An expression that was not observed stays marked as not observed; it is not assumed to emit code. Links describe the instrumented child sources found in the output, not a source map for additional dynamically generated code. Supported tracing requires one expression in an `echo` statement (`<?= ... ?>` or `<?php echo ...; ?>`); other PHP output forms retain a diagnostic. Comments removed by a minifier or sanitizer can prevent source attribution without affecting the child execution counters.
142
+
143
+ The template report shows bindings and scripts in the same original file. Function and branch counters describe inline JavaScript; they do not imply branch-level coverage inside Knockout, Alpine or other template binding expressions. In the JSON report, `scripts.unsupported` lists unsupported scripts, `scripts.generated` lists unresolved or unobserved PHP output, and `scripts.references` includes all PHP output locations with their status and child-source links. Rendering and source attribution are separate from execution coverage.
144
+
145
+ ## Reading the numbers
146
+
147
+ **Executable lines** are distinct starting source lines of measured bindings, template expressions and inline script statements. **Statements** count those individual operations. **Script functions** and **script branches** are separate metrics for inline scripts. Static text and continuation lines have no execution denominator.
148
+ A Knockout `click` hit records binding evaluation, not callback invocation. An `if`
149
+ hit does not prove its condition was true; jQuery `else` counts branch entry. Dynamic
150
+ bindings generated by another expression are not assigned invented Knockout source locations.
151
+
152
+ **DOM presence** is independent: the source marker entered the tested document.
153
+ Hidden DOM counts; fetched files, detached caches and inert template bodies alone do
154
+ not count. Compiling a template without rendering it produces no execution hits.
155
+ Rendering a detached fragment can produce execution hits without DOM presence.
156
+
157
+ All physical `.html` files under the selected roots remain in the denominator,
158
+ including unused files, along with PHTML containing browser markup. Module/theme applicability is not inferred. PHP rendering, templates generated wholly by PHP/JS, database content, shadow roots and arbitrary third-party languages are outside the execution metric. Playwright collects child frames; the Cypress adapter retains its top-document behavior. Comments stripped
159
+ by minifiers/sanitizers can prevent DOM observation. Use Istanbul for whole `.js` files and PCOV for PHP executable lines. Inline script counters are stored only in template records; they never create `window.__coverage__` entries.
160
+
161
+ ## Repeat runs and upgrades
162
+
163
+ Use fresh manifests, disposable copies, static assets and raw records for each run.
164
+ Version 1.5 uses new source identities for every template. Recreate manifests, copies and raw records when upgrading. JSON retains schema version 2 and adds per-file script diagnostics, function and branch counters and their summaries. Hits from old
165
+ source identities are rejected. The metric is now named `template-execution`.
166
+
167
+ Each test writes a unique `.mtc` record. Counters reset between tests, including
168
+ retained documents; observations survive navigation. Reports recursively merge shard
169
+ records and deduplicate copied record IDs. Stale IDs, conflicting records and invalid
170
+ counts fail the report. No records produces an explicitly labelled inventory baseline.
171
+ Keep generated artifacts and this package in test infrastructure.
172
+
173
+ Collection does not use dynamic `Function` construction. For Cypress CSP checks,
174
+ set `experimentalCspAllowList: ['default-src', 'script-src', 'script-src-elem']`
175
+ and `modifyObstructiveCode: false` in the Cypress configuration. Cypress adds its
176
+ own script nonce and removes some directives; use Playwright when you need to test
177
+ the unmodified policy. See [Cypress CSP behavior](https://docs.cypress.io/app/references/content-security-policy).
178
+
179
+ Instrumented Alpine property paths use the reserved `x-mtc` directive and require
180
+ the package runtime before Alpine starts. The collection adapters install it
181
+ automatically. `withTemplateCoverage` also keeps auxiliary `browser.newContext()`
182
+ contexts functional, including worker-scoped login fixtures, without recording
183
+ their setup activity. For a separate warm-up browser that must not record coverage:
184
+
185
+ ```js
186
+ // Playwright: register before navigating any page in this context.
187
+ const {installTemplateRuntime} = require('@magelens/magento-template-coverage/playwright');
188
+ await installTemplateRuntime(context);
189
+
190
+ // Cypress: add to the warm-up support file.
191
+ const {observeExecution} = require('@magelens/magento-template-coverage/browser');
192
+ Cypress.on('window:before:load', win => observeExecution(win, () => {}));
193
+ ```
194
+
195
+ Keep warm-up and measured runs in separate browser contexts.
196
+
197
+ ## Package development
198
+
199
+ ```sh
200
+ npm test # requires PHP CLI for PHTML behavior checks
201
+ npm run test:types
202
+ npx playwright install chromium
203
+ npm run test:playwright
204
+ npm run test:browser -- /path/to/magento /path/to/cypress/node_modules/cypress
205
+ npm pack --dry-run
206
+ ```
207
+
208
+ The browser harness uses the supplied Magento checkout's real Knockout, renderer,
209
+ Underscore, `mage/template`, UI literal renderer and modal HTML. It fetches the legacy
210
+ jQuery engine at the revision and SHA-256 in `test/browser/engines-lock.json`, cached
211
+ in browser artifacts. It never modifies the Magento checkout. Tests assert exact
212
+ source IDs, real counters, false-body zeros, cached rerenders and unchanged rendering.
213
+
214
+ ## FAQ
215
+
216
+ ### Does this replace PHP or JavaScript coverage?
217
+
218
+ No. This package measures browser expressions and inline scripts in HTML/PHTML. Use [PCOV](https://github.com/MageLens/pcov) for PHP executable lines and Istanbul for whole `.js` files. [MageLens](https://github.com/MageLens/MageLens) integrates all three collectors.
219
+
220
+ ### Why is a visible template still uncovered?
221
+
222
+ DOM presence and expression execution are separate metrics. Confirm the application serves the instrumented disposable copies, refresh static assets, and register the adapter before navigation. A static template can have DOM presence without executable lines. See [reading the numbers](#reading-the-numbers).
223
+
224
+ ### Does it support Hyvä CSP themes?
225
+
226
+ Yes. Hyvä CSP bindings and inline scripts are measured without enabling `unsafe-eval` or `unsafe-inline`. Keep the theme’s script nonces or hash registration enabled. Coverage instruments the script before Magento computes its hash. See [supported syntax and limitations](#html-template-syntax).
227
+
228
+ ### Can I collect coverage from an existing remote store?
229
+
230
+ Only if you control its test environment and serve instrumented copies there. Installing a Cypress or Playwright fixture alone does not instrument the store. Keep instrumentation in test infrastructure.
231
+
232
+ ## Releases and support
233
+
234
+ See the [changelog](CHANGELOG.md) and [GitHub releases](https://github.com/MageLens/magento-template-coverage/releases). Report reproducible problems in [issues](https://github.com/MageLens/magento-template-coverage/issues), including the package version, runner, template syntax and a minimal example.
235
+
236
+ ## License
237
+
238
+ Licensed under the [MIT License](LICENSE), which permits commercial use, modification and redistribution under its terms.
239
+
240
+ ## Repository navigation for AI agents
241
+
242
+ See [AGENTS.md](AGENTS.md) for the architecture map, source entry points, validation commands and contribution constraints.
package/bin/cli.js ADDED
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-FileCopyrightText: MageLens
3
+ // SPDX-License-Identifier: MIT
4
+ // License: see LICENSE in the repository root.
5
+
6
+ 'use strict';
7
+
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+ const { parseArgs } = require('node:util');
11
+ const { createManifest, instrument, merge, readRecords, writeReport } = require('../lib');
12
+
13
+ function main() {
14
+ const { values, positionals } = parseArgs({
15
+ allowPositionals: true,
16
+ options: {
17
+ source: { type: 'string' },
18
+ root: { type: 'string', multiple: true },
19
+ map: { type: 'string', multiple: true },
20
+ engine: { type: 'string', multiple: true },
21
+ manifest: { type: 'string' },
22
+ hits: { type: 'string' },
23
+ output: { type: 'string' },
24
+ help: { type: 'boolean' }
25
+ }
26
+ });
27
+ if (values.help || !positionals.length) {
28
+ console.log(`Magento template execution coverage
29
+ inventory --source <Magento> --manifest <file> [--root app/code --root app/design] [--engine path=jquery-tmpl]
30
+ instrument --source <Magento> --manifest <file> --map app/code=<copy> --map app/design=<copy>
31
+ report --manifest <file> --hits <shard-directory> --output <report-directory>
32
+
33
+ Instrumentation only writes outside the original Magento tree. Reports measure
34
+ template bindings and inline scripts, their starting source lines, script functions/branches,
35
+ and separate DOM presence.
36
+ Engines: auto, knockout, underscore, jquery-tmpl, literal, alpine, html. Overrides match a file
37
+ or directory prefix; the most specific match wins.`);
38
+ return;
39
+ }
40
+ const command = positionals[0];
41
+ const required = command === 'inventory' ? ['source', 'manifest']
42
+ : command === 'instrument' ? ['source', 'manifest', 'map']
43
+ : command === 'report' ? ['manifest', 'hits', 'output'] : null;
44
+ if (!required || positionals.length !== 1) throw new Error(`Unknown command: ${positionals.join(' ')}`);
45
+ for (const option of required) if (!values[option]) throw new Error(`Missing --${option}`);
46
+ if (command === 'inventory') {
47
+ const engines = {};
48
+ for (const mapping of values.engine || []) {
49
+ const index = mapping.indexOf('=');
50
+ const name = mapping.slice(0, index);
51
+ if (index < 1 || Object.hasOwn(engines, name)) throw new Error(`Invalid or duplicate --engine: ${mapping}`);
52
+ engines[name] = mapping.slice(index + 1);
53
+ }
54
+ const manifest = createManifest({ source: values.source, roots: values.root, engines });
55
+ fs.mkdirSync(path.dirname(values.manifest), { recursive: true });
56
+ fs.writeFileSync(values.manifest, `${JSON.stringify(manifest, null, 2)}\n`);
57
+ console.log(`Inventoried ${manifest.templates.length} files; ${manifest.templates.filter(entry => entry.instrumented).length} browser templates.`);
58
+ } else {
59
+ const manifest = JSON.parse(fs.readFileSync(values.manifest, 'utf8'));
60
+ if (command === 'instrument') {
61
+ const mappings = {};
62
+ for (const mapping of values.map) {
63
+ const separator = mapping.indexOf('=');
64
+ if (separator < 1 || separator === mapping.length - 1) throw new Error(`Invalid --map: ${mapping}`);
65
+ const root = mapping.slice(0, separator);
66
+ if (Object.hasOwn(mappings, root)) throw new Error(`Duplicate --map: ${root}`);
67
+ mappings[root] = mapping.slice(separator + 1);
68
+ }
69
+ console.log(`Instrumented ${instrument({ source: values.source, manifest, mappings })} disposable templates.`);
70
+ } else {
71
+ const report = merge(manifest, readRecords(values.hits));
72
+ writeReport(report, values.output);
73
+ console.log(`Template execution: ${report.lines.covered}/${report.lines.total} lines; ${report.statements.covered}/${report.statements.total} statements.`);
74
+ console.log(`Template DOM coverage: ${report.summary.covered}/${report.summary.eligible}; ${report.summary.unsupported} unsupported. Report: ${path.join(values.output, 'index.html')}`);
75
+ }
76
+ }
77
+ }
78
+
79
+ try { main(); } catch (error) {
80
+ console.error(error.message);
81
+ process.exitCode = 1;
82
+ }
@@ -0,0 +1,70 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ const { observeTemplates } = require('../lib/browser');
8
+ const { observeExecution } = require('../lib/execution');
9
+
10
+ function registerTemplateCoverage({ outputDir = '.template-coverage' } = {}) {
11
+ let collector;
12
+ let execution;
13
+ let ids = new Set();
14
+ let hits = {};
15
+ let references = new Map();
16
+
17
+ function connect(win) {
18
+ collector?.disconnect();
19
+ execution?.disconnect();
20
+ collector = observeTemplates(win, id => ids.add(id), reference => references.set(JSON.stringify(reference), reference));
21
+ execution = observeExecution(win, (id, statement) => {
22
+ const counters = hits[id] ||= {};
23
+ counters[statement] = (counters[statement] || 0) + 1;
24
+ });
25
+ }
26
+
27
+ Cypress.on('test:before:run', () => {
28
+ if (collector) collector.disconnect();
29
+ execution?.disconnect();
30
+ collector = undefined;
31
+ ids = new Set();
32
+ hits = {};
33
+ references = new Map();
34
+ });
35
+ Cypress.on('window:before:load', win => {
36
+ connect(win);
37
+ });
38
+ Cypress.on('window:before:unload', () => {
39
+ if (collector) collector.flush();
40
+ });
41
+
42
+ beforeEach(() => {
43
+ // Also supports tests that keep the current page with testIsolation: false.
44
+ cy.window({ log: false }).then(win => {
45
+ if (!collector) connect(win);
46
+ });
47
+ });
48
+
49
+ afterEach(function () {
50
+ // Queue this after existing test commands; retain IDs from previous pages.
51
+ cy.then({ log: false }, () => {
52
+ if (collector) collector.flush();
53
+ const recordId = globalThis.crypto.randomUUID?.() ||
54
+ `${Date.now()}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
55
+ const record = {
56
+ schemaVersion: 2,
57
+ recordId,
58
+ spec: Cypress.spec.relative,
59
+ test: Cypress.currentTest.titlePath,
60
+ retry: this.currentTest.currentRetry(),
61
+ ids: [...ids].sort(),
62
+ hits,
63
+ references: [...references.values()]
64
+ };
65
+ return cy.writeFile(`${outputDir}/${recordId}.mtc`, JSON.stringify(record), { log: false });
66
+ });
67
+ });
68
+ }
69
+
70
+ module.exports = { registerTemplateCoverage };