-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparser.js
More file actions
273 lines (239 loc) · 8.86 KB
/
parser.js
File metadata and controls
273 lines (239 loc) · 8.86 KB
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
/**
* @fileoverview AST parsing and walking module
* @module analyze/javascript/parser
*/
const fs = require('fs');
const acorn = require('acorn');
const jsx = require('acorn-jsx');
const walk = require('acorn-walk');
const { extend } = require('acorn-jsx-walk');
const { PARSER_OPTIONS, NODE_TYPES } = require('./constants');
const { detectAnalyticsSource } = require('./detectors');
const { extractEventData, processEventData } = require('./extractors');
const { findWrappingFunction } = require('./utils/function-finder');
const { collectImportedConstantStringMap } = require('./utils/import-resolver');
// Extend walker to support JSX
extend(walk.base);
// Configure parser with JSX support
const parser = acorn.Parser.extend(jsx());
/**
* Error thrown when file cannot be read
*/
class FileReadError extends Error {
constructor(filePath, originalError) {
super(`Failed to read file: ${filePath}`);
this.name = 'FileReadError';
this.filePath = filePath;
this.originalError = originalError;
}
}
/**
* Error thrown when file cannot be parsed
*/
class ParseError extends Error {
constructor(filePath, originalError) {
super(`Failed to parse file: ${filePath}`);
this.name = 'ParseError';
this.filePath = filePath;
this.originalError = originalError;
}
}
/**
* Parses a JavaScript file and returns its AST
* @param {string} filePath - Path to the JavaScript file
* @returns {Object} Parsed AST
* @throws {FileReadError} If file cannot be read
* @throws {ParseError} If file cannot be parsed
*/
function parseFile(filePath) {
let code;
try {
code = fs.readFileSync(filePath, 'utf8');
} catch (error) {
throw new FileReadError(filePath, error);
}
try {
return parser.parse(code, PARSER_OPTIONS);
} catch (error) {
throw new ParseError(filePath, error);
}
}
// ---------------------------------------------
// Helper – custom function matcher
// ---------------------------------------------
/**
* Determines whether a CallExpression node matches the provided custom function configuration.
* Supports both simple identifiers (e.g. myTrack), dot-separated members (e.g. Custom.track),
* and method-as-event patterns (e.g. eventCalls.EVENT_NAME).
* The logic mirrors isCustomFunction from detectors/analytics-source.js but is kept local to avoid
* circular dependencies.
* @param {Object} node – CallExpression AST node
* @param {Object} customConfig – Custom function configuration object
* @returns {boolean}
*/
function nodeMatchesCustomFunction(node, customConfig) {
if (!customConfig || !node.callee) return false;
// Handle method-as-event pattern
if (customConfig.isMethodAsEvent && customConfig.objectName) {
if (node.callee.type !== NODE_TYPES.MEMBER_EXPRESSION) {
return false;
}
const objectNode = node.callee.object;
if (objectNode.type !== NODE_TYPES.IDENTIFIER) {
return false;
}
return objectNode.name === customConfig.objectName;
}
// Handle standard custom function patterns
const fnName = customConfig.functionName;
if (!fnName) return false;
// Support chained calls in function name by stripping trailing parens from each segment
const parts = fnName.split('.').map(p => p.replace(/\(\s*\)$/, ''));
// Simple identifier case
if (parts.length === 1) {
return node.callee.type === NODE_TYPES.IDENTIFIER && node.callee.name === parts[0];
}
// Allow MemberExpression and CallExpression within the chain (e.g., getService().track)
let currentNode = node.callee;
let idx = parts.length - 1;
while (currentNode && idx >= 0) {
const expected = parts[idx];
if (currentNode.type === NODE_TYPES.MEMBER_EXPRESSION) {
if (
currentNode.property.type !== NODE_TYPES.IDENTIFIER ||
currentNode.property.name !== expected
) {
return false;
}
// step to the object; do not decrement idx for call expressions yet
currentNode = currentNode.object;
idx -= 1;
continue;
}
if (currentNode.type === NODE_TYPES.CALL_EXPRESSION) {
// descend into the callee of the call without consuming a part
currentNode = currentNode.callee;
continue;
}
if (currentNode.type === NODE_TYPES.IDENTIFIER) {
return idx === 0 && currentNode.name === expected;
}
return false;
}
return false;
}
// -----------------------------------------------------------------------------
// Utility – collect constants defined as plain objects or Object.freeze({...})
// -----------------------------------------------------------------------------
function collectConstantStringMap(ast) {
const map = {};
walk.simple(ast, {
VariableDeclaration(node) {
// Only consider const declarations
if (node.kind !== 'const') return;
node.declarations.forEach(decl => {
if (decl.id.type !== NODE_TYPES.IDENTIFIER || !decl.init) return;
const name = decl.id.name;
let objLiteral = null;
if (decl.init.type === NODE_TYPES.OBJECT_EXPRESSION) {
objLiteral = decl.init;
} else if (decl.init.type === NODE_TYPES.CALL_EXPRESSION) {
// Check for Object.freeze({...})
const callee = decl.init.callee;
if (
callee &&
callee.type === NODE_TYPES.MEMBER_EXPRESSION &&
callee.object.type === NODE_TYPES.IDENTIFIER &&
callee.object.name === 'Object' &&
callee.property.type === NODE_TYPES.IDENTIFIER &&
callee.property.name === 'freeze' &&
decl.init.arguments.length > 0 &&
decl.init.arguments[0].type === NODE_TYPES.OBJECT_EXPRESSION
) {
objLiteral = decl.init.arguments[0];
}
}
if (objLiteral) {
map[name] = {};
objLiteral.properties.forEach(prop => {
if (!prop.key || !prop.value) return;
const keyName = prop.key.name || prop.key.value;
if (prop.value.type === NODE_TYPES.LITERAL && typeof prop.value.value === 'string') {
map[name][keyName] = prop.value.value;
}
});
}
});
}
});
return map;
}
/**
* Walk the AST once and find tracking events for built-in providers plus any number of custom
* function configurations. This avoids the previous O(n * customConfigs) behaviour.
*
* @param {Object} ast – Parsed AST of the source file
* @param {string} filePath – Absolute/relative path to the source file
* @param {Object[]} [customConfigs=[]] – Array of parsed custom function configurations
* @returns {Array<Object>} – List of extracted tracking events
*/
function findTrackingEvents(ast, filePath, customConfigs = []) {
const events = [];
// Collect constant mappings once per file (locals + imported)
const constantMap = {
...collectConstantStringMap(ast),
...collectImportedConstantStringMap(filePath, ast)
};
walk.ancestor(ast, {
[NODE_TYPES.CALL_EXPRESSION]: (node, ancestors) => {
try {
let matchedCustomConfig = null;
// Attempt to match any custom function first to avoid mis-classifying built-in providers
if (Array.isArray(customConfigs) && customConfigs.length > 0) {
for (const cfg of customConfigs) {
if (cfg && nodeMatchesCustomFunction(node, cfg)) {
matchedCustomConfig = cfg;
break;
}
}
}
if (matchedCustomConfig) {
const event = extractTrackingEvent(node, ancestors, filePath, constantMap, matchedCustomConfig);
if (event) events.push(event);
} else {
const event = extractTrackingEvent(node, ancestors, filePath, constantMap, null);
if (event) events.push(event);
}
} catch (error) {
console.error(`Error processing node in ${filePath}:`, error.message);
}
}
});
return events;
}
/**
* Extracts tracking event from a CallExpression node
* @param {Object} node - CallExpression node
* @param {Array<Object>} ancestors - Ancestor nodes
* @param {string} filePath - File path
* @param {Object} constantMap - Constant string map
* @param {Object} [customConfig] - Custom function configuration object
* @returns {Object|null} Extracted event or null
*/
function extractTrackingEvent(node, ancestors, filePath, constantMap, customConfig) {
// Pass the full customConfig object (not just functionName) to support method-as-event patterns
const source = detectAnalyticsSource(node, customConfig || null);
if (source === 'unknown') {
return null;
}
const eventData = extractEventData(node, source, constantMap, customConfig);
const line = node.loc.start.line;
const functionName = findWrappingFunction(node, ancestors);
return processEventData(eventData, source, filePath, line, functionName, customConfig);
}
module.exports = {
parseFile,
findTrackingEvents,
FileReadError,
ParseError
};