|
| 1 | +import { getNodeImportStatements, getNodeImportCalls } from '@nodejs/codemod-utils/ast-grep/import-statement'; |
| 2 | +import { getNodeRequireCalls } from '@nodejs/codemod-utils/ast-grep/require-call'; |
| 3 | +import { resolveBindingPath } from '@nodejs/codemod-utils/ast-grep/resolve-binding-path'; |
| 4 | +import type { SgRoot, Edit, SgNode } from '@codemod.com/jssg-types/main'; |
| 5 | +import type JS from "@codemod.com/jssg-types/langs/javascript"; |
| 6 | + |
| 7 | +/** |
| 8 | + * Classes of the repl module |
| 9 | + */ |
| 10 | +const CLASS_NAMES = [ |
| 11 | + 'REPLServer', |
| 12 | + 'Recoverable', |
| 13 | +]; |
| 14 | + |
| 15 | +/** |
| 16 | + * Transform function that converts deprecated node:repl classes to use the `new` keyword |
| 17 | + * |
| 18 | + * Handles: |
| 19 | + * 1. `repl.REPLServer()` → `new repl.REPLServer()` |
| 20 | + * 2. `repl.Recoverable()` → `new repl.Recoverable()` |
| 21 | + * 3. Handles both CommonJS, ESM imports, and dynamic imports |
| 22 | + * 4. Preserves constructor arguments and assignments |
| 23 | + */ |
| 24 | +export default function transform(root: SgRoot<JS>): string | null { |
| 25 | + const rootNode = root.root(); |
| 26 | + const edits: Edit[] = []; |
| 27 | + |
| 28 | + const allStatementNodes = [ |
| 29 | + ...getNodeImportStatements(root, 'repl'), |
| 30 | + ...getNodeRequireCalls(root, 'repl'), |
| 31 | + ...getNodeImportCalls(root, 'repl'), |
| 32 | + ]; |
| 33 | + |
| 34 | + // if no imports are present it means that we don't need to process the file |
| 35 | + if (!allStatementNodes.length) return null; |
| 36 | + |
| 37 | + const classes = new Set<string>(getReplClassBasePaths(allStatementNodes)); |
| 38 | + |
| 39 | + for (const cls of classes) { |
| 40 | + const classesWithoutNew = rootNode.findAll({ |
| 41 | + rule: { |
| 42 | + not: { follows: { pattern: 'new' } }, |
| 43 | + pattern: `${cls}($$$ARGS)`, |
| 44 | + }, |
| 45 | + }); |
| 46 | + |
| 47 | + for (const clsWithoutNew of classesWithoutNew) { |
| 48 | + edits.push(clsWithoutNew.replace(`new ${clsWithoutNew.text()}`)); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + if (!edits.length) return null; |
| 53 | + |
| 54 | + return rootNode.commitEdits(edits); |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Get the base path of the repl classes |
| 59 | + * |
| 60 | + * @param statements - The import & require statements to search for the repl classes |
| 61 | + * @returns The base path of the repl classes |
| 62 | + */ |
| 63 | +function* getReplClassBasePaths(statements: SgNode<JS>[]) { |
| 64 | + for (const cls of CLASS_NAMES) { |
| 65 | + for (const stmt of statements) { |
| 66 | + const resolvedPath = resolveBindingPath(stmt, `$.${cls}`); |
| 67 | + if (resolvedPath) { |
| 68 | + yield resolvedPath; |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments