@nxext/stencil
Version:
Nx plugin for stenciljs
217 lines • 8.37 kB
JavaScript
;
/*
Originally from nrwl nx: packages/angular/src/utils/nx-devkit/ast-utils.ts
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDecoratorMetadata = getDecoratorMetadata;
exports.addExportToModule = addExportToModule;
exports.addDeclarationToModule = addDeclarationToModule;
const ts = require("typescript");
const js_1 = require("@nx/js");
const tsquery_1 = require("@phenomnomnominal/tsquery");
function _angularImportsFromNode(node, _sourceFile) {
const ms = node.moduleSpecifier;
let modulePath;
switch (ms.kind) {
case ts.SyntaxKind.StringLiteral:
modulePath = ms.text;
break;
default:
return {};
}
if (!modulePath.startsWith('@angular/')) {
return {};
}
if (node.importClause) {
if (node.importClause.name) {
// This is of the form `import Name from 'path'`. Ignore.
return {};
}
else if (node.importClause.namedBindings) {
const nb = node.importClause.namedBindings;
if (nb.kind == ts.SyntaxKind.NamespaceImport) {
// This is of the form `import * as name from 'path'`. Return `name.`.
return {
[`${nb.name.text}.`]: modulePath,
};
}
else {
// This is of the form `import {a,b,c} from 'path'`
const namedImports = nb;
return namedImports.elements
.map((is) => is.propertyName ? is.propertyName.text : is.name.text)
.reduce((acc, curr) => {
acc[curr] = modulePath;
return acc;
}, {});
}
}
return {};
}
else {
// This is of the form `import 'path';`. Nothing to do.
return {};
}
}
function getDecoratorMetadata(source, identifier, module) {
const angularImports = (0, tsquery_1.tsquery)(source, 'ImportDeclaration')
.map((node) => _angularImportsFromNode(node, source))
.reduce((acc, current) => {
for (const key of Object.keys(current)) {
acc[key] = current[key];
}
return acc;
}, {});
return (0, js_1.getSourceNodes)(source)
.filter((node) => {
return (node.kind == ts.SyntaxKind.Decorator &&
node.expression.kind == ts.SyntaxKind.CallExpression);
})
.map((node) => node.expression)
.filter((expr) => {
if (expr.expression.kind == ts.SyntaxKind.Identifier) {
const id = expr.expression;
return (id.getFullText(source) == identifier &&
angularImports[id.getFullText(source)] === module);
}
else if (expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression) {
// This covers foo.NgModule when importing * as foo.
const paExpr = expr.expression;
// If the left expression is not an identifier, just give up at that point.
if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) {
return false;
}
const id = paExpr.name.text;
const moduleId = paExpr.expression.getText(source);
return id === identifier && angularImports[`${moduleId}.`] === module;
}
return false;
})
.filter((expr) => expr.arguments[0] &&
expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression)
.map((expr) => expr.arguments[0]);
}
function _addSymbolToNgModuleMetadata(host, source, ngModulePath, metadataField, expression) {
const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
let node = nodes[0];
// Find the decorator declaration.
if (!node) {
return source;
}
// Get all the children property assignment of object literals.
const matchingProperties = node.properties
.filter((prop) => prop.kind == ts.SyntaxKind.PropertyAssignment)
// Filter out every fields that's not "metadataField". Also handles string literals
// (but not expressions).
.filter((prop) => {
const name = prop.name;
switch (name.kind) {
case ts.SyntaxKind.Identifier:
return name.getText(source) == metadataField;
case ts.SyntaxKind.StringLiteral:
return name.text == metadataField;
}
return false;
});
// Get the last node of the array literal.
if (!matchingProperties) {
return source;
}
if (matchingProperties.length == 0) {
// We haven't found the field in the metadata declaration. Insert a new field.
const expr = node;
let position;
let toInsert;
if (expr.properties.length == 0) {
position = expr.getEnd() - 1;
toInsert = ` ${metadataField}: [${expression}]\n`;
}
else {
node = expr.properties[expr.properties.length - 1];
position = node.getEnd();
// Get the indentation of the last element, if any.
const text = node.getFullText(source);
if (text.match('^\r?\r?\n')) {
toInsert = `,${text.match(/^\r?\n\s+/)[0]}${metadataField}: [${expression}]`;
}
else {
toInsert = `, ${metadataField}: [${expression}]`;
}
}
return (0, js_1.insertChange)(host, source, ngModulePath, position, toInsert);
}
const assignment = matchingProperties[0];
// If it's not an array, nothing we can do really.
if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
return source;
}
const arrLiteral = assignment.initializer;
if (arrLiteral.elements.length == 0) {
// Forward the property.
node = arrLiteral;
}
else {
node = arrLiteral.elements;
}
if (!node) {
console.log('No app module found. Please add your new class to your component.');
return source;
}
const isArray = Array.isArray(node);
if (isArray) {
// eslint-disable-next-line @typescript-eslint/ban-types
const nodeArray = node;
const symbolsArray = nodeArray.map((node) => node.getText());
if (symbolsArray.includes(expression)) {
return source;
}
node = node[node.length - 1];
}
let toInsert;
let position = node.getEnd();
if (!isArray && node.kind == ts.SyntaxKind.ObjectLiteralExpression) {
// We haven't found the field in the metadata declaration. Insert a new
// field.
const expr = node;
if (expr.properties.length == 0) {
position = expr.getEnd() - 1;
toInsert = ` ${metadataField}: [${expression}]\n`;
}
else {
node = expr.properties[expr.properties.length - 1];
position = node.getEnd();
// Get the indentation of the last element, if any.
const text = node.getFullText(source);
if (text.match('^\r?\r?\n')) {
toInsert = `,${text.match(/^\r?\n\s+/)[0]}${metadataField}: [${expression}]`;
}
else {
toInsert = `, ${metadataField}: [${expression}]`;
}
}
}
else if (!isArray && node.kind == ts.SyntaxKind.ArrayLiteralExpression) {
// We found the field but it's empty. Insert it just before the `]`.
position--;
toInsert = `${expression}`;
}
else {
// Get the indentation of the last element, if any.
const text = node.getFullText(source);
if (text.match(/^\r?\n/)) {
toInsert = `,${text.match(/^\r?\n(\r?)\s+/)[0]}${expression}`;
}
else {
toInsert = `, ${expression}`;
}
}
return (0, js_1.insertChange)(host, source, ngModulePath, position, toInsert);
}
function addExportToModule(host, source, modulePath, symbolName) {
return _addSymbolToNgModuleMetadata(host, source, modulePath, 'exports', symbolName);
}
// Add a function who calculates pi
function addDeclarationToModule(host, source, modulePath, symbolName) {
return _addSymbolToNgModuleMetadata(host, source, modulePath, 'declarations', symbolName);
}
//# sourceMappingURL=angular-ast-utils.js.map