refakts
Version:
TypeScript refactoring tool built for AI coding agents to perform precise refactoring operations via command line instead of requiring complete code regeneration.
55 lines • 2.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.VariableReplacer = void 0;
const ts_morph_1 = require("ts-morph");
const context_analyzer_1 = require("./context-analyzer");
class VariableReplacer {
constructor() {
this.contextAnalyzer = new context_analyzer_1.ContextAnalyzer();
}
replaceAllReferences(_sourceFile, variableName, declaration, initializerText) {
const references = this.findAllReferences(variableName, declaration);
for (const reference of references) {
reference.replaceWithText(initializerText);
}
}
removeDeclaration(declaration) {
const declarationStatement = declaration.getVariableStatement();
if (declarationStatement) {
declarationStatement.remove();
}
}
findAllReferences(variableName, declaration) {
const references = [];
const declarationNode = declaration.getNameNode();
const declarationScope = this.findDeclarationScope(declaration);
this.collectScopedReferences(declarationScope, variableName, declarationNode, references);
return references;
}
findDeclarationScope(declaration) {
let current = declaration;
while (current) {
if (ts_morph_1.Node.isBlock(current) || ts_morph_1.Node.isMethodDeclaration(current) || ts_morph_1.Node.isFunctionDeclaration(current) || ts_morph_1.Node.isSourceFile(current)) {
return current;
}
current = current.getParent();
}
return declaration.getSourceFile();
}
collectScopedReferences(scope, variableName, declarationNode, references) {
scope.forEachDescendant((node) => {
if (this.isMatchingIdentifier(node, variableName, declarationNode)) {
references.push(node);
}
});
}
isMatchingIdentifier(node, variableName, declarationNode) {
return node.getKind() === 80 &&
node.getText() === variableName &&
node !== declarationNode &&
!this.contextAnalyzer.isInTypeContext(node) &&
!this.contextAnalyzer.isInDestructuringPattern(node);
}
}
exports.VariableReplacer = VariableReplacer;
//# sourceMappingURL=variable-replacer.js.map