angular-ide
Version:
Provides a seamless integration with the Angular IDE from the command-line for developers looking for an enhanced development experience with Angular.
131 lines (117 loc) • 4.13 kB
JavaScript
const ts = require('typescript');
const astUtils = require('./ast-utils');
const path = require('path');
function ivyTransformer(builder, options) {
return function (context) {
return function (sourceFile) {
let isComponent = false;
if (sourceFile.identifiers) {
if (typeof sourceFile.identifiers.Component !== "undefined") {
isComponent = true;
}
if (!isComponent && typeof sourceFile.identifiers.get === "function") {
isComponent = sourceFile.identifiers.get("Component");
}
}
if (isComponent) {
const original = astUtils.findOriginal(sourceFile);
let templateURL = undefined;
const styleUrls = [];
if (original) {
const decorators = astUtils.collectDeepNodes(
original,
ts.SyntaxKind.Decorator
);
if (decorators.length > 0) {
const properties = astUtils.collectDeepNodes(
decorators[0],
ts.SyntaxKind.PropertyAssignment
);
properties.forEach((propertyNode) => {
if (
propertyNode.name.text === "styleUrls" &&
ts.hasOnlyExpressionInitializer(propertyNode)
) {
const arrayNodes = astUtils.collectDeepNodes(
propertyNode,
ts.SyntaxKind.ArrayLiteralExpression
);
if (arrayNodes.length > 0) {
const arrayNode = arrayNodes[0];
arrayNode.elements.forEach((element) => {
styleUrls.push(
path.normalize(
path.join(
path.dirname(sourceFile.fileName),
element.text
)
)
);
});
}
}
if (
propertyNode.name.text === "templateUrl" &&
ts.hasOnlyExpressionInitializer(propertyNode)
) {
const tmpTemplateURL = propertyNode.initializer.text;
if (tmpTemplateURL) {
templateURL = path.normalize(
path.join(path.dirname(sourceFile.fileName), tmpTemplateURL)
);
}
}
});
}
}
function visitor(node) {
if (ts.isClassDeclaration(node)) {
const tsPath = sourceFile.fileName;
const property = context.factory.createPropertyDeclaration(
undefined,
undefined,
"__clMeta",
undefined,
undefined,
context.factory.createObjectLiteralExpression([
context.factory.createPropertyAssignment(
"componentPath",
context.factory.createStringLiteral(tsPath)
),
context.factory.createPropertyAssignment(
"styleUrls",
context.factory.createArrayLiteralExpression(
styleUrls.map((styleURL) =>
context.factory.createStringLiteral(styleURL)
)
)
),
context.factory.createPropertyAssignment(
"templateUrl",
context.factory.createStringLiteral(templateURL)
),
])
);
return ts.visitEachChild(
context.factory.updateClassDeclaration(
node,
node.decorators,
node.modifiers,
node.name,
node.typeParameters,
node.heritageClauses,
[...node.members, property]
),
visitor,
context
);
}
return ts.visitEachChild(node, visitor, context);
}
return ts.visitNode(sourceFile, visitor);
}
return sourceFile;
};
};
}
module.exports = ivyTransformer;