This repository has been archived by the owner on Jun 20, 2023. It is now read-only.
/
FileAnalysis.ts
191 lines (156 loc) · 5.45 KB
/
FileAnalysis.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
import { ASTTraverse } from "./../ASTTraverse";
import { PrettyError } from "./../PrettyError";
import { File } from "../core/File";
import * as acorn from "acorn";
import { AutoImport } from "./plugins/AutoImport";
import { LanguageLevel } from "./plugins/LanguageLevel";
import { OwnVariable } from "./plugins/OwnVariable";
import { OwnBundle } from "./plugins/OwnBundle";
import { ImportDeclaration } from "./plugins/ImportDeclaration";
import { DynamicImportStatement } from "./plugins/DynamicImportStatement";
import { escapeRegExp } from '../Utils';
require("acorn-jsx/inject")(acorn);
require("./acorn-ext/obj-rest-spread")(acorn);
export interface TraversalPlugin {
onNode(file: File, node: any, parent: any): void
onEnd(file: File): void
}
const plugins: TraversalPlugin[] = [AutoImport, OwnVariable, OwnBundle, ImportDeclaration, DynamicImportStatement, LanguageLevel];
export function acornParse(contents, options?: any): any {
return acorn.parse(contents, {
...options || {}, ...{
sourceType: "module",
tolerant: true,
locations: true,
ranges: true,
ecmaVersion: '2018',
plugins: {
jsx: true, objRestSpread: true
},
jsx: { allowNamespacedObjects: true },
},
});
}
/**
* Makes static analysis on the code
* Gets require statements (es5 and es6)
*
* Adds additional injections (if needed)
*
* @export
* @class FileAST
*/
export class FileAnalysis {
public ast: any;
private wasAnalysed = false;
public skipAnalysis = false;
public bannedImports = {};
public nativeImports = {};
public fuseBoxMainFile;
public requiresRegeneration = false;
public statementReplacement = new Set<{ from: string, to: string }>();
public requiresTranspilation = false;
public fuseBoxVariable = "FuseBox";
public dependencies: string[] = [];
constructor(public file: File) { }
public astIsLoaded(): boolean {
return this.ast !== undefined;
}
/**
* Loads an AST
*
* @param {*} ast
*
* @memberOf FileAnalysis
*/
public loadAst(ast: any) {
this.ast = ast;
}
public skip() {
this.skipAnalysis = true;
}
/**
*
*
* @private
*
* @memberOf FileAST
*/
public parseUsingAcorn(options?: any) {
try {
this.ast = acornParse(this.file.contents, options);
} catch (err) {
return PrettyError.errorWithContents(err, this.file);
}
}
public registerReplacement(rawRequireStatement: string, targetReplacement: string) {
if( rawRequireStatement !== targetReplacement ){
this.statementReplacement.add({ from: rawRequireStatement, to: targetReplacement })
}
}
public handleAliasReplacement(requireStatement: string): string {
if (!this.file.context.experimentalAliasEnabled) {
return requireStatement;
}
// enable aliases only for the current project
// if (this.file.collection.name !== this.file.context.defaultPackageName) {
// return requireStatement;
// }
const aliasCollection = this.file.context.aliasCollection;
aliasCollection.forEach(props => {
if (props.expr.test(requireStatement)) {
requireStatement = requireStatement.replace(props.expr, `${props.replacement}$2`);
// only if we need it
this.requiresRegeneration = true;
}
});
return requireStatement;
}
public addDependency(name: string) {
this.dependencies.push(name);
}
public resetDependencies() {
this.dependencies = [];
}
public nodeIsString(node) {
return node.type === "Literal" || node.type === "StringLiteral";
}
public replaceAliases(collection : Set<{ from: string, to: string }>){
collection.forEach(item => {
const regExp =
new RegExp(`(require|\\$fsmp\\$)\\(('|")${escapeRegExp(item.from)}('|")\\)`)
this.file.contents = this.file.contents.replace(regExp, `$1("${item.to}")`)
});
}
public analyze(traversalOptions?: { plugins: TraversalPlugin[] }) {
// We don't want to make analysis 2 times
if (this.wasAnalysed || this.skipAnalysis) {
return;
}
// setting es6 module
// to transpile it with typescrip
if (this.file.collection && this.file.collection.info && this.file.collection.info.jsNext) {
this.file.es6module = true;
}
let traversalPlugins = plugins;
if (traversalOptions && Array.isArray(traversalOptions.plugins)) {
traversalPlugins = plugins.concat(traversalOptions.plugins)
}
ASTTraverse.traverse(this.ast, {
pre: (node, parent, prop, idx) =>
traversalPlugins.forEach(plugin => plugin.onNode(this.file, node, parent)),
});
traversalPlugins.forEach(plugin => plugin.onEnd(this.file));
this.wasAnalysed = true;
// regenerate content
this.replaceAliases(this.statementReplacement);
if (this.requiresRegeneration) {
this.file.contents = this.file.context.generateCode(this.ast, {
});
}
if (this.requiresTranspilation) {
let result = this.file.transpileUsingTypescript();
this.file.contents = result.outputText;
}
}
}