@rxap/ts-morph
Version:
Provides utilities for manipulating TypeScript code using the ts-morph library. It offers a fluent API to add, modify, and remove code elements such as classes, decorators, imports, and properties in both Angular and NestJS projects. This package simplifi
76 lines • 3.45 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultInsertAtFactory = DefaultInsertAtFactory;
exports.AddRoute = AddRoute;
const ts_morph_1 = require("ts-morph");
const coerce_array_element_1 = require("../coerce-array-element");
const build_route_object_1 = require("./build-route-object");
const find_parent_route_1 = require("./find-parent-route");
require("colors");
function DefaultInsertAtFactory(route) {
return (array) => {
var _a, _b;
const elementCount = array.getElements().length;
if (route.path === '') {
if (elementCount > 0) {
const lastElement = array.getElements()[elementCount - 1];
if (lastElement.isKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression)) {
if ((_a = lastElement.asKindOrThrow(ts_morph_1.SyntaxKind.ObjectLiteralExpression).getProperty('path')) === null || _a === void 0 ? void 0 : _a.getText().match(/\*\*/)) {
return elementCount - 2;
}
}
}
return array.getElements().length - 1;
}
let insertAt = 0;
if (elementCount > 0) {
// find the first object literal
// this ensures that use of variables for route imports like STATUS_CHECK_ROUTE is always the first element
for (const element of array.getElements()) {
if (!element.isKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression)) {
insertAt++;
}
if (element.isKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression)) {
if (((_b = element.asKindOrThrow(ts_morph_1.SyntaxKind.ObjectLiteralExpression).getProperty('path')) === null || _b === void 0 ? void 0 : _b.getText()) === '') {
insertAt++;
}
else {
break;
}
}
else {
break;
}
}
}
return insertAt;
};
}
function AddRoute(sourceFile, options) {
const { component, route, path, name = 'ROUTES', insertAt = DefaultInsertAtFactory(route) } = options;
const routes = sourceFile.getVariableDeclaration(name);
if (routes) {
let initializer = routes.getInitializerIfKindOrThrow(ts_morph_1.SyntaxKind.ArrayLiteralExpression);
if (path === null || path === void 0 ? void 0 : path.length) {
initializer = (0, find_parent_route_1.FindParentRouteChildrenArrayByPath)(initializer, path);
}
if (initializer) {
if (component) {
initializer = (0, find_parent_route_1.FindParentRouteChildrenArrayByComponent)(initializer, component);
}
if (initializer) {
(0, coerce_array_element_1.CoerceArrayElement)(initializer, (0, build_route_object_1.BuildRouteObject)(route), (0, coerce_array_element_1.FindArrayElementByObjectProperty)('path', route.path), insertAt);
}
else {
console.log(`Could not find parent route by component for '${component}'`.yellow);
}
}
else {
console.log(`Could not find parent route by path for '${path}'`.yellow);
}
}
else {
console.log(`${name} variable not found`.red);
}
}
//# sourceMappingURL=add-route.js.map