@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/lib/alpine.js ADDED
@@ -0,0 +1,203 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ const {parseFragment} = require('parse5');
8
+ const {parse} = require('acorn');
9
+ const {decodeHTMLAttribute} = require('entities');
10
+ const PhpParser = require('php-parser');
11
+ const {hit} = require('./engines');
12
+
13
+ // Tokenize PHP instead of treating ?> in strings, comments and heredocs as HTML.
14
+ // Keep offsets identical so reports always point into original PHTML.
15
+ function maskPhp(source) {
16
+ let masked = '', offset = 0, open = -1;
17
+ const ranges = [];
18
+ for (const token of new PhpParser().tokenGetAll(source)) {
19
+ const text = Array.isArray(token) ? token[1] : token;
20
+ const type = Array.isArray(token) ? token[0] : '';
21
+ if (type === 'T_OPEN_TAG' || type === 'T_OPEN_TAG_WITH_ECHO') open = offset;
22
+ masked += type === 'T_INLINE_HTML' ? text : text.replace(/[^\r\n]/g, ' ');
23
+ offset += text.length;
24
+ if (type === 'T_CLOSE_TAG') { ranges.push([open, offset]); open = -1; }
25
+ }
26
+ if (open >= 0) ranges.push([open, offset]);
27
+ if (offset !== source.length) throw new Error('Cannot map PHP template tokens');
28
+ return {masked: maskEventNames(masked, ranges), ranges};
29
+ }
30
+
31
+ // Spaces are safe for PHP between attributes and inside values, but split an
32
+ // event name. Walk only real opening tags and keep PHP within such names opaque.
33
+ // Unique, same-length placeholders also prevent parse5 dropping distinct PHP
34
+ // names as duplicate attributes. Nothing from this parsing copy is emitted.
35
+ function maskEventNames(masked, ranges) {
36
+ if (!ranges.length) return masked;
37
+ const ends = new Map(ranges);
38
+ const tree = parseFragment(masked, {sourceCodeLocationInfo: true});
39
+ const visit = node => {
40
+ const tag = node.sourceCodeLocation?.startTag;
41
+ if (tag) {
42
+ let cursor = tag.startOffset + /^<[^\s/>]+/.exec(masked.slice(tag.startOffset))[0].length;
43
+ while (cursor < tag.endOffset - 1) {
44
+ if (/[\s/]/.test(masked[cursor])) { cursor++; continue; }
45
+ const start = cursor;
46
+ while (cursor < tag.endOffset && !/[\s=/>]/.test(masked[cursor])) cursor++;
47
+ if (/^(?:@|x-on:)/i.test(masked.slice(start, cursor))) {
48
+ while (ends.has(cursor)) {
49
+ const end = ends.get(cursor);
50
+ const placeholder = cursor.toString(36).padEnd(end - cursor, '_');
51
+ masked = masked.slice(0, cursor) + placeholder + masked.slice(end);
52
+ cursor = end;
53
+ while (cursor < tag.endOffset && !/[\s=/>]/.test(masked[cursor])) cursor++;
54
+ }
55
+ }
56
+ while (/\s/.test(masked[cursor] || '') && cursor < tag.endOffset) cursor++;
57
+ if (masked[cursor] === '=') {
58
+ cursor++;
59
+ while (/\s/.test(masked[cursor] || '') && cursor < tag.endOffset) cursor++;
60
+ const quote = masked[cursor];
61
+ if (quote === '"' || quote === "'") {
62
+ cursor++;
63
+ while (cursor < tag.endOffset && masked[cursor] !== quote) cursor++;
64
+ cursor++;
65
+ } else {
66
+ while (cursor < tag.endOffset && !/[\s>]/.test(masked[cursor])) cursor++;
67
+ }
68
+ }
69
+ if (cursor === start) cursor++;
70
+ }
71
+ }
72
+ for (const child of node.childNodes || []) visit(child);
73
+ if (node.content) visit(node.content);
74
+ };
75
+ visit(tree);
76
+ return masked;
77
+ }
78
+
79
+ const expressionDirectives = new Set(['data', 'text', 'html', 'html-safe', 'show', 'if', 'bind', 'init', 'on', 'for', 'model']);
80
+
81
+ function analyzeAlpine(source, templateId, {phtml = false, register, edit} = {}) {
82
+ const {masked, ranges} = phtml ? maskPhp(source) : {masked: source, ranges: []};
83
+ const tree = parseFragment(masked, {sourceCodeLocationInfo: true});
84
+ const statements = [], edits = [], unsupported = [];
85
+ const location = offset => {
86
+ const lines = source.slice(0, offset).split(/\r\n|\r|\n/);
87
+ return {line: lines.length, column: lines.at(-1).length};
88
+ };
89
+ const visit = node => {
90
+ const scoped = [];
91
+ for (const attribute of node.attrs || []) {
92
+ let name = attribute.name;
93
+ const directive = name.startsWith('@') ? 'on' : name.startsWith(':') ? 'bind'
94
+ : name.match(/^x-([\w-]+)/)?.[1];
95
+ if (!expressionDirectives.has(directive)) continue;
96
+ // :key is evaluated in x-for's generated loop scope, not on its own.
97
+ const span = node.sourceCodeLocation?.attrs?.[name];
98
+ if (!span) continue;
99
+ const raw = masked.slice(span.startOffset, span.endOffset);
100
+ const nameLength = /^[^\s=]+/.exec(raw)[0].length;
101
+ if (ranges.some(([from, to]) => from >= span.startOffset && to <= span.startOffset + nameLength)) {
102
+ name = source.slice(span.startOffset, span.startOffset + nameLength);
103
+ }
104
+ const line = location(span.startOffset).line;
105
+ // A valueless listener applies modifiers without evaluating an expression.
106
+ if (directive === 'on' && /^(?:@|x-on:)[^\s.]+(?:\.[^\s.]+)*$/.test(raw) && !raw.includes('=')) continue;
107
+ const match = /^[^\s=]+\s*=\s*(["'])/.exec(raw);
108
+ if (!match) { unsupported.push(`Unquoted Alpine directive ${name} at line ${line}`); continue; }
109
+ const start = span.startOffset + match[0].length;
110
+ const end = span.endOffset - 1;
111
+ let expression = source.slice(start, end);
112
+ if (!expression.trim()) continue;
113
+ let validation = masked.slice(start, end);
114
+ for (const [from, to] of ranges) {
115
+ if (from >= start && to <= end) {
116
+ const relative = from - start;
117
+ validation = validation.slice(0, relative) + '0' + validation.slice(relative + 1);
118
+ }
119
+ }
120
+ validation = decodeHTMLAttribute(validation);
121
+ let from = start, to = end, kind = 'expression';
122
+ if (directive === 'for') {
123
+ const loop = /^(.*?)\s+(?:in|of)\s+([\s\S]+)$/.exec(validation);
124
+ if (!loop) { unsupported.push(`Cannot map Alpine x-for at line ${line}`); continue; }
125
+ // The collection's raw span is located without decoding its entities.
126
+ const rawLoop = /^(.*?)\s+(?:in|of)\s+([\s\S]+)$/.exec(expression);
127
+ if (!rawLoop) { unsupported.push(`Cannot map Alpine x-for at line ${line}`); continue; }
128
+ from = end - rawLoop[2].length;
129
+ expression = rawLoop[2]; validation = loop[2];
130
+ }
131
+ let ast;
132
+ try {
133
+ ast = parse(`(${validation}\n)`, {ecmaVersion: 'latest', allowAwaitOutsideFunction: true}).body[0].expression;
134
+ } catch (error) {
135
+ if (['init', 'on'].includes(directive)) {
136
+ try { parse(validation, {ecmaVersion: 'latest', allowAwaitOutsideFunction: true, allowReturnOutsideFunction: true}); kind = 'body'; }
137
+ catch { unsupported.push(`Cannot parse Alpine ${name} at line ${line}`); continue; }
138
+ } else { unsupported.push(`Cannot parse Alpine ${name} at line ${line}`); continue; }
139
+ }
140
+ if (directive === 'model' && (!['Identifier', 'MemberExpression'].includes(ast?.type) || /[\r\n]|<\?/.test(expression))) {
141
+ unsupported.push(`Unsupported dynamic/multiline Alpine x-model at line ${line}`); continue;
142
+ }
143
+ if (directive === 'model' && node.attrs.some(attribute => [':type', 'x-bind:type', ':name', 'x-bind:name'].includes(attribute.name))) {
144
+ unsupported.push(`Dynamic input type/name for Alpine x-model at line ${line}`); continue;
145
+ }
146
+ const id = register ? register(name, `alpine:${directive}`, span.startOffset, span.endOffset) : String(statements.length);
147
+ statements.push({id, binding: name, syntax: `alpine:${directive}`, start: location(span.startOffset), end: location(span.endOffset)});
148
+ // Escape only inserted text, leaving the source's PHP and entities intact.
149
+ const encode = text => text.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll("'", '&#39;');
150
+ // Property paths are valid in both Alpine evaluators. A scope getter
151
+ // counts access and returns the evaluator's complete scope, including
152
+ // data providers, loop locals, event parameters and magic properties.
153
+ const propertyPath = ranges.reduceRight((text, [start, end]) => start >= from && end <= to
154
+ ? text.slice(0, start - from) + '0' + text.slice(end - from) : text, expression);
155
+ if (/^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)*$/.test(decodeHTMLAttribute(propertyPath))) {
156
+ scoped.push(id);
157
+ edits.push({offset: from, text: `__mtc_${templateId}_${id}.`});
158
+ if (directive === 'model' && node.attrs.some(attribute => attribute.name === 'type' && attribute.value === 'radio') && !node.attrs.some(attribute => attribute.name === 'name')) {
159
+ edits.push({offset: span.endOffset, text: ` name="${encode(decodeHTMLAttribute(expression))}"`});
160
+ }
161
+ continue;
162
+ }
163
+ const counter = hit(templateId, id);
164
+ let prefix = `(${counter},(`, suffix = '))';
165
+ if (kind === 'body') {
166
+ prefix = `${counter};`; suffix = '';
167
+ }
168
+ if (directive === 'model') {
169
+ // Keep an assignable member expression: Alpine compiles both a
170
+ // getter and an assignment, even when a model's value is an object.
171
+ if (node.attrs.some(attribute => attribute.name === 'type' && attribute.value === 'radio') && !node.attrs.some(attribute => attribute.name === 'name')) {
172
+ edits.push({offset: span.endOffset, text: ` name="${encode(decodeHTMLAttribute(expression))}"`});
173
+ }
174
+ const parameter = `__mtcValue_${templateId}`;
175
+ prefix = `({get value(){${counter};return (`;
176
+ const suffixStart = `)},set value(${parameter}){`;
177
+ edits.push({offset: from, text: encode(prefix)});
178
+ edits.push({offset: to, text: encode(suffixStart) + expression + encode(`=${parameter}}}).value`)});
179
+ } else {
180
+ edits.push({offset: from, text: encode(prefix)}, {offset: to, text: encode(suffix)});
181
+ }
182
+ }
183
+ if (scoped.length) {
184
+ if (node.attrs.some(attribute => attribute.name === 'x-mtc')) throw new Error('The Alpine directive x-mtc is reserved for template coverage');
185
+ // A marker inside a PHP-conditional attribute can disappear while
186
+ // other bindings on this element still need their runtime scope.
187
+ const start = node.sourceCodeLocation.startTag.startOffset;
188
+ const markerOffset = start + /^<[^\s/>]+/.exec(masked.slice(start))[0].length;
189
+ edits.push({offset: markerOffset, text: ` x-mtc="${templateId}:${scoped.join(',')}"`});
190
+ }
191
+ if (!['script', 'style', 'textarea'].includes(node.tagName)) {
192
+ for (const child of node.childNodes || []) visit(child);
193
+ if (node.content) visit(node.content);
194
+ }
195
+ };
196
+ visit(tree);
197
+ if (edit) for (const insertion of edits) edit(insertion.offset, insertion.text);
198
+ let content = source;
199
+ for (const edit of edits.sort((a, b) => b.offset - a.offset)) content = content.slice(0, edit.offset) + edit.text + content.slice(edit.offset);
200
+ return {statements, content, engines: ['alpine'], unsupported};
201
+ }
202
+
203
+ module.exports = {analyzeAlpine, maskPhp};
@@ -0,0 +1,18 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+
10
+ // Build the same small CommonJS runtime used by Cypress into one init script.
11
+ // No parser, Node dependency or external bundler is shipped to the browser.
12
+ function browserSource() {
13
+ const files = ['engines-runtime', 'execution', 'browser'];
14
+ const modules = files.map(name => `${JSON.stringify(`./${name}`)}: function(module, exports, require) {\n${fs.readFileSync(path.join(__dirname, `${name}.js`), 'utf8')}\n}`);
15
+ return `(() => { const modules = {${modules.join(',')}}; const cache = {}; function require(name) { if (!cache[name]) { const module = cache[name] = {exports:{}}; modules[name](module, module.exports, require); } return cache[name].exports; } return require('./browser'); })()`;
16
+ }
17
+
18
+ module.exports = { browserSource };
package/lib/browser.js ADDED
@@ -0,0 +1,87 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ // Observe without dynamic code generation so strict CSP remains enforced.
8
+ function collectTemplates(win, onHit, onReference) {
9
+ const seen = new WeakSet();
10
+ const pattern = /^mtc:([a-f0-9]{32})$/;
11
+ const references = new Set();
12
+
13
+ function inspectScripts(root) {
14
+ if (!onReference) return;
15
+ const scripts = root.nodeType === 1 && root.localName === 'script' ? [root] : [];
16
+ if (root.querySelectorAll) for (const script of root.querySelectorAll('script')) scripts.push(script);
17
+ for (const script of scripts) {
18
+ for (const match of script.textContent.matchAll(/\/\*mtc-ref:([a-f0-9]{32}):(script:\d+:g:\d+):([a-f0-9]+)\*\//g)) {
19
+ if (references.has(match[0])) continue;
20
+ const text = match[3].replace(/../g, hex => String.fromCharCode(parseInt(hex, 16)));
21
+ const info = JSON.parse(text);
22
+ references.add(match[0]);
23
+ onReference({template: match[1], fragment: match[2], targets: info.targets, empty: info.empty});
24
+ }
25
+ }
26
+ }
27
+
28
+ function inspect(node) {
29
+ if (node.nodeType !== 8 || seen.has(node)) return;
30
+ const match = pattern.exec(node.nodeValue);
31
+ if (match) {
32
+ seen.add(node);
33
+ onHit(match[1]);
34
+ }
35
+ }
36
+
37
+ function scan(root) {
38
+ inspectScripts(root.nodeType === 3 ? root.parentNode || root : root);
39
+ inspect(root);
40
+ const walker = win.document.createTreeWalker(root, win.NodeFilter.SHOW_COMMENT);
41
+ let comment;
42
+ while ((comment = walker.nextNode())) inspect(comment);
43
+ }
44
+
45
+ function process(records) {
46
+ for (const record of records) {
47
+ for (const node of record.addedNodes) {
48
+ // A subtree may already be removed by this callback. The mutation
49
+ // still proves insertion into the observed document during this turn.
50
+ scan(node);
51
+ }
52
+ }
53
+ }
54
+
55
+ const observer = new win.MutationObserver(process);
56
+ observer.observe(win.document, { childList: true, subtree: true });
57
+ scan(win.document);
58
+ return {
59
+ flush() { process(observer.takeRecords()); },
60
+ disconnect() {
61
+ process(observer.takeRecords());
62
+ observer.disconnect();
63
+ }
64
+ };
65
+ }
66
+
67
+ /** Observe source markers in the application document, never detached template caches. */
68
+ function observeTemplates(win, onHit, onReference) {
69
+ if (win.Function === Function) return collectTemplates(win, onHit, onReference);
70
+ // Keep DOM callbacks in the application's realm. Cross-window traversal can
71
+ // otherwise give Magento Admin elements prototypes from the Cypress frame.
72
+ // A nonce-authorized script works under strict CSP without dynamic eval.
73
+ const script = win.document.createElement('script');
74
+ const nonce = win.document.currentScript?.nonce || win.document.querySelector('script[nonce]')?.nonce;
75
+ if (nonce) script.nonce = nonce;
76
+ const key = '__mtcObserve_' + Math.random().toString(36).slice(2);
77
+ script.textContent = `window[${JSON.stringify(key)}] = (${collectTemplates.toString()});`;
78
+ let collect;
79
+ try {
80
+ (win.document.head || win.document.documentElement).appendChild(script);
81
+ collect = win[key];
82
+ } finally { script.remove(); delete win[key]; }
83
+ if (typeof collect !== 'function') throw new Error('Template coverage needs an authorized observer script. Preserve Cypress script nonces when using CSP.');
84
+ return collect(win, onHit, onReference);
85
+ }
86
+
87
+ module.exports = { observeTemplates, ...require('./execution') };
@@ -0,0 +1,8 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ // Kept separate from Node-only parsers so Cypress does not bundle Acorn/HTML parsers.
8
+ module.exports = { helper: '__mtcTemplateHit' };
package/lib/engines.js ADDED
@@ -0,0 +1,129 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ const { parse } = require('acorn');
8
+
9
+ const engines = ['auto', 'knockout', 'underscore', 'jquery-tmpl', 'literal', 'alpine', 'html'];
10
+ const { helper } = require('./engines-runtime');
11
+ const hit = (template, statement) =>
12
+ `typeof window.${helper}==="function"&&window.${helper}("${template}","${statement}")`;
13
+
14
+ function detectEngine(source) {
15
+ if (/<%[\s\S]*?%>/.test(source)) return 'underscore';
16
+ if (/\{\{\/?(?:if|else|each|tmpl|wrap|html|=|!)(?:\s|\(|\}\})/.test(source)) return 'jquery-tmpl';
17
+ if (/\$\{/.test(source)) return /\$\{\s*\$\s*[.[]/.test(source) ? 'literal' : 'jquery-tmpl';
18
+ if (/\s(?:x-(?:data|text|html|show|if|for|on|bind|model|init)|[@:][\w-]+)[\w:.-]*\s*=/.test(source)) return 'alpine';
19
+ return 'knockout';
20
+ }
21
+
22
+ // Build a JS syntax tree across <% %> boundaries. Literal markup is represented
23
+ // by empty statements; only expressions mapped to original code can get hits.
24
+ function underscore(source, add, edit) {
25
+ let program = '', cursor = 0;
26
+ const spans = [], interpolations = new Map();
27
+ const append = (code, offset) => {
28
+ const start = program.length;
29
+ program += code;
30
+ spans.push({ start, end: program.length, offset });
31
+ return start;
32
+ };
33
+ const tokens = [...source.matchAll(/<%([=-]?)([\s\S]+?)%>/g)];
34
+ for (const token of tokens) {
35
+ if (token.index > cursor) program += '\n;\n';
36
+ const codeStart = token.index + 2 + token[1].length;
37
+ if (token[1]) {
38
+ program += '\n__mtcOutput(('; // synthetic; never emitted into the template
39
+ const start = append(token[2], codeStart);
40
+ interpolations.set(start, { token, end: program.length });
41
+ program += '\n));\n';
42
+ } else {
43
+ program += '\n';
44
+ append(token[2], codeStart);
45
+ program += '\n';
46
+ }
47
+ cursor = token.index + token[0].length;
48
+ }
49
+ let ast;
50
+ try { ast = parse(program, { ecmaVersion: 'latest', allowReturnOutsideFunction: true }); }
51
+ catch (error) { throw new Error(`Cannot parse Underscore evaluation code: ${error.message}`); }
52
+ const offset = (position, end = false) => {
53
+ const span = spans.find(s => position >= s.start && (end ? position <= s.end : position < s.end));
54
+ return span ? span.offset + position - span.start : undefined;
55
+ };
56
+ const wrapped = new Set();
57
+ const wrap = (node, label, syntax = 'underscore:evaluate', start) => {
58
+ if (!node || wrapped.has(node)) return;
59
+ const a = offset(node.start), b = offset(node.end, true);
60
+ if (a === undefined || b === undefined) return;
61
+ wrapped.add(node);
62
+ const call = add(label, syntax, start ?? a, b);
63
+ edit(a, `(${call},(`);
64
+ edit(b, '))');
65
+ };
66
+ const visit = node => {
67
+ if (!node || typeof node.type !== 'string') return;
68
+ if (node.type === 'ExpressionStatement') {
69
+ const expression = node.expression;
70
+ if (expression.type === 'CallExpression' && expression.callee.name === '__mtcOutput') {
71
+ const argument = expression.arguments[0];
72
+ const interpolation = [...interpolations].find(([a, data]) => argument.start >= a && argument.end <= data.end)?.[1];
73
+ if (interpolation) {
74
+ wrap(argument, interpolation.token[1] === '-' ? 'escape' : 'interpolate',
75
+ `underscore:${interpolation.token[1] === '-' ? 'escape' : 'interpolate'}`, interpolation.token.index);
76
+ }
77
+ } else if (!node.directive) wrap(expression, 'evaluate');
78
+ }
79
+ if (node.type === 'VariableDeclarator') wrap(node.init, 'initialize');
80
+ if (['IfStatement', 'WhileStatement', 'DoWhileStatement', 'ForStatement', 'ConditionalExpression'].includes(node.type)) wrap(node.test, 'condition');
81
+ if (node.type === 'ForStatement') {
82
+ if (node.init?.type !== 'VariableDeclaration') wrap(node.init, 'initialize');
83
+ wrap(node.update, 'update');
84
+ }
85
+ if (['ForInStatement', 'ForOfStatement'].includes(node.type)) wrap(node.right, 'iterate');
86
+ if (['ReturnStatement', 'ThrowStatement'].includes(node.type)) wrap(node.argument, node.type === 'ReturnStatement' ? 'return' : 'throw');
87
+ if (node.type === 'SwitchStatement') wrap(node.discriminant, 'switch');
88
+ if (node.type === 'SwitchCase') wrap(node.test, 'case');
89
+ for (const [key, value] of Object.entries(node)) {
90
+ if (key === 'type') continue;
91
+ if (Array.isArray(value)) value.forEach(visit);
92
+ else if (value && typeof value === 'object') visit(value);
93
+ }
94
+ };
95
+ visit(ast);
96
+ }
97
+
98
+ // Follow the legacy engine's own token grammar. Counters are separate tags,
99
+ // leaving its function auto-invocation, null checks, escaping and item context intact.
100
+ function jquery(source, add, edit) {
101
+ const pattern = /\$\{([^}]*)\}|\{\{(\/?)(\w+|.)(?:\(((?:[^}]|}(?!}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^}]|}(?!}))*?)\))?\s*\}\}/g;
102
+ const supported = new Set(['if', 'else', 'each', 'tmpl', 'wrap', 'html', '=', '!']);
103
+ for (const match of source.matchAll(pattern)) {
104
+ const type = match[1] !== undefined ? '=' : match[3];
105
+ if (!supported.has(type)) throw new Error(`Unsupported jQuery template tag: ${type}`);
106
+ if (match[2] || type === '!') continue;
107
+ const call = add(type === '=' ? 'interpolate' : type, `jquery-tmpl:${type}`, match.index, match.index + match[0].length);
108
+ const marker = `{{mtc ${call}}}`;
109
+ // An else declaration belongs to its branch; preceding it would count
110
+ // execution of the previous branch and may make the generated JS invalid.
111
+ edit(type === 'else' ? match.index + match[0].length : match.index, marker);
112
+ }
113
+ }
114
+
115
+ function literal(source, add, edit) {
116
+ let ast;
117
+ try { ast = parse('`' + source + '`', { ecmaVersion: 'latest' }); }
118
+ catch (error) { throw new Error(`Cannot parse Magento template literal: ${error.message}. Use --engine for another template language.`); }
119
+ const template = ast.body[0]?.expression;
120
+ if (template?.type !== 'TemplateLiteral' || ast.body.length !== 1) throw new Error('Invalid Magento template literal');
121
+ for (const expression of template.expressions) {
122
+ const start = expression.start - 1, end = expression.end - 1;
123
+ const call = add('interpolate', 'literal:interpolate', start, end);
124
+ edit(start, `(${call},(`);
125
+ edit(end, '))');
126
+ }
127
+ }
128
+
129
+ module.exports = { engines, helper, hit, detectEngine, underscore, jquery, literal };
@@ -0,0 +1,141 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ const windows = new WeakMap();
8
+ const { helper } = require('./engines-runtime');
9
+
10
+ function installJqueryTemplates(jquery) {
11
+ if (!jquery?.tmpl?.tag) return false;
12
+ if (jquery.tmpl.tag.mtc && jquery.tmpl.tag.mtc.open !== '$1;') {
13
+ throw new Error('The jQuery template tag "mtc" is reserved for coverage');
14
+ }
15
+ jquery.tmpl.tag.mtc = { open: '$1;' };
16
+ return true;
17
+ }
18
+
19
+ /** Instrument accessors AFTER Knockout parses expressions and creates property writers. */
20
+ function installKnockout(ko, onHit) {
21
+ const provider = ko?.bindingProvider?.instance;
22
+ if (!provider || typeof provider.parseBindingsString !== 'function') return false;
23
+ const original = provider.parseBindingsString;
24
+ provider.parseBindingsString = function (source, context, node, options) {
25
+ const result = original.apply(this, arguments);
26
+ const markers = [...source.matchAll(/\/\*mtc_([a-f0-9]{32})_(\d+)_([a-f0-9]+)\*\//g)];
27
+ for (const [, template, statement, encoded] of markers) {
28
+ const binding = decodeURIComponent(encoded.replace(/../g, part => `%${part}`));
29
+ const key = binding === 'textinput' ? 'textInput' : binding;
30
+ if (!Object.hasOwn(result, key)) {
31
+ throw new Error(`Template coverage cannot track preprocessed binding: ${binding}`);
32
+ }
33
+ if (options?.valueAccessors) {
34
+ const accessor = result[key];
35
+ result[key] = function () {
36
+ onHit(template, statement);
37
+ return accessor.apply(this, arguments);
38
+ };
39
+ } else {
40
+ // getBindings() evaluates its values eagerly inside the original provider.
41
+ onHit(template, statement);
42
+ }
43
+ }
44
+ return result;
45
+ };
46
+ return true;
47
+ }
48
+
49
+ /** Register before Alpine starts; no eval or generated functions are required. */
50
+ function installAlpine(alpine, onHit) {
51
+ if (!alpine?.directive || !alpine?.addScopeToNode) return false;
52
+ alpine.directive('mtc', (element, {expression}, {cleanup}) => {
53
+ const match = /^([a-f0-9]{32}):([0-9,]+)$/.exec(expression);
54
+ if (!match) throw new Error('Invalid Alpine template coverage marker');
55
+ const template = match[1];
56
+ const scope = {};
57
+ for (const statement of match[2].split(',')) {
58
+ Object.defineProperty(scope, `__mtc_${template}_${statement}`, {
59
+ get() { onHit(template, statement); return this; }
60
+ });
61
+ }
62
+ cleanup(alpine.addScopeToNode(element, scope));
63
+ }).before('data');
64
+ return true;
65
+ }
66
+
67
+ /** Attach before RequireJS consumers receive Knockout; never require application modules ourselves. */
68
+ function observeExecution(win, onHit) {
69
+ let state = windows.get(win);
70
+ // WindowProxy identity can survive navigation while its document/globals change.
71
+ if (!state || state.document !== win.document) {
72
+ state = { previousHelper: state && win[helper] === state.helper, document: win.document, onHit, modules: new WeakSet(), loaders: new WeakSet() };
73
+ windows.set(win, state);
74
+ if (win[helper] !== undefined && !state.previousHelper) throw new Error(`Template coverage global already exists: ${helper}`);
75
+ Object.defineProperty(win, helper, { configurable: true, value(template, statement) {
76
+ state.onHit?.(template, statement);
77
+ } });
78
+ state.helper = win[helper];
79
+ const attach = module => {
80
+ installJqueryTemplates(module);
81
+ if (!module || (typeof module !== 'object' && typeof module !== 'function') || state.modules.has(module)) return;
82
+ if (installKnockout(module, (template, statement) => state.onHit?.(template, statement))) state.modules.add(module);
83
+ };
84
+ const loader = requirejs => {
85
+ if (typeof requirejs !== 'function' || state.loaders.has(requirejs)) return;
86
+ state.loaders.add(requirejs);
87
+ const wrap = callback => function (context, map) {
88
+ attach(context.defined[map.id]);
89
+ // Legacy plugins may return undefined and instead extend jQuery.
90
+ attach(context.defined.jquery);
91
+ attach(win.jQuery);
92
+ return callback?.apply(this, arguments);
93
+ };
94
+ let current = wrap(requirejs.onResourceLoad);
95
+ Object.defineProperty(requirejs, 'onResourceLoad', {
96
+ configurable: true, enumerable: true,
97
+ get() { return current; },
98
+ set(value) { if (value !== current) current = wrap(value); }
99
+ });
100
+ for (const context of Object.values(requirejs.s?.contexts || {})) {
101
+ for (const module of Object.values(context.defined)) attach(module);
102
+ }
103
+ };
104
+ const watch = (key, consume) => {
105
+ let value = win[key];
106
+ consume(value);
107
+ const descriptor = Object.getOwnPropertyDescriptor(win, key);
108
+ if (descriptor && !descriptor.configurable) return;
109
+ Object.defineProperty(win, key, {
110
+ configurable: true, enumerable: descriptor?.enumerable ?? true,
111
+ // UMD engines may publish an empty object, then populate it in place.
112
+ // Attach on its first consumer read as well as assignment.
113
+ get() { consume(value); return value; },
114
+ set(next) { value = next; consume(next); }
115
+ });
116
+ };
117
+ const alpine = module => {
118
+ if (!module || state.modules.has(module)) return;
119
+ if (installAlpine(module, (template, statement) => state.onHit?.(template, statement))) state.modules.add(module);
120
+ };
121
+ watch('Alpine', alpine);
122
+ win.document.addEventListener('alpine:init', () => alpine(win.Alpine));
123
+ watch('requirejs', loader);
124
+ watch('ko', attach);
125
+ watch('jQuery', attach);
126
+ }
127
+ if (win[helper] !== state.helper) {
128
+ if (win[helper] !== undefined) {
129
+ throw new Error(`Template coverage global already exists: ${helper}`);
130
+ }
131
+
132
+ Object.defineProperty(win, helper, {
133
+ configurable: true,
134
+ value: state.helper
135
+ });
136
+ }
137
+ state.onHit = onHit;
138
+ return { disconnect() { if (state.onHit === onHit) state.onHit = undefined; } };
139
+ }
140
+
141
+ module.exports = { installAlpine, installKnockout, installJqueryTemplates, observeExecution };
@@ -0,0 +1,23 @@
1
+ // SPDX-FileCopyrightText: MageLens
2
+ // SPDX-License-Identifier: MIT
3
+ // License: see LICENSE in the repository root.
4
+
5
+ 'use strict';
6
+
7
+ const PhpParser = require('php-parser');
8
+
9
+ // Evaluate the original expression once, in its original PHP scope. Only the
10
+ // resulting string enters this closure; no application variables are captured.
11
+ function traceGeneratedOutput(source, template, fragment) {
12
+ const ast = new PhpParser({ast: {withPositions: true}}).parseCode(source);
13
+ const output = ast.children[0];
14
+ if (ast.children.length !== 1 || output.kind !== 'echo' || output.expressions.length !== 1) return null;
15
+ const expression = output.expressions[0];
16
+ const prefix = `(static function ($__mtcOutput) { $__mtcOutput = (string) $__mtcOutput; ` +
17
+ `preg_match_all('/__mtcTemplateHit\\("([a-f0-9]{32})"/', $__mtcOutput, $__mtcMatches); ` +
18
+ `$__mtcInfo = array('targets' => array_values(array_unique($__mtcMatches[1])), 'empty' => trim($__mtcOutput) === ''); ` +
19
+ `return '/*mtc-ref:${template}:${fragment}:' . bin2hex(json_encode($__mtcInfo)) . '*/' . $__mtcOutput; })(`;
20
+ return source.slice(0, expression.loc.start.offset) + prefix + source.slice(expression.loc.start.offset, expression.loc.end.offset) + ')' + source.slice(expression.loc.end.offset);
21
+ }
22
+
23
+ module.exports = {traceGeneratedOutput};