refakts
Version:
TypeScript refactoring tool built for AI coding agents to perform precise refactoring operations via command line instead of requiring complete code regeneration.
264 lines • 10.8 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.RefactorEngine = void 0;
const ts_morph_1 = require("ts-morph");
const tsquery_1 = require("@phenomnomnominal/tsquery");
const path = __importStar(require("path"));
class RefactorEngine {
constructor() {
this.project = new ts_morph_1.Project();
}
async inlineVariableByQuery(filePath, query) {
const sourceFile = this.loadSourceFile(filePath);
const node = this.findNodeByQuery(sourceFile, query);
await this.performInlineVariable(node);
await sourceFile.save();
}
async performInlineVariable(node) {
this.validateIdentifierNode(node);
const variableName = node.getText();
const sourceFile = node.getSourceFile();
const declaration = this.getVariableDeclaration(sourceFile, variableName);
const initializerText = this.getInitializerText(declaration, variableName);
this.replaceAllReferences(sourceFile, variableName, declaration, initializerText);
this.removeDeclaration(declaration);
}
loadSourceFile(filePath) {
const absolutePath = path.resolve(filePath);
return this.project.addSourceFileAtPath(absolutePath);
}
findNodeByQuery(sourceFile, query) {
const matches = this.executeQuery(sourceFile, query);
this.validateMatches(matches, query);
if (matches.length > 1) {
return this.handleMultipleMatches(sourceFile, matches, query);
}
return this.convertToMorphNode(sourceFile, matches[0]);
}
handleMultipleMatches(sourceFile, matches, query) {
const firstNode = this.convertToMorphNode(sourceFile, matches[0]);
if (!ts_morph_1.Node.isIdentifier(firstNode)) {
throw new Error(`Multiple matches found for query: ${query}. Please be more specific.`);
}
this.validateSameVariable(sourceFile, matches, firstNode.getText(), query);
return firstNode;
}
validateSameVariable(sourceFile, matches, variableName, query) {
for (let i = 1; i < matches.length; i++) {
const node = this.convertToMorphNode(sourceFile, matches[i]);
if (!ts_morph_1.Node.isIdentifier(node) || node.getText() !== variableName) {
throw new Error(`Multiple matches found for query: ${query}. Please be more specific.`);
}
}
}
validateIdentifierNode(node) {
if (node.getKind() !== 80) {
throw new Error(`Expected identifier, got ${node.getKindName()}`);
}
}
getVariableDeclaration(sourceFile, variableName) {
const declaration = this.findVariableDeclaration(sourceFile, variableName);
if (!declaration) {
throw new Error(`Variable declaration for '${variableName}' not found`);
}
return declaration;
}
getInitializerText(declaration, variableName, context) {
const nameNode = declaration.getNameNode();
if (ts_morph_1.Node.isObjectBindingPattern(nameNode) && variableName) {
return this.getDestructuringInitializer(declaration, variableName);
}
return this.getRegularInitializer(declaration, context);
}
getDestructuringInitializer(declaration, variableName) {
const initializer = declaration.getInitializer();
if (!initializer) {
throw new Error('Destructuring declaration has no initializer to inline');
}
const initializerText = initializer.getText();
return `${initializerText}.${variableName}`;
}
getRegularInitializer(declaration, context) {
const initializer = declaration.getInitializer();
if (!initializer) {
throw new Error('Variable has no initializer to inline');
}
return this.formatInitializerText(initializer, context);
}
formatInitializerText(initializer, context) {
const initializerText = initializer.getText();
if (this.needsParentheses(initializer, context)) {
return `(${initializerText})`;
}
return initializerText;
}
needsParentheses(node, context) {
if (!ts_morph_1.Node.isBinaryExpression(node)) {
return false;
}
return this.isSimpleAdditionOrSubtraction(node);
}
isSimpleAdditionOrSubtraction(node) {
const binaryExpr = node.asKindOrThrow(ts_morph_1.SyntaxKind.BinaryExpression);
if (!this.isAdditionOrSubtraction(binaryExpr)) {
return false;
}
return this.hasSimpleOperands(binaryExpr);
}
isAdditionOrSubtraction(binaryExpr) {
const operator = binaryExpr.getOperatorToken().getKind();
return operator === ts_morph_1.SyntaxKind.PlusToken || operator === ts_morph_1.SyntaxKind.MinusToken;
}
hasSimpleOperands(binaryExpr) {
const left = binaryExpr.getLeft();
const right = binaryExpr.getRight();
return this.areSimpleOperands(left, right);
}
areSimpleOperands(left, right) {
return (ts_morph_1.Node.isIdentifier(left) || ts_morph_1.Node.isNumericLiteral(left)) &&
(ts_morph_1.Node.isIdentifier(right) || ts_morph_1.Node.isNumericLiteral(right));
}
replaceAllReferences(sourceFile, variableName, declaration, initializerText) {
const references = this.findAllReferences(sourceFile, variableName, declaration);
for (const reference of references) {
reference.replaceWithText(initializerText);
}
}
removeDeclaration(declaration) {
const declarationStatement = declaration.getVariableStatement();
if (declarationStatement) {
declarationStatement.remove();
}
}
isMatchingIdentifier(node, variableName, declarationNode) {
return node.getKind() === 80 &&
node.getText() === variableName &&
node !== declarationNode &&
!this.isInTypeContext(node) &&
!this.isInDestructuringPattern(node);
}
isInDestructuringPattern(node) {
let parent = node.getParent();
while (parent) {
if (this.isDestructuringContext(parent)) {
return true;
}
parent = parent.getParent();
}
return false;
}
isDestructuringContext(node) {
return node.getKind() === ts_morph_1.SyntaxKind.ObjectBindingPattern ||
node.getKind() === ts_morph_1.SyntaxKind.ArrayBindingPattern ||
node.getKind() === ts_morph_1.SyntaxKind.BindingElement;
}
isInTypeContext(node) {
let parent = node.getParent();
while (parent) {
if (this.isTypeContext(parent)) {
return true;
}
parent = parent.getParent();
}
return false;
}
isTypeContext(node) {
return node.getKind() === ts_morph_1.SyntaxKind.TypeLiteral ||
node.getKind() === ts_morph_1.SyntaxKind.PropertySignature ||
node.getKind() === ts_morph_1.SyntaxKind.TypeReference;
}
executeQuery(sourceFile, query) {
return (0, tsquery_1.tsquery)(sourceFile.compilerNode, query);
}
validateMatches(matches, query) {
if (matches.length === 0) {
throw new Error(`No matches found for query: ${query}`);
}
}
convertToMorphNode(sourceFile, match) {
const node = sourceFile.getDescendantAtPos(match.getStart());
if (!node) {
throw new Error(`Could not find ts-morph node for query match`);
}
return node;
}
collectMatchingIdentifiers(sourceFile, variableName, declarationNode, references) {
sourceFile.forEachDescendant((node) => {
if (this.isMatchingIdentifier(node, variableName, declarationNode)) {
references.push(node);
}
});
}
findVariableDeclaration(sourceFile, variableName) {
const variableDeclarations = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.VariableDeclaration);
for (const decl of variableDeclarations) {
if (this.matchesVariableName(decl, variableName)) {
return decl;
}
}
return undefined;
}
matchesVariableName(declaration, variableName) {
if (declaration.getName() === variableName) {
return true;
}
return this.matchesDestructuredVariable(declaration, variableName);
}
matchesDestructuredVariable(declaration, variableName) {
const nameNode = declaration.getNameNode();
if (!ts_morph_1.Node.isObjectBindingPattern(nameNode)) {
return false;
}
return this.hasMatchingElement(nameNode, variableName);
}
hasMatchingElement(nameNode, variableName) {
const bindingPattern = nameNode.asKindOrThrow(ts_morph_1.SyntaxKind.ObjectBindingPattern);
for (const element of bindingPattern.getElements()) {
if (element.getName() === variableName) {
return true;
}
}
return false;
}
findAllReferences(sourceFile, variableName, declaration) {
const references = [];
const declarationNode = declaration.getNameNode();
this.collectMatchingIdentifiers(sourceFile, variableName, declarationNode, references);
return references;
}
}
exports.RefactorEngine = RefactorEngine;
//# sourceMappingURL=refactor-engine-old.js.map