UNPKG

@wroud/di-tools-codemod

Version:

@wroud/di-tools-codemod is a codemod utility that automates the migration of your codebase from Inversify to @wroud/di. It streamlines the transformation process, allowing for effortless and customizable transitions through configuration support.

55 lines 2.64 kB
import { ClassPrivateMethod, Identifier, TSParameterProperty, } from "jscodeshift"; import { isMultipleInjectDecorator } from "./isMultipleInjectDecorator.js"; import { isConstructorInjectDecorator } from "./isConstructorInjectDecorator.js"; import { isInjectableDecorator } from "./isInjectableDecorator.js"; import { createInjectableDecorator } from "./createInjectableDecorator.js"; export function transformDecorators(j, root, replacingPackage) { const decoratedClasses = []; root.find(j.ClassDeclaration).forEach((path) => { const decorators = path.node.decorators || []; const newDecorators = [ ...decorators.filter((decorator) => !isInjectableDecorator([replacingPackage], decorator)), ]; if (newDecorators.length === decorators.length) { return; } const constructors = j(path) .find(j.ClassBody) .filter((p) => p.parentPath.node === path.node) .map((path) => j(path) .find(j.ClassMethod, { kind: "constructor" }) .filter((p) => p.parentPath.node === path.node) .paths()); const constructorParams = constructors.map((path) => j(path) .find(j.Pattern, (node) => { if (node.type === "TSParameterProperty") { return true; } return node.type === "Identifier" && node.name !== "constructor"; }) .filter((p) => p.parentPath.node === path.node) .paths()); const dependencies = []; for (const param of constructorParams.nodes()) { const decorators = param.decorators || []; let type = j(param).find(j.TSTypeReference).nodes()[0]?.typeName; if (!type && param.type === "Identifier") { type = j(param).find(j.TSTypeAnnotation).nodes()[0]?.typeAnnotation; } if (!type) { dependencies.push({ type: j.nullLiteral(), multiple: false }); continue; } const multiple = decorators.some((decorator) => isMultipleInjectDecorator([replacingPackage], decorator)); dependencies.push({ type: type, multiple }); param.decorators = decorators.filter((decorator) => !isConstructorInjectDecorator([replacingPackage], decorator)); } newDecorators.push(createInjectableDecorator(j, dependencies)); if (path.node.id) { decoratedClasses.push(path.node.id.name); } path.node.decorators = newDecorators; }); return decoratedClasses; } //# sourceMappingURL=transformDecorators.js.map