-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathparser.ts
418 lines (370 loc) · 12.2 KB
/
parser.ts
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
import * as babelParser from '@babel/parser';
import * as path from 'path';
import * as fs from 'fs';
import { getNonce } from './getNonce';
import { Tree } from './types/Tree';
import { ImportObj } from './types/ImportObj';
import { File } from '@babel/types';
export class Parser {
entryFile: string;
tree: Tree | undefined;
constructor(filePath: string) {
// Fix when selecting files in wsl file system
this.entryFile = filePath;
if (process.platform === 'linux' && this.entryFile.includes('wsl$')) {
this.entryFile = path.resolve(
filePath.split(path.win32.sep).join(path.posix.sep)
);
this.entryFile = '/' + this.entryFile.split('/').slice(3).join('/');
// Fix for when running wsl but selecting files held on windows file system
} else if (
process.platform === 'linux' &&
/[a-zA-Z]/.test(this.entryFile[0])
) {
const root = `/mnt/${this.entryFile[0].toLowerCase()}`;
this.entryFile = path.join(
root,
filePath.split(path.win32.sep).slice(1).join(path.posix.sep)
);
}
this.tree = undefined;
// Break down and reasemble given filePath safely for any OS using path?
}
// Public method to generate component tree based on current entryFile
public parse(): Tree {
// Create root Tree node
const root = {
id: getNonce(),
name: path.basename(this.entryFile).replace(/\.(t|j)sx?$/, ''),
fileName: path.basename(this.entryFile),
filePath: this.entryFile,
importPath: '/', // this.entryFile here breaks windows file path on root e.g. C:\\ is detected as third party
expanded: false,
depth: 0,
count: 1,
thirdParty: false,
reactRouter: false,
reduxConnect: false,
children: [],
parentList: [],
props: {},
error: '',
};
this.tree = root;
this.parser(root);
return this.tree;
}
public getTree(): Tree {
return this.tree!;
}
// Set Sapling Parser with a specific Data Tree (from workspace state)
public setTree(tree: Tree): void {
this.entryFile = tree.filePath;
this.tree = tree;
}
public updateTree(filePath: string): Tree {
let children: any[] = [];
const getChildNodes = (node: Tree): void => {
const { depth, filePath, expanded } = node;
children.push({ depth, filePath, expanded });
};
const matchExpand = (node: Tree): void => {
for (let i = 0; i < children.length; i += 1) {
const oldNode = children[i];
if (
oldNode.depth === node.depth &&
oldNode.filePath === node.filePath &&
oldNode.expanded
) {
node.expanded = true;
}
}
};
const callback = (node: Tree): void => {
if (node.filePath === filePath) {
node.children.forEach((child) => {
this.traverseTree(getChildNodes, child);
});
const newNode = this.parser(node);
this.traverseTree(matchExpand, newNode);
children = [];
}
};
this.traverseTree(callback, this.tree);
return this.tree!;
}
// Traverses the tree and changes expanded property of node whose id matches provided id
public toggleNode(id: string, expanded: boolean): Tree {
const callback = (node: { id: string; expanded: boolean }) => {
if (node.id === id) {
node.expanded = expanded;
}
};
this.traverseTree(callback, this.tree);
return this.tree!;
}
// Traverses all nodes of current component tree and applies callback to each node
private traverseTree(
callback: Function,
node: Tree | undefined = this.tree
): void {
if (!node) {
return;
}
callback(node);
node.children.forEach((childNode) => {
this.traverseTree(callback, childNode);
});
}
// Recursively builds the React component tree structure starting from root node
private parser(componentTree: Tree): Tree | undefined {
// If import is a node module, do not parse any deeper
if (!['\\', '/', '.'].includes(componentTree.importPath[0])) {
componentTree.thirdParty = true;
if (
componentTree.fileName === 'react-router-dom' ||
componentTree.fileName === 'react-router'
) {
componentTree.reactRouter = true;
}
return;
}
// Check that file has valid fileName/Path, if not found, add error to node and halt
const fileName = this.getFileName(componentTree);
if (!fileName) {
componentTree.error = 'File not found.';
return;
}
// If current node recursively calls itself, do not parse any deeper:
if (componentTree.parentList.includes(componentTree.filePath)) {
return;
}
// Create abstract syntax tree of current component tree file
let ast: babelParser.ParseResult<File>;
try {
ast = babelParser.parse(
fs.readFileSync(path.resolve(componentTree.filePath), 'utf-8'),
{
sourceType: 'module',
tokens: true,
plugins: ['jsx', 'typescript'],
}
);
} catch (err) {
componentTree.error = 'Error while processing this file/node';
return componentTree;
}
// Find imports in the current file, then find child components in the current file
const imports = this.getImports(ast.program.body);
// Get any JSX Children of current file:
if (ast.tokens) {
componentTree.children = this.getJSXChildren(
ast.tokens,
imports,
componentTree
);
}
// Check if current node is connected to the Redux store
if (ast.tokens) {
componentTree.reduxConnect = this.checkForRedux(ast.tokens, imports);
}
// Recursively parse all child components
componentTree.children.forEach((child) => this.parser(child));
return componentTree;
}
// Finds files where import string does not include a file extension
private getFileName(componentTree: Tree): string | undefined {
const ext = path.extname(componentTree.filePath);
let fileName: string | undefined = componentTree.fileName;
if (!ext) {
// Try and find file extension that exists in directory:
const fileArray = fs.readdirSync(path.dirname(componentTree.filePath));
const regEx = new RegExp(`${componentTree.fileName}.(j|t)sx?$`);
fileName = fileArray.find((fileStr) => fileStr.match(regEx));
fileName ? (componentTree.filePath += path.extname(fileName)) : null;
}
return fileName;
}
// Extracts Imports from current file
// const Page1 = lazy(() => import('./page1')); -> is parsed as 'ImportDeclaration'
// import Page2 from './page2'; -> is parsed as 'VariableDeclaration'
private getImports(body: { [key: string]: any }[]): ImportObj {
const bodyImports = body.filter(
(item) => item.type === 'ImportDeclaration' || 'VariableDeclaration'
);
// console.log('bodyImports are: ', bodyImports);
return bodyImports.reduce((accum, curr) => {
// Import Declarations:
if (curr.type === 'ImportDeclaration') {
curr.specifiers.forEach(
(i: {
local: { name: string | number };
imported: { name: any };
}) => {
accum[i.local.name] = {
importPath: curr.source.value,
importName: i.imported ? i.imported.name : i.local.name,
};
}
);
}
// Imports Inside Variable Declarations: // Not easy to deal with nested objects
if (curr.type === 'VariableDeclaration') {
const importPath = this.findVarDecImports(curr.declarations[0]);
if (importPath) {
const importName = curr.declarations[0].id.name;
accum[curr.declarations[0].id.name] = {
importPath,
importName,
};
}
}
return accum;
}, {});
}
// Recursive helper method to find import path in Variable Declaration
private findVarDecImports(ast: { [key: string]: any }): string | boolean {
// Base Case, find import path in variable declaration and return it,
if (ast.hasOwnProperty('callee') && ast.callee.type === 'Import') {
return ast.arguments[0].value;
}
// Otherwise look for imports in any other non null/undefined objects in the tree:
for (let key in ast) {
if (ast.hasOwnProperty(key) && typeof ast[key] === 'object' && ast[key]) {
const importPath = this.findVarDecImports(ast[key]);
if (importPath) {
return importPath;
}
}
}
return false;
}
// Finds JSX React Components in current file
private getJSXChildren(
astTokens: any[],
importsObj: ImportObj,
parentNode: Tree
): Tree[] {
let childNodes: { [key: string]: Tree } = {};
let props: { [key: string]: boolean } = {};
let token: { [key: string]: any };
for (let i = 0; i < astTokens.length; i++) {
// Case for finding JSX tags eg <App .../>
if (
astTokens[i].type.label === 'jsxTagStart' &&
astTokens[i + 1].type.label === 'jsxName' &&
importsObj[astTokens[i + 1].value]
) {
token = astTokens[i + 1];
props = this.getJSXProps(astTokens, i + 2);
childNodes = this.getChildNodes(
importsObj,
token,
props,
parentNode,
childNodes
);
// Case for finding components passed in as props e.g. <Route component={App} />
} else if (
astTokens[i].type.label === 'jsxName' &&
(astTokens[i].value === 'component' ||
astTokens[i].value === 'children') &&
importsObj[astTokens[i + 3].value]
) {
token = astTokens[i + 3];
childNodes = this.getChildNodes(
importsObj,
token,
props,
parentNode,
childNodes
);
}
}
return Object.values(childNodes);
}
private getChildNodes(
imports: ImportObj,
astToken: { [key: string]: any },
props: { [key: string]: boolean },
parent: Tree,
children: { [key: string]: Tree }
): { [key: string]: Tree } {
if (children[astToken.value]) {
children[astToken.value].count += 1;
children[astToken.value].props = {
...children[astToken.value].props,
...props,
};
} else {
// Add tree node to childNodes if one does not exist
children[astToken.value] = {
id: getNonce(),
name: imports[astToken.value]['importName'],
fileName: path.basename(imports[astToken.value]['importPath']),
filePath: path.resolve(
path.dirname(parent.filePath),
imports[astToken.value]['importPath']
),
importPath: imports[astToken.value]['importPath'],
expanded: false,
depth: parent.depth + 1,
thirdParty: false,
reactRouter: false,
reduxConnect: false,
count: 1,
props: props,
children: [],
parentList: [parent.filePath].concat(parent.parentList),
error: '',
};
}
return children;
}
// Extracts prop names from a JSX element
private getJSXProps(
astTokens: { [key: string]: any }[],
j: number
): { [key: string]: boolean } {
const props: any = {};
while (astTokens[j].type.label !== 'jsxTagEnd') {
if (
astTokens[j].type.label === 'jsxName' &&
astTokens[j + 1].value === '='
) {
props[astTokens[j].value] = true;
}
j += 1;
}
return props;
}
// Checks if current Node is connected to React-Redux Store
private checkForRedux(astTokens: any[], importsObj: ImportObj): boolean {
// Check that react-redux is imported in this file (and we have a connect method or otherwise)
let reduxImported = false;
let connectAlias;
Object.keys(importsObj).forEach((key) => {
if (
importsObj[key].importPath === 'react-redux' &&
importsObj[key].importName === 'connect'
) {
reduxImported = true;
connectAlias = key;
}
});
if (!reduxImported) {
return false;
}
// Check that connect method is invoked and exported in the file
for (let i = 0; i < astTokens.length; i += 1) {
if (
astTokens[i].type.label === 'export' &&
astTokens[i + 1].type.label === 'default' &&
astTokens[i + 2].value === connectAlias
) {
return true;
}
}
return false;
}
}