-
Notifications
You must be signed in to change notification settings - Fork 12k
/
replace_resources.ts
341 lines (296 loc) · 9.79 KB
/
replace_resources.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
const inlineDataLoaderPath = require.resolve('../inline-data-loader');
export function replaceResources(
shouldTransform: (fileName: string) => boolean,
getTypeChecker: () => ts.TypeChecker,
directTemplateLoading = false,
inlineStyleMimeType?: string,
inlineStyleFileExtension?: string,
): ts.TransformerFactory<ts.SourceFile> {
if (inlineStyleMimeType && !/^text\/[-.\w]+$/.test(inlineStyleMimeType)) {
throw new Error('Invalid inline style MIME type.');
}
return (context: ts.TransformationContext) => {
const typeChecker = getTypeChecker();
const resourceImportDeclarations: ts.ImportDeclaration[] = [];
const moduleKind = context.getCompilerOptions().module;
const nodeFactory = context.factory;
const visitNode: ts.Visitor = (node: ts.Node) => {
if (ts.isClassDeclaration(node)) {
const decorators = ts.visitNodes(node.decorators, (node) =>
ts.isDecorator(node)
? visitDecorator(
nodeFactory,
node,
typeChecker,
directTemplateLoading,
resourceImportDeclarations,
moduleKind,
inlineStyleMimeType,
inlineStyleFileExtension,
)
: node,
);
return nodeFactory.updateClassDeclaration(
node,
decorators,
node.modifiers,
node.name,
node.typeParameters,
node.heritageClauses,
node.members,
);
}
return ts.visitEachChild(node, visitNode, context);
};
return (sourceFile: ts.SourceFile) => {
if (!shouldTransform(sourceFile.fileName)) {
return sourceFile;
}
const updatedSourceFile = ts.visitNode(sourceFile, visitNode);
if (resourceImportDeclarations.length) {
// Add resource imports
return context.factory.updateSourceFile(
updatedSourceFile,
ts.setTextRange(
context.factory.createNodeArray([
...resourceImportDeclarations,
...updatedSourceFile.statements,
]),
updatedSourceFile.statements,
),
);
}
return updatedSourceFile;
};
};
}
function visitDecorator(
nodeFactory: ts.NodeFactory,
node: ts.Decorator,
typeChecker: ts.TypeChecker,
directTemplateLoading: boolean,
resourceImportDeclarations: ts.ImportDeclaration[],
moduleKind?: ts.ModuleKind,
inlineStyleMimeType?: string,
inlineStyleFileExtension?: string,
): ts.Decorator {
if (!isComponentDecorator(node, typeChecker)) {
return node;
}
if (!ts.isCallExpression(node.expression)) {
return node;
}
const decoratorFactory = node.expression;
const args = decoratorFactory.arguments;
if (args.length !== 1 || !ts.isObjectLiteralExpression(args[0])) {
// Unsupported component metadata
return node;
}
const objectExpression = args[0] as ts.ObjectLiteralExpression;
const styleReplacements: ts.Expression[] = [];
// visit all properties
let properties = ts.visitNodes(objectExpression.properties, (node) =>
ts.isObjectLiteralElementLike(node)
? visitComponentMetadata(
nodeFactory,
node,
styleReplacements,
directTemplateLoading,
resourceImportDeclarations,
moduleKind,
inlineStyleMimeType,
inlineStyleFileExtension,
)
: node,
);
// replace properties with updated properties
if (styleReplacements.length > 0) {
const styleProperty = nodeFactory.createPropertyAssignment(
nodeFactory.createIdentifier('styles'),
nodeFactory.createArrayLiteralExpression(styleReplacements),
);
properties = nodeFactory.createNodeArray([...properties, styleProperty]);
}
return nodeFactory.updateDecorator(
node,
nodeFactory.updateCallExpression(
decoratorFactory,
decoratorFactory.expression,
decoratorFactory.typeArguments,
[nodeFactory.updateObjectLiteralExpression(objectExpression, properties)],
),
);
}
function visitComponentMetadata(
nodeFactory: ts.NodeFactory,
node: ts.ObjectLiteralElementLike,
styleReplacements: ts.Expression[],
directTemplateLoading: boolean,
resourceImportDeclarations: ts.ImportDeclaration[],
moduleKind?: ts.ModuleKind,
inlineStyleMimeType?: string,
inlineStyleFileExtension?: string,
): ts.ObjectLiteralElementLike | undefined {
if (!ts.isPropertyAssignment(node) || ts.isComputedPropertyName(node.name)) {
return node;
}
const name = node.name.text;
switch (name) {
case 'moduleId':
return undefined;
case 'templateUrl':
const url = getResourceUrl(node.initializer, directTemplateLoading ? '!raw-loader!' : '');
if (!url) {
return node;
}
const importName = createResourceImport(
nodeFactory,
url,
resourceImportDeclarations,
moduleKind,
);
if (!importName) {
return node;
}
return nodeFactory.updatePropertyAssignment(
node,
nodeFactory.createIdentifier('template'),
importName,
);
case 'styles':
case 'styleUrls':
if (!ts.isArrayLiteralExpression(node.initializer)) {
return node;
}
const isInlineStyle = name === 'styles';
const styles = ts.visitNodes(node.initializer.elements, (node) => {
if (!ts.isStringLiteral(node) && !ts.isNoSubstitutionTemplateLiteral(node)) {
return node;
}
let url;
if (isInlineStyle) {
if (inlineStyleMimeType) {
const data = Buffer.from(node.text).toString('base64');
url = `data:${inlineStyleMimeType};charset=utf-8;base64,${data}`;
} else if (inlineStyleFileExtension) {
const data = Buffer.from(node.text).toString('base64');
const containingFile = node.getSourceFile().fileName;
url = `${containingFile}.${inlineStyleFileExtension}!=!${inlineDataLoaderPath}?data=${encodeURIComponent(
data,
)}!${containingFile}`;
} else {
return nodeFactory.createStringLiteral(node.text);
}
} else {
url = getResourceUrl(node);
}
if (!url) {
return node;
}
return createResourceImport(nodeFactory, url, resourceImportDeclarations, moduleKind);
});
// Styles should be placed first
if (isInlineStyle) {
styleReplacements.unshift(...styles);
} else {
styleReplacements.push(...styles);
}
return undefined;
default:
return node;
}
}
export function getResourceUrl(node: ts.Node, loader = ''): string | null {
// only analyze strings
if (!ts.isStringLiteral(node) && !ts.isNoSubstitutionTemplateLiteral(node)) {
return null;
}
return `${loader}${/^\.?\.\//.test(node.text) ? '' : './'}${node.text}`;
}
function isComponentDecorator(node: ts.Node, typeChecker: ts.TypeChecker): node is ts.Decorator {
if (!ts.isDecorator(node)) {
return false;
}
const origin = getDecoratorOrigin(node, typeChecker);
if (origin && origin.module === '@angular/core' && origin.name === 'Component') {
return true;
}
return false;
}
function createResourceImport(
nodeFactory: ts.NodeFactory,
url: string,
resourceImportDeclarations: ts.ImportDeclaration[],
moduleKind = ts.ModuleKind.ES2015,
): ts.Identifier | ts.Expression {
const urlLiteral = nodeFactory.createStringLiteral(url);
if (moduleKind < ts.ModuleKind.ES2015) {
return nodeFactory.createPropertyAccessExpression(
nodeFactory.createCallExpression(nodeFactory.createIdentifier('require'), [], [urlLiteral]),
'default',
);
} else {
const importName = nodeFactory.createIdentifier(
`__NG_CLI_RESOURCE__${resourceImportDeclarations.length}`,
);
resourceImportDeclarations.push(
nodeFactory.createImportDeclaration(
undefined,
undefined,
nodeFactory.createImportClause(false, importName, undefined),
urlLiteral,
),
);
return importName;
}
}
interface DecoratorOrigin {
name: string;
module: string;
}
function getDecoratorOrigin(
decorator: ts.Decorator,
typeChecker: ts.TypeChecker,
): DecoratorOrigin | null {
if (!ts.isCallExpression(decorator.expression)) {
return null;
}
let identifier: ts.Node;
let name = '';
if (ts.isPropertyAccessExpression(decorator.expression.expression)) {
identifier = decorator.expression.expression.expression;
name = decorator.expression.expression.name.text;
} else if (ts.isIdentifier(decorator.expression.expression)) {
identifier = decorator.expression.expression;
} else {
return null;
}
// NOTE: resolver.getReferencedImportDeclaration would work as well but is internal
const symbol = typeChecker.getSymbolAtLocation(identifier);
if (symbol && symbol.declarations && symbol.declarations.length > 0) {
const declaration = symbol.declarations[0];
let module: string;
if (ts.isImportSpecifier(declaration)) {
name = (declaration.propertyName || declaration.name).text;
module = (declaration.parent.parent.parent.moduleSpecifier as ts.Identifier).text;
} else if (ts.isNamespaceImport(declaration)) {
// Use the name from the decorator namespace property access
module = (declaration.parent.parent.moduleSpecifier as ts.Identifier).text;
} else if (ts.isImportClause(declaration)) {
name = (declaration.name as ts.Identifier).text;
module = (declaration.parent.moduleSpecifier as ts.Identifier).text;
} else {
return null;
}
return { name, module };
}
return null;
}