From ecb28a2155ff342c2bf3a2a6f20c5cf3b9ec87a3 Mon Sep 17 00:00:00 2001 From: Vishal Raj <9031842908.vk@gmail.com> Date: Wed, 18 Nov 2026 22:37:32 +0530 Subject: [PATCH 1/4] feat(DEP0199): migrate internal HTTP imports to node:http Signed-off-by: Vishal Raj <9031842908.vk@gmail.com> --- .../README.md | 19 + .../codemod.yaml | 25 + .../package.json | 24 + .../src/workflow.ts | 664 ++++++++++++++++++ .../tests/already-migrated/expected.mjs | 2 + .../tests/already-migrated/input.mjs | 2 + .../tests/cjs-destructuring/expected.js | 2 + .../tests/cjs-destructuring/input.js | 2 + .../tests/cjs-direct-property/expected.js | 2 + .../tests/cjs-direct-property/input.js | 2 + .../consolidate-existing-http/expected.mjs | 1 + .../tests/consolidate-existing-http/input.mjs | 2 + .../tests/dynamic-import/expected.mjs | 6 + .../tests/dynamic-import/input.mjs | 6 + .../tests/esm-aliases/expected.mjs | 1 + .../tests/esm-aliases/input.mjs | 2 + .../tests/esm-named/expected.mjs | 1 + .../tests/esm-named/input.mjs | 1 + .../tests/esm-node-prefix/expected.mjs | 1 + .../tests/esm-node-prefix/input.mjs | 1 + .../tests/mixed-internal-exports/expected.mjs | 2 + .../tests/mixed-internal-exports/input.mjs | 1 + .../tests/re-exports/expected.mjs | 2 + .../tests/re-exports/input.mjs | 2 + .../tests/typescript/expected.ts | 3 + .../tests/typescript/input.ts | 4 + .../tests/unresolved-cases/expected.mjs | 3 + .../tests/unresolved-cases/input.mjs | 3 + .../workflow.yaml | 25 + 29 files changed, 811 insertions(+) create mode 100644 recipes/http-internal-modules-to-node-http/README.md create mode 100644 recipes/http-internal-modules-to-node-http/codemod.yaml create mode 100644 recipes/http-internal-modules-to-node-http/package.json create mode 100644 recipes/http-internal-modules-to-node-http/src/workflow.ts create mode 100644 recipes/http-internal-modules-to-node-http/tests/already-migrated/expected.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/already-migrated/input.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/cjs-destructuring/expected.js create mode 100644 recipes/http-internal-modules-to-node-http/tests/cjs-destructuring/input.js create mode 100644 recipes/http-internal-modules-to-node-http/tests/cjs-direct-property/expected.js create mode 100644 recipes/http-internal-modules-to-node-http/tests/cjs-direct-property/input.js create mode 100644 recipes/http-internal-modules-to-node-http/tests/consolidate-existing-http/expected.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/consolidate-existing-http/input.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/dynamic-import/expected.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/dynamic-import/input.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/esm-aliases/expected.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/esm-aliases/input.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/esm-named/expected.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/esm-named/input.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/esm-node-prefix/expected.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/esm-node-prefix/input.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/mixed-internal-exports/expected.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/mixed-internal-exports/input.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/re-exports/expected.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/re-exports/input.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/typescript/expected.ts create mode 100644 recipes/http-internal-modules-to-node-http/tests/typescript/input.ts create mode 100644 recipes/http-internal-modules-to-node-http/tests/unresolved-cases/expected.mjs create mode 100644 recipes/http-internal-modules-to-node-http/tests/unresolved-cases/input.mjs create mode 100644 recipes/http-internal-modules-to-node-http/workflow.yaml diff --git a/recipes/http-internal-modules-to-node-http/README.md b/recipes/http-internal-modules-to-node-http/README.md new file mode 100644 index 00000000..544a76b4 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/README.md @@ -0,0 +1,19 @@ +# @nodejs/http-internal-modules-to-node-http + +Migrates legacy imports of internal Node.js HTTP modules (`_http_*`) to the public `node:http` module as introduced under [DEP0199](https://nodejs.org/api/deprecations.html#dep0199-requirenode_http_). + +## Supported Modules and Exports + +- `_http_agent` / `node:_http_agent`: `Agent`, `globalAgent` +- `_http_client` / `node:_http_client`: `ClientRequest` +- `_http_incoming` / `node:_http_incoming`: `IncomingMessage` +- `_http_outgoing` / `node:_http_outgoing`: `OutgoingMessage`, `validateHeaderName`, `validateHeaderValue` +- `_http_server` / `node:_http_server`: `Server`, `ServerResponse`, `STATUS_CODES` + +## Behavior + +- Replaces module specifiers with `node:http` when accessing supported public exports. +- Supports ESM named imports, CommonJS destructuring, direct property access, dynamic imports, and re-exports. +- Preserves local aliases and handles TypeScript type annotations. +- Consolidates multiple imports targeting `node:http`. +- Skips internal-only exports (e.g. `_http_common`), escaped namespace objects, and unknown properties, reporting them for manual review. diff --git a/recipes/http-internal-modules-to-node-http/codemod.yaml b/recipes/http-internal-modules-to-node-http/codemod.yaml new file mode 100644 index 00000000..3d59370e --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/codemod.yaml @@ -0,0 +1,25 @@ +schema_version: "1.0" +name: "@nodejs/http-internal-modules-to-node-http" +version: "1.0.0" +description: "Handle DEP0199 by migrating internal HTTP module imports (_http_*) to node:http." +author: Vishal Raj +license: MIT +workflow: workflow.yaml +category: migration +repository: https://github.com/nodejs/userland-migrations + +targets: + languages: + - javascript + - typescript + +keywords: + - transformation + - migration + - nodejs + - http + - dep0199 + +registry: + access: public + visibility: public diff --git a/recipes/http-internal-modules-to-node-http/package.json b/recipes/http-internal-modules-to-node-http/package.json new file mode 100644 index 00000000..1b9242c8 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/package.json @@ -0,0 +1,24 @@ +{ + "name": "@nodejs/http-internal-modules-to-node-http", + "version": "1.0.0", + "description": "Handle DEP0199 by migrating internal HTTP modules (_http_*) to node:http", + "type": "module", + "scripts": { + "test": "npx codemod jssg test -l typescript ./src/workflow.ts" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/userland-migrations.git", + "directory": "recipes/http-internal-modules-to-node-http", + "bugs": "https://github.com/nodejs/userland-migrations/issues" + }, + "author": "Vishal Raj", + "license": "MIT", + "homepage": "https://github.com/nodejs/userland-migrations/blob/main/recipes/http-internal-modules-to-node-http/README.md", + "devDependencies": { + "@codemod.com/jssg-types": "^1.6.3" + }, + "dependencies": { + "@nodejs/codemod-utils": "*" + } +} diff --git a/recipes/http-internal-modules-to-node-http/src/workflow.ts b/recipes/http-internal-modules-to-node-http/src/workflow.ts new file mode 100644 index 00000000..28960b7d --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/src/workflow.ts @@ -0,0 +1,664 @@ +import type { + Edit, + Range, + SgNode, + SgRoot, +} from '@codemod.com/jssg-types/main'; +import type Js from '@codemod.com/jssg-types/langs/javascript'; +import { removeLines } from '@nodejs/codemod-utils/ast-grep/remove-lines'; + +/** + * Public exports supported by each internal HTTP module under DEP0199. + */ +const MODULE_EXPORTS: Record> = { + _http_agent: new Set(['Agent', 'globalAgent']), + _http_client: new Set(['ClientRequest']), + _http_incoming: new Set(['IncomingMessage']), + _http_outgoing: new Set([ + 'OutgoingMessage', + 'validateHeaderName', + 'validateHeaderValue', + ]), + _http_server: new Set(['Server', 'ServerResponse', 'STATUS_CODES']), +}; + +function getInternalModuleName(specifier: string): string | null { + const cleaned = specifier.replace(/^node:/, ''); + if (cleaned in MODULE_EXPORTS) { + return cleaned; + } + return null; +} + +function getUnquotedText(node: SgNode): string { + return node.text().replace(/^['"`]|['"`]$/g, ''); +} + +function warn(root: SgRoot, node: SgNode, message: string): void { + const { start } = node.range(); + console.warn( + `${root.filename()}:${start.line + 1}:${start.column + 1}: ${message}`, + ); +} + +type SpecifierInfo = { + node: SgNode; + text: string; + imported: string; + local: string; +}; + +type ImportStatementInfo = { + statement: SgNode; + sourceNode: SgNode; + rawSource: string; + internalMod: string; + isTypeOnly: boolean; + supported: SpecifierInfo[]; + unsupported: SpecifierInfo[]; +}; + +/** + * Handle DEP0199: migrate internal Node.js HTTP modules (_http_*) to node:http. + */ +export default function transform(root: SgRoot): string | null { + const rootNode = root.root(); + const edits: Edit[] = []; + const linesToRemove: Range[] = []; + + // Check for excluded modules like _http_common + const allStrings = rootNode.findAll({ rule: { kind: 'string' } }); + for (const str of allStrings) { + const unquoted = getUnquotedText(str); + if (unquoted.replace(/^node:/, '') === '_http_common') { + warn( + root, + str, + '_http_common internals such as HTTPParser are excluded from migration to node:http (DEP0199)', + ); + } + } + + // 1. Process ESM import statements + processImportStatements(root, rootNode, edits, linesToRemove); + + // 2. Process ESM export statements (re-exports) + processExportStatements(root, rootNode, edits); + + // 3. Process CommonJS require calls + processRequireCalls(root, rootNode, edits); + + // 4. Process dynamic import(...) calls + processDynamicImports(root, rootNode, edits); + + if (edits.length === 0 && linesToRemove.length === 0) { + return null; + } + + const transformed = rootNode.commitEdits(edits); + if (linesToRemove.length > 0) { + return removeLines(transformed, linesToRemove); + } + + return transformed; +} + +/** + * Handle ESM import statements: + * - Replaces specifier with 'node:http' when exports are supported + * - Consolidates multiple compatible imports targeting 'node:http' + * - Splits mixed imports (retaining unsupported exports in the internal module) + * - Skips and reports namespace and unsupported imports + */ +function processImportStatements( + root: SgRoot, + rootNode: SgNode, + edits: Edit[], + linesToRemove: Range[], +): void { + const importStatements = rootNode.findAll({ + rule: { kind: 'import_statement' }, + }); + + // Find pre-existing node:http imports + const existingHttpImports: { + statement: SgNode; + isTypeOnly: boolean; + namedImports: SgNode | null; + }[] = []; + + const internalImports: ImportStatementInfo[] = []; + + for (const stmt of importStatements) { + const sourceNode = stmt.field('source'); + if (!sourceNode) continue; + + const rawSource = getUnquotedText(sourceNode); + const normalized = rawSource.replace(/^node:/, ''); + + if (normalized === 'http') { + const isTypeOnly = stmt.text().startsWith('import type'); + const namedImports = stmt.find({ rule: { kind: 'named_imports' } }); + existingHttpImports.push({ statement: stmt, isTypeOnly, namedImports }); + continue; + } + + const internalMod = getInternalModuleName(rawSource); + if (!internalMod) continue; + + // Check for namespace import: import * as foo from '_http_*' + const nsImport = stmt.find({ rule: { kind: 'namespace_import' } }); + if (nsImport) { + warn( + root, + stmt, + `Namespace import '${nsImport.text()}' from '${rawSource}' is skipped; review manually (DEP0199)`, + ); + continue; + } + + const specifiers = stmt.findAll({ rule: { kind: 'import_specifier' } }); + if (specifiers.length === 0) { + warn( + root, + stmt, + `Import from '${rawSource}' without named specifiers is skipped; review manually (DEP0199)`, + ); + continue; + } + + const isTypeOnly = stmt.text().startsWith('import type'); + const supported: SpecifierInfo[] = []; + const unsupported: SpecifierInfo[] = []; + + for (const spec of specifiers) { + const nameNode = spec.field('name'); + const aliasNode = spec.field('alias'); + const imported = nameNode ? nameNode.text() : spec.text(); + const local = aliasNode ? aliasNode.text() : imported; + + if (MODULE_EXPORTS[internalMod].has(imported)) { + supported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + } else { + unsupported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + warn( + root, + spec, + `Internal-only export '${imported}' from '${rawSource}' cannot be migrated to 'node:http' (DEP0199)`, + ); + } + } + + if (supported.length > 0) { + internalImports.push({ + statement: stmt, + sourceNode, + rawSource, + internalMod, + isTypeOnly, + supported, + unsupported, + }); + } + } + + if (internalImports.length === 0) return; + + // Group internal imports by type-only status + const valueInternal = internalImports.filter((i) => !i.isTypeOnly); + const typeInternal = internalImports.filter((i) => i.isTypeOnly); + + consolidateImportsGroup( + valueInternal, + existingHttpImports.find((e) => !e.isTypeOnly), + edits, + linesToRemove, + ); + + consolidateImportsGroup( + typeInternal, + existingHttpImports.find((e) => e.isTypeOnly), + edits, + linesToRemove, + ); +} + +function consolidateImportsGroup( + imports: ImportStatementInfo[], + existingHttp: + | { + statement: SgNode; + isTypeOnly: boolean; + namedImports: SgNode | null; + } + | undefined, + edits: Edit[], + linesToRemove: Range[], +): void { + if (imports.length === 0) return; + + // Case 1: Consolidate into pre-existing node:http import + if (existingHttp?.namedImports) { + const existingNamedText = existingHttp.namedImports.text(); + // Parse existing specifiers + const existingSpecs = existingNamedText + .replace(/^\{\s*|\s*\}$/g, '') + .split(',') + .map((s) => s.trim()) + .filter(Boolean); + + const specsToAdd: string[] = []; + + for (const imp of imports) { + for (const sup of imp.supported) { + if (!existingSpecs.includes(sup.text)) { + specsToAdd.push(sup.text); + existingSpecs.push(sup.text); + } + } + + if (imp.unsupported.length === 0) { + // Entire import migrated; remove line + linesToRemove.push(imp.statement.range()); + } else { + // Mixed import: keep only unsupported specifiers + const named = imp.statement.find({ + rule: { kind: 'named_imports' }, + }); + if (named) { + const remaining = imp.unsupported.map((u) => u.text).join(', '); + edits.push(named.replace(`{ ${remaining} }`)); + } + } + } + + if (specsToAdd.length > 0) { + const allSpecs = [ + ...existingNamedText + .replace(/^\{\s*|\s*\}$/g, '') + .split(',') + .map((s) => s.trim()) + .filter(Boolean), + ...specsToAdd, + ].join(', '); + + edits.push(existingHttp.namedImports.replace(`{ ${allSpecs} }`)); + } + return; + } + + // Case 2: No pre-existing node:http import, but multiple or single internal imports + const [first, ...rest] = imports; + + if (rest.length === 0 && first.unsupported.length === 0) { + // Single completely supported import: just update source + edits.push(first.sourceNode.replace("'node:http'")); + return; + } + + // Consolidate into first + const consolidatedSpecs: string[] = []; + for (const sup of first.supported) { + if (!consolidatedSpecs.includes(sup.text)) { + consolidatedSpecs.push(sup.text); + } + } + + for (const rem of rest) { + for (const sup of rem.supported) { + if (!consolidatedSpecs.includes(sup.text)) { + consolidatedSpecs.push(sup.text); + } + } + + if (rem.unsupported.length === 0) { + linesToRemove.push(rem.statement.range()); + } else { + const named = rem.statement.find({ + rule: { kind: 'named_imports' }, + }); + if (named) { + const remaining = rem.unsupported.map((u) => u.text).join(', '); + edits.push(named.replace(`{ ${remaining} }`)); + } + } + } + + if (first.unsupported.length === 0) { + // Replace first statement's source and specifiers + edits.push(first.sourceNode.replace("'node:http'")); + const named = first.statement.find({ rule: { kind: 'named_imports' } }); + if (named) { + edits.push(named.replace(`{ ${consolidatedSpecs.join(', ')} }`)); + } + } else { + // First was mixed: keep unsupported in first, and append new node:http import + const remaining = first.unsupported.map((u) => u.text).join(', '); + const typePrefix = first.isTypeOnly ? 'type ' : ''; + const firstSource = first.sourceNode.text(); + const newStmt = `import ${typePrefix}{ ${remaining} } from ${firstSource};\nimport ${typePrefix}{ ${consolidatedSpecs.join(', ')} } from 'node:http';`; + edits.push(first.statement.replace(newStmt)); + } +} + +/** + * Handle ESM export statements (re-exports): + * - export { IncomingMessage } from '_http_incoming'; + */ +function processExportStatements( + root: SgRoot, + rootNode: SgNode, + edits: Edit[], +): void { + const exportStatements = rootNode.findAll({ + rule: { kind: 'export_statement' }, + }); + + for (const stmt of exportStatements) { + const sourceNode = stmt.field('source'); + if (!sourceNode) continue; + + const rawSource = getUnquotedText(sourceNode); + const internalMod = getInternalModuleName(rawSource); + if (!internalMod) continue; + + const specifiers = stmt.findAll({ rule: { kind: 'export_specifier' } }); + if (specifiers.length === 0) continue; + + const supported: SpecifierInfo[] = []; + const unsupported: SpecifierInfo[] = []; + + for (const spec of specifiers) { + const nameNode = spec.field('name'); + const aliasNode = spec.field('alias'); + const imported = nameNode ? nameNode.text() : spec.text(); + const local = aliasNode ? aliasNode.text() : imported; + + if (MODULE_EXPORTS[internalMod].has(imported)) { + supported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + } else { + unsupported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + warn( + root, + spec, + `Internal-only re-export '${imported}' from '${rawSource}' cannot be migrated to 'node:http' (DEP0199)`, + ); + } + } + + if (supported.length > 0 && unsupported.length === 0) { + edits.push(sourceNode.replace("'node:http'")); + } else if (supported.length > 0 && unsupported.length > 0) { + // Mixed re-export: keep unsupported, add supported + const remaining = unsupported.map((u) => u.text).join(', '); + const supText = supported.map((s) => s.text).join(', '); + const sourceText = sourceNode.text(); + const newStmt = `export { ${remaining} } from ${sourceText};\nexport { ${supText} } from 'node:http';`; + edits.push(stmt.replace(newStmt)); + } + } +} + +/** + * Handle CommonJS require calls: + * - const { Server } = require('_http_server'); + * - const Server = require('_http_server').Server; + * - const agent = require('_http_agent'); (skipped / warned) + */ +function processRequireCalls( + root: SgRoot, + rootNode: SgNode, + edits: Edit[], +): void { + const requireCalls = rootNode.findAll({ + rule: { + kind: 'call_expression', + has: { + field: 'function', + kind: 'identifier', + regex: '^require$', + }, + }, + }); + + for (const call of requireCalls) { + const args = call.field('arguments'); + if (!args) continue; + + const stringArg = args.find({ rule: { kind: 'string' } }); + if (!stringArg) continue; + + const rawSource = getUnquotedText(stringArg); + const internalMod = getInternalModuleName(rawSource); + if (!internalMod) continue; + + const parent = call.parent(); + if (!parent) continue; + + // Case A: Member expression: require('_http_server').Server + if (parent.is('member_expression')) { + const prop = parent.field('property'); + if (prop && MODULE_EXPORTS[internalMod].has(prop.text())) { + edits.push(stringArg.replace("'node:http'")); + } else { + warn( + root, + prop || call, + `Unknown/internal property '${prop?.text()}' on '${rawSource}' is skipped; review manually (DEP0199)`, + ); + } + continue; + } + + // Case B: Variable declarator: const { Server } = require(...) + if (parent.is('variable_declarator')) { + const namePattern = parent.field('name'); + if (namePattern?.is('object_pattern')) { + const shorthandProps = namePattern.findAll({ + rule: { kind: 'shorthand_property_identifier_pattern' }, + }); + const pairProps = namePattern.findAll({ + rule: { kind: 'pair_pattern' }, + }); + + const supportedNames: string[] = []; + const unsupportedNames: string[] = []; + + for (const sh of shorthandProps) { + const name = sh.text(); + if (MODULE_EXPORTS[internalMod].has(name)) { + supportedNames.push(name); + } else { + unsupportedNames.push(name); + warn( + root, + sh, + `Internal-only export '${name}' from '${rawSource}' cannot be migrated to 'node:http' (DEP0199)`, + ); + } + } + + for (const pair of pairProps) { + const key = pair.field('key')?.text() || ''; + if (MODULE_EXPORTS[internalMod].has(key)) { + supportedNames.push(pair.text()); + } else { + unsupportedNames.push(pair.text()); + warn( + root, + pair, + `Internal-only export '${key}' from '${rawSource}' cannot be migrated to 'node:http' (DEP0199)`, + ); + } + } + + if (supportedNames.length > 0 && unsupportedNames.length === 0) { + edits.push(stringArg.replace("'node:http'")); + } else if ( + supportedNames.length > 0 && + unsupportedNames.length > 0 + ) { + // Mixed destructuring: keep unsupported, add new require for supported + const declParent = parent.parent(); // lexical_declaration or variable_declaration + const kind = declParent?.kind() === 'lexical_declaration' ? 'const' : 'var'; + const newDecl = `${kind} { ${unsupportedNames.join(', ')} } = require(${stringArg.text()});\n${kind} { ${supportedNames.join(', ')} } = require('node:http');`; + if (declParent) { + edits.push(declParent.replace(newDecl)); + } + } + continue; + } + + // Case C: Un-destructured namespace object: const agent = require('_http_agent') + warn( + root, + parent, + `Namespace object '${namePattern?.text()}' from '${rawSource}' is skipped; review manually (DEP0199)`, + ); + } + } +} + +/** + * Handle dynamic import(...) calls: + * - const { Server } = await import('_http_server'); + * - const server = await import('_http_server').then(m => m.Server); + */ +function processDynamicImports( + root: SgRoot, + rootNode: SgNode, + edits: Edit[], +): void { + const dynamicImports = rootNode.findAll({ + rule: { + kind: 'call_expression', + has: { + field: 'function', + kind: 'import', + }, + }, + }); + + for (const call of dynamicImports) { + const args = call.field('arguments'); + if (!args) continue; + + const stringArg = args.find({ rule: { kind: 'string' } }); + if (!stringArg) continue; + + const rawSource = getUnquotedText(stringArg); + const internalMod = getInternalModuleName(rawSource); + if (!internalMod) continue; + + // Walk up to find if exports are destructured or accessed via .then + const current: SgNode | null = call; + let isSupported = false; + + // Check parent: await import(...) + const parent = current.parent(); + if (parent?.is('await_expression')) { + const grandParent = parent.parent(); + if (grandParent?.is('variable_declarator')) { + const name = grandParent.field('name'); + if (name?.is('object_pattern')) { + const props = name.findAll({ + rule: { + any: [ + { kind: 'shorthand_property_identifier_pattern' }, + { kind: 'pair_pattern' }, + ], + }, + }); + const allSupported = + props.length > 0 && + props.every((p) => { + const key = + p.is('pair_pattern') ? p.field('key')?.text() || '' : p.text(); + return MODULE_EXPORTS[internalMod].has(key); + }); + if (allSupported) { + isSupported = true; + } + } + } + } + + // Check chained .then: import(...).then(...) + const callParent = call.parent(); + if ( + callParent?.is('member_expression') && + callParent.field('property')?.text() === 'then' + ) { + const thenCall = callParent.parent(); + if (thenCall?.is('call_expression')) { + const thenArgs = thenCall.field('arguments'); + const callback = thenArgs?.child(1); // child(0) is '(', child(1) is callback function + if (callback) { + // Check if callback accesses supported member: m => m.Server or ({ Server }) => ... + const param = callback.field('parameters') || callback.field('parameter'); + if (param) { + const destructured = param.findAll({ + rule: { + any: [ + { kind: 'shorthand_property_identifier_pattern' }, + { kind: 'pair_pattern' }, + ], + }, + }); + if ( + destructured.length > 0 && + destructured.every((p) => { + const key = + p.is('pair_pattern') ? p.field('key')?.text() || '' : p.text(); + return MODULE_EXPORTS[internalMod].has(key); + }) + ) { + isSupported = true; + } + } + // Check return / body member expression: m.Server + const members = callback.findAll({ + rule: { kind: 'member_expression' }, + }); + for (const m of members) { + const prop = m.field('property')?.text() || ''; + if (MODULE_EXPORTS[internalMod].has(prop)) { + isSupported = true; + break; + } + } + } + } + } + + if (isSupported) { + edits.push(stringArg.replace("'node:http'")); + } else { + warn( + root, + call, + `Dynamic import of '${rawSource}' without verified public exports is skipped; review manually (DEP0199)`, + ); + } + } +} diff --git a/recipes/http-internal-modules-to-node-http/tests/already-migrated/expected.mjs b/recipes/http-internal-modules-to-node-http/tests/already-migrated/expected.mjs new file mode 100644 index 00000000..36e8d643 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/already-migrated/expected.mjs @@ -0,0 +1,2 @@ +import { Agent } from 'node:http'; +const { Server } = require('node:http'); diff --git a/recipes/http-internal-modules-to-node-http/tests/already-migrated/input.mjs b/recipes/http-internal-modules-to-node-http/tests/already-migrated/input.mjs new file mode 100644 index 00000000..36e8d643 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/already-migrated/input.mjs @@ -0,0 +1,2 @@ +import { Agent } from 'node:http'; +const { Server } = require('node:http'); diff --git a/recipes/http-internal-modules-to-node-http/tests/cjs-destructuring/expected.js b/recipes/http-internal-modules-to-node-http/tests/cjs-destructuring/expected.js new file mode 100644 index 00000000..f31607f6 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/cjs-destructuring/expected.js @@ -0,0 +1,2 @@ +const { Agent: HttpAgent } = require('node:http'); +const { Server, STATUS_CODES } = require('node:http'); diff --git a/recipes/http-internal-modules-to-node-http/tests/cjs-destructuring/input.js b/recipes/http-internal-modules-to-node-http/tests/cjs-destructuring/input.js new file mode 100644 index 00000000..586a3083 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/cjs-destructuring/input.js @@ -0,0 +1,2 @@ +const { Agent: HttpAgent } = require('_http_agent'); +const { Server, STATUS_CODES } = require('node:_http_server'); diff --git a/recipes/http-internal-modules-to-node-http/tests/cjs-direct-property/expected.js b/recipes/http-internal-modules-to-node-http/tests/cjs-direct-property/expected.js new file mode 100644 index 00000000..f57075c8 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/cjs-direct-property/expected.js @@ -0,0 +1,2 @@ +const Server = require('node:http').Server; +const globalAgent = require('node:http').globalAgent; diff --git a/recipes/http-internal-modules-to-node-http/tests/cjs-direct-property/input.js b/recipes/http-internal-modules-to-node-http/tests/cjs-direct-property/input.js new file mode 100644 index 00000000..b6ac30ed --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/cjs-direct-property/input.js @@ -0,0 +1,2 @@ +const Server = require('_http_server').Server; +const globalAgent = require('node:_http_agent').globalAgent; diff --git a/recipes/http-internal-modules-to-node-http/tests/consolidate-existing-http/expected.mjs b/recipes/http-internal-modules-to-node-http/tests/consolidate-existing-http/expected.mjs new file mode 100644 index 00000000..f6d11715 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/consolidate-existing-http/expected.mjs @@ -0,0 +1 @@ +import { createServer, IncomingMessage } from 'node:http'; diff --git a/recipes/http-internal-modules-to-node-http/tests/consolidate-existing-http/input.mjs b/recipes/http-internal-modules-to-node-http/tests/consolidate-existing-http/input.mjs new file mode 100644 index 00000000..af1eb4c2 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/consolidate-existing-http/input.mjs @@ -0,0 +1,2 @@ +import { createServer } from 'node:http'; +import { IncomingMessage } from '_http_incoming'; diff --git a/recipes/http-internal-modules-to-node-http/tests/dynamic-import/expected.mjs b/recipes/http-internal-modules-to-node-http/tests/dynamic-import/expected.mjs new file mode 100644 index 00000000..e4050e14 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/dynamic-import/expected.mjs @@ -0,0 +1,6 @@ +async function load() { + const { Server } = await import('node:http'); + const { IncomingMessage } = await import('node:http'); + const agent = await import('node:http').then((m) => m.Agent); + return { Server, IncomingMessage, agent }; +} diff --git a/recipes/http-internal-modules-to-node-http/tests/dynamic-import/input.mjs b/recipes/http-internal-modules-to-node-http/tests/dynamic-import/input.mjs new file mode 100644 index 00000000..1407f0c4 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/dynamic-import/input.mjs @@ -0,0 +1,6 @@ +async function load() { + const { Server } = await import('_http_server'); + const { IncomingMessage } = await import('node:_http_incoming'); + const agent = await import('_http_agent').then((m) => m.Agent); + return { Server, IncomingMessage, agent }; +} diff --git a/recipes/http-internal-modules-to-node-http/tests/esm-aliases/expected.mjs b/recipes/http-internal-modules-to-node-http/tests/esm-aliases/expected.mjs new file mode 100644 index 00000000..70a3d486 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/esm-aliases/expected.mjs @@ -0,0 +1 @@ +import { Agent as CustomAgent, ServerResponse as Res, STATUS_CODES } from 'node:http'; diff --git a/recipes/http-internal-modules-to-node-http/tests/esm-aliases/input.mjs b/recipes/http-internal-modules-to-node-http/tests/esm-aliases/input.mjs new file mode 100644 index 00000000..70d52a13 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/esm-aliases/input.mjs @@ -0,0 +1,2 @@ +import { Agent as CustomAgent } from '_http_agent'; +import { ServerResponse as Res, STATUS_CODES } from '_http_server'; diff --git a/recipes/http-internal-modules-to-node-http/tests/esm-named/expected.mjs b/recipes/http-internal-modules-to-node-http/tests/esm-named/expected.mjs new file mode 100644 index 00000000..8548dfcb --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/esm-named/expected.mjs @@ -0,0 +1 @@ +import { IncomingMessage } from 'node:http'; diff --git a/recipes/http-internal-modules-to-node-http/tests/esm-named/input.mjs b/recipes/http-internal-modules-to-node-http/tests/esm-named/input.mjs new file mode 100644 index 00000000..10fda6fd --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/esm-named/input.mjs @@ -0,0 +1 @@ +import { IncomingMessage } from '_http_incoming'; diff --git a/recipes/http-internal-modules-to-node-http/tests/esm-node-prefix/expected.mjs b/recipes/http-internal-modules-to-node-http/tests/esm-node-prefix/expected.mjs new file mode 100644 index 00000000..5e77fcf7 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/esm-node-prefix/expected.mjs @@ -0,0 +1 @@ +import { ClientRequest } from 'node:http'; diff --git a/recipes/http-internal-modules-to-node-http/tests/esm-node-prefix/input.mjs b/recipes/http-internal-modules-to-node-http/tests/esm-node-prefix/input.mjs new file mode 100644 index 00000000..7a32ea84 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/esm-node-prefix/input.mjs @@ -0,0 +1 @@ +import { ClientRequest } from 'node:_http_client'; diff --git a/recipes/http-internal-modules-to-node-http/tests/mixed-internal-exports/expected.mjs b/recipes/http-internal-modules-to-node-http/tests/mixed-internal-exports/expected.mjs new file mode 100644 index 00000000..08bde017 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/mixed-internal-exports/expected.mjs @@ -0,0 +1,2 @@ +import { _someInternalExport } from '_http_agent'; +import { Agent } from 'node:http'; diff --git a/recipes/http-internal-modules-to-node-http/tests/mixed-internal-exports/input.mjs b/recipes/http-internal-modules-to-node-http/tests/mixed-internal-exports/input.mjs new file mode 100644 index 00000000..daabc8c3 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/mixed-internal-exports/input.mjs @@ -0,0 +1 @@ +import { Agent, _someInternalExport } from '_http_agent'; diff --git a/recipes/http-internal-modules-to-node-http/tests/re-exports/expected.mjs b/recipes/http-internal-modules-to-node-http/tests/re-exports/expected.mjs new file mode 100644 index 00000000..96f4b855 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/re-exports/expected.mjs @@ -0,0 +1,2 @@ +export { IncomingMessage } from 'node:http'; +export { Agent as HttpAgent } from 'node:http'; diff --git a/recipes/http-internal-modules-to-node-http/tests/re-exports/input.mjs b/recipes/http-internal-modules-to-node-http/tests/re-exports/input.mjs new file mode 100644 index 00000000..d4042efc --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/re-exports/input.mjs @@ -0,0 +1,2 @@ +export { IncomingMessage } from '_http_incoming'; +export { Agent as HttpAgent } from 'node:_http_agent'; diff --git a/recipes/http-internal-modules-to-node-http/tests/typescript/expected.ts b/recipes/http-internal-modules-to-node-http/tests/typescript/expected.ts new file mode 100644 index 00000000..f9fb9e0e --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/typescript/expected.ts @@ -0,0 +1,3 @@ +import type { IncomingMessage, ServerResponse } from 'node:http'; + +function handle(req: IncomingMessage, res: ServerResponse): void {} diff --git a/recipes/http-internal-modules-to-node-http/tests/typescript/input.ts b/recipes/http-internal-modules-to-node-http/tests/typescript/input.ts new file mode 100644 index 00000000..4a5408b6 --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/typescript/input.ts @@ -0,0 +1,4 @@ +import type { IncomingMessage } from '_http_incoming'; +import type { ServerResponse } from 'node:_http_server'; + +function handle(req: IncomingMessage, res: ServerResponse): void {} diff --git a/recipes/http-internal-modules-to-node-http/tests/unresolved-cases/expected.mjs b/recipes/http-internal-modules-to-node-http/tests/unresolved-cases/expected.mjs new file mode 100644 index 00000000..7931437d --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/unresolved-cases/expected.mjs @@ -0,0 +1,3 @@ +const agent = require('_http_agent'); +import * as server from '_http_server'; +import { HTTPParser } from '_http_common'; diff --git a/recipes/http-internal-modules-to-node-http/tests/unresolved-cases/input.mjs b/recipes/http-internal-modules-to-node-http/tests/unresolved-cases/input.mjs new file mode 100644 index 00000000..7931437d --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/tests/unresolved-cases/input.mjs @@ -0,0 +1,3 @@ +const agent = require('_http_agent'); +import * as server from '_http_server'; +import { HTTPParser } from '_http_common'; diff --git a/recipes/http-internal-modules-to-node-http/workflow.yaml b/recipes/http-internal-modules-to-node-http/workflow.yaml new file mode 100644 index 00000000..906d1e2a --- /dev/null +++ b/recipes/http-internal-modules-to-node-http/workflow.yaml @@ -0,0 +1,25 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/codemod-com/codemod/refs/heads/main/schemas/workflow.json + +version: "1" + +nodes: + - id: apply-transforms + name: Apply AST Transformations + type: automatic + steps: + - name: Handle DEP0199 by migrating internal HTTP module imports to node:http + js-ast-grep: + js_file: src/workflow.ts + base_path: . + include: + - "**/*.js" + - "**/*.jsx" + - "**/*.mjs" + - "**/*.cjs" + - "**/*.cts" + - "**/*.mts" + - "**/*.ts" + - "**/*.tsx" + exclude: + - "**/node_modules/**" + language: typescript From 16821afb4c97b40d5d54bdb3ee3c3571f5feb984 Mon Sep 17 00:00:00 2001 From: Vishal Raj <9031842908.vk@gmail.com> Date: Thu, 19 Nov 2026 10:56:42 +0530 Subject: [PATCH 2/4] refactor(DEP0199): use workspace ast-grep utilities and sync lockfile Signed-off-by: Vishal Raj <9031842908.vk@gmail.com> --- package-lock.json | 14 + .../src/workflow.ts | 485 ++++++++++-------- 2 files changed, 281 insertions(+), 218 deletions(-) diff --git a/package-lock.json b/package-lock.json index 287f3675..18075943 100644 --- a/package-lock.json +++ b/package-lock.json @@ -533,6 +533,10 @@ "resolved": "recipes/http-classes-with-new", "link": true }, + "node_modules/@nodejs/http-internal-modules-to-node-http": { + "resolved": "recipes/http-internal-modules-to-node-http", + "link": true + }, "node_modules/@nodejs/http-outgoingmessage-headers": { "resolved": "recipes/http-outgoingmessage-headers", "link": true @@ -1180,6 +1184,16 @@ "@codemod.com/jssg-types": "^1.6.3" } }, + "recipes/http-internal-modules-to-node-http": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@nodejs/codemod-utils": "*" + }, + "devDependencies": { + "@codemod.com/jssg-types": "^1.6.3" + } + }, "recipes/http-outgoingmessage-headers": { "name": "@nodejs/http-outgoingmessage-headers", "dependencies": { diff --git a/recipes/http-internal-modules-to-node-http/src/workflow.ts b/recipes/http-internal-modules-to-node-http/src/workflow.ts index 28960b7d..99b62915 100644 --- a/recipes/http-internal-modules-to-node-http/src/workflow.ts +++ b/recipes/http-internal-modules-to-node-http/src/workflow.ts @@ -5,6 +5,8 @@ import type { SgRoot, } from '@codemod.com/jssg-types/main'; import type Js from '@codemod.com/jssg-types/langs/javascript'; +import { getNodeImportStatements, getNodeImportCalls } from '@nodejs/codemod-utils/ast-grep/import-statement'; +import { getNodeRequireCalls } from '@nodejs/codemod-utils/ast-grep/require-call'; import { removeLines } from '@nodejs/codemod-utils/ast-grep/remove-lines'; /** @@ -22,6 +24,8 @@ const MODULE_EXPORTS: Record> = { _http_server: new Set(['Server', 'ServerResponse', 'STATUS_CODES']), }; +const TARGET_MODULES = Object.keys(MODULE_EXPORTS); + function getInternalModuleName(specifier: string): string | null { const cleaned = specifier.replace(/^node:/, ''); if (cleaned in MODULE_EXPORTS) { @@ -66,7 +70,7 @@ export default function transform(root: SgRoot): string | null { const edits: Edit[] = []; const linesToRemove: Range[] = []; - // Check for excluded modules like _http_common + // Warn on excluded modules like _http_common const allStrings = rootNode.findAll({ rule: { kind: 'string' } }); for (const str of allStrings) { const unquoted = getUnquotedText(str); @@ -79,16 +83,16 @@ export default function transform(root: SgRoot): string | null { } } - // 1. Process ESM import statements + // 1. Process ESM import statements using getNodeImportStatements utility processImportStatements(root, rootNode, edits, linesToRemove); // 2. Process ESM export statements (re-exports) processExportStatements(root, rootNode, edits); - // 3. Process CommonJS require calls + // 3. Process CommonJS require calls using getNodeRequireCalls utility processRequireCalls(root, rootNode, edits); - // 4. Process dynamic import(...) calls + // 4. Process dynamic import(...) calls using getNodeImportCalls utility processDynamicImports(root, rootNode, edits); if (edits.length === 0 && linesToRemove.length === 0) { @@ -105,6 +109,7 @@ export default function transform(root: SgRoot): string | null { /** * Handle ESM import statements: + * - Uses getNodeImportStatements from @nodejs/codemod-utils for target and http imports * - Replaces specifier with 'node:http' when exports are supported * - Consolidates multiple compatible imports targeting 'node:http' * - Splits mixed imports (retaining unsupported exports in the internal module) @@ -116,99 +121,127 @@ function processImportStatements( edits: Edit[], linesToRemove: Range[], ): void { - const importStatements = rootNode.findAll({ - rule: { kind: 'import_statement' }, - }); - - // Find pre-existing node:http imports + // Find pre-existing node:http imports using the workspace utility and type import matching + const existingHttpStmts = [ + ...getNodeImportStatements(root, 'http'), + ...rootNode.findAll({ + rule: { + kind: 'import_statement', + has: { + field: 'source', + kind: 'string', + has: { + kind: 'string_fragment', + regex: '^(node:)?http$', + }, + }, + pattern: 'import type $$$IMPORTS from $SOURCE', + }, + }), + ]; const existingHttpImports: { statement: SgNode; isTypeOnly: boolean; namedImports: SgNode | null; - }[] = []; + }[] = existingHttpStmts.map((stmt) => ({ + statement: stmt, + isTypeOnly: stmt.text().startsWith('import type'), + namedImports: stmt.find({ rule: { kind: 'named_imports' } }), + })); const internalImports: ImportStatementInfo[] = []; - for (const stmt of importStatements) { - const sourceNode = stmt.field('source'); - if (!sourceNode) continue; - - const rawSource = getUnquotedText(sourceNode); - const normalized = rawSource.replace(/^node:/, ''); - - if (normalized === 'http') { - const isTypeOnly = stmt.text().startsWith('import type'); - const namedImports = stmt.find({ rule: { kind: 'named_imports' } }); - existingHttpImports.push({ statement: stmt, isTypeOnly, namedImports }); - continue; - } - - const internalMod = getInternalModuleName(rawSource); - if (!internalMod) continue; - - // Check for namespace import: import * as foo from '_http_*' - const nsImport = stmt.find({ rule: { kind: 'namespace_import' } }); - if (nsImport) { - warn( - root, - stmt, - `Namespace import '${nsImport.text()}' from '${rawSource}' is skipped; review manually (DEP0199)`, - ); - continue; - } - - const specifiers = stmt.findAll({ rule: { kind: 'import_specifier' } }); - if (specifiers.length === 0) { - warn( - root, - stmt, - `Import from '${rawSource}' without named specifiers is skipped; review manually (DEP0199)`, - ); - continue; - } - - const isTypeOnly = stmt.text().startsWith('import type'); - const supported: SpecifierInfo[] = []; - const unsupported: SpecifierInfo[] = []; - - for (const spec of specifiers) { - const nameNode = spec.field('name'); - const aliasNode = spec.field('alias'); - const imported = nameNode ? nameNode.text() : spec.text(); - const local = aliasNode ? aliasNode.text() : imported; + for (const mod of TARGET_MODULES) { + const statements = [ + ...getNodeImportStatements(root, mod), + ...rootNode.findAll({ + rule: { + kind: 'import_statement', + has: { + field: 'source', + kind: 'string', + has: { + kind: 'string_fragment', + regex: `^(node:)?${mod}$`, + }, + }, + pattern: 'import type $$$IMPORTS from $SOURCE', + }, + }), + ]; + + for (const stmt of statements) { + const sourceNode = stmt.field('source'); + if (!sourceNode) continue; + + const rawSource = getUnquotedText(sourceNode); + const internalMod = getInternalModuleName(rawSource); + if (!internalMod) continue; + + // Check for namespace import: import * as foo from '_http_*' + const nsImport = stmt.find({ rule: { kind: 'namespace_import' } }); + if (nsImport) { + warn( + root, + stmt, + `Namespace import '${nsImport.text()}' from '${rawSource}' is skipped; review manually (DEP0199)`, + ); + continue; + } - if (MODULE_EXPORTS[internalMod].has(imported)) { - supported.push({ - node: spec, - text: spec.text(), - imported, - local, - }); - } else { - unsupported.push({ - node: spec, - text: spec.text(), - imported, - local, - }); + const specifiers = stmt.findAll({ rule: { kind: 'import_specifier' } }); + if (specifiers.length === 0) { warn( root, - spec, - `Internal-only export '${imported}' from '${rawSource}' cannot be migrated to 'node:http' (DEP0199)`, + stmt, + `Import from '${rawSource}' without named specifiers is skipped; review manually (DEP0199)`, ); + continue; } - } - if (supported.length > 0) { - internalImports.push({ - statement: stmt, - sourceNode, - rawSource, - internalMod, - isTypeOnly, - supported, - unsupported, - }); + const isTypeOnly = stmt.text().startsWith('import type'); + const supported: SpecifierInfo[] = []; + const unsupported: SpecifierInfo[] = []; + + for (const spec of specifiers) { + const nameNode = spec.field('name'); + const aliasNode = spec.field('alias'); + const imported = nameNode ? nameNode.text() : spec.text(); + const local = aliasNode ? aliasNode.text() : imported; + + if (MODULE_EXPORTS[internalMod].has(imported)) { + supported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + } else { + unsupported.push({ + node: spec, + text: spec.text(), + imported, + local, + }); + warn( + root, + spec, + `Internal-only export '${imported}' from '${rawSource}' cannot be migrated to 'node:http' (DEP0199)`, + ); + } + } + + if (supported.length > 0) { + internalImports.push({ + statement: stmt, + sourceNode, + rawSource, + internalMod, + isTypeOnly, + supported, + unsupported, + }); + } } } @@ -250,7 +283,6 @@ function consolidateImportsGroup( // Case 1: Consolidate into pre-existing node:http import if (existingHttp?.namedImports) { const existingNamedText = existingHttp.namedImports.text(); - // Parse existing specifiers const existingSpecs = existingNamedText .replace(/^\{\s*|\s*\}$/g, '') .split(',') @@ -268,10 +300,8 @@ function consolidateImportsGroup( } if (imp.unsupported.length === 0) { - // Entire import migrated; remove line linesToRemove.push(imp.statement.range()); } else { - // Mixed import: keep only unsupported specifiers const named = imp.statement.find({ rule: { kind: 'named_imports' }, }); @@ -301,12 +331,10 @@ function consolidateImportsGroup( const [first, ...rest] = imports; if (rest.length === 0 && first.unsupported.length === 0) { - // Single completely supported import: just update source edits.push(first.sourceNode.replace("'node:http'")); return; } - // Consolidate into first const consolidatedSpecs: string[] = []; for (const sup of first.supported) { if (!consolidatedSpecs.includes(sup.text)) { @@ -335,14 +363,12 @@ function consolidateImportsGroup( } if (first.unsupported.length === 0) { - // Replace first statement's source and specifiers edits.push(first.sourceNode.replace("'node:http'")); const named = first.statement.find({ rule: { kind: 'named_imports' } }); if (named) { edits.push(named.replace(`{ ${consolidatedSpecs.join(', ')} }`)); } } else { - // First was mixed: keep unsupported in first, and append new node:http import const remaining = first.unsupported.map((u) => u.text).join(', '); const typePrefix = first.isTypeOnly ? 'type ' : ''; const firstSource = first.sourceNode.text(); @@ -409,7 +435,6 @@ function processExportStatements( if (supported.length > 0 && unsupported.length === 0) { edits.push(sourceNode.replace("'node:http'")); } else if (supported.length > 0 && unsupported.length > 0) { - // Mixed re-export: keep unsupported, add supported const remaining = unsupported.map((u) => u.text).join(', '); const supText = supported.map((s) => s.text).join(', '); const sourceText = sourceNode.text(); @@ -421,58 +446,81 @@ function processExportStatements( /** * Handle CommonJS require calls: - * - const { Server } = require('_http_server'); - * - const Server = require('_http_server').Server; - * - const agent = require('_http_agent'); (skipped / warned) + * - Uses getNodeRequireCalls from @nodejs/codemod-utils for target modules + * - Handles destructuring: const { Server } = require('_http_server'); + * - Handles member expressions: const Server = require('_http_server').Server; + * - Skips and warns on namespace objects: const agent = require('_http_agent'); */ function processRequireCalls( root: SgRoot, rootNode: SgNode, edits: Edit[], ): void { - const requireCalls = rootNode.findAll({ + // Member expressions: const Server = require('_http_server').Server; + const memberRequires = rootNode.findAll({ rule: { - kind: 'call_expression', - has: { - field: 'function', - kind: 'identifier', - regex: '^require$', - }, + kind: 'member_expression', + all: [ + { + has: { + field: 'object', + kind: 'call_expression', + all: [ + { + has: { + field: 'function', + kind: 'identifier', + regex: '^require$', + }, + }, + ], + }, + }, + ], }, }); - for (const call of requireCalls) { - const args = call.field('arguments'); - if (!args) continue; - - const stringArg = args.find({ rule: { kind: 'string' } }); + for (const expr of memberRequires) { + const call = expr.field('object'); + const stringArg = call?.field('arguments')?.find({ rule: { kind: 'string' } }); if (!stringArg) continue; const rawSource = getUnquotedText(stringArg); const internalMod = getInternalModuleName(rawSource); if (!internalMod) continue; - const parent = call.parent(); - if (!parent) continue; - - // Case A: Member expression: require('_http_server').Server - if (parent.is('member_expression')) { - const prop = parent.field('property'); - if (prop && MODULE_EXPORTS[internalMod].has(prop.text())) { - edits.push(stringArg.replace("'node:http'")); - } else { - warn( - root, - prop || call, - `Unknown/internal property '${prop?.text()}' on '${rawSource}' is skipped; review manually (DEP0199)`, - ); - } - continue; + const prop = expr.field('property'); + if (prop && MODULE_EXPORTS[internalMod].has(prop.text())) { + edits.push(stringArg.replace("'node:http'")); + } else { + warn( + root, + prop || expr, + `Unknown/internal property '${prop?.text()}' on '${rawSource}' is skipped; review manually (DEP0199)`, + ); } + } + + // Use getNodeRequireCalls from local workspace utility for variable declarations + for (const mod of TARGET_MODULES) { + const declarators = getNodeRequireCalls(root, mod); + + for (const declarator of declarators) { + // Skip declarators whose value is a member_expression (handled above) + if (declarator.field('value')?.is('member_expression')) continue; + + const call = declarator.find({ + rule: { + kind: 'call_expression', + has: { field: 'function', regex: '^require$' }, + }, + }); + const stringArg = call?.field('arguments')?.find({ rule: { kind: 'string' } }); + if (!stringArg) continue; + + const rawSource = getUnquotedText(stringArg); + const namePattern = declarator.field('name'); - // Case B: Variable declarator: const { Server } = require(...) - if (parent.is('variable_declarator')) { - const namePattern = parent.field('name'); if (namePattern?.is('object_pattern')) { const shorthandProps = namePattern.findAll({ rule: { kind: 'shorthand_property_identifier_pattern' }, @@ -486,7 +534,7 @@ function processRequireCalls( for (const sh of shorthandProps) { const name = sh.text(); - if (MODULE_EXPORTS[internalMod].has(name)) { + if (MODULE_EXPORTS[mod].has(name)) { supportedNames.push(name); } else { unsupportedNames.push(name); @@ -500,7 +548,7 @@ function processRequireCalls( for (const pair of pairProps) { const key = pair.field('key')?.text() || ''; - if (MODULE_EXPORTS[internalMod].has(key)) { + if (MODULE_EXPORTS[mod].has(key)) { supportedNames.push(pair.text()); } else { unsupportedNames.push(pair.text()); @@ -518,8 +566,7 @@ function processRequireCalls( supportedNames.length > 0 && unsupportedNames.length > 0 ) { - // Mixed destructuring: keep unsupported, add new require for supported - const declParent = parent.parent(); // lexical_declaration or variable_declaration + const declParent = declarator.parent(); const kind = declParent?.kind() === 'lexical_declaration' ? 'const' : 'var'; const newDecl = `${kind} { ${unsupportedNames.join(', ')} } = require(${stringArg.text()});\n${kind} { ${supportedNames.join(', ')} } = require('node:http');`; if (declParent) { @@ -529,10 +576,10 @@ function processRequireCalls( continue; } - // Case C: Un-destructured namespace object: const agent = require('_http_agent') + // Un-destructured namespace object: const agent = require('_http_agent') warn( root, - parent, + declarator, `Namespace object '${namePattern?.text()}' from '${rawSource}' is skipped; review manually (DEP0199)`, ); } @@ -541,113 +588,115 @@ function processRequireCalls( /** * Handle dynamic import(...) calls: - * - const { Server } = await import('_http_server'); - * - const server = await import('_http_server').then(m => m.Server); + * - Uses getNodeImportCalls from @nodejs/codemod-utils for target modules + * - Handles: const { Server } = await import('_http_server'); + * - Handles: import('_http_agent').then(m => m.Agent); */ function processDynamicImports( root: SgRoot, rootNode: SgNode, edits: Edit[], ): void { - const dynamicImports = rootNode.findAll({ + for (const mod of TARGET_MODULES) { + // Declarators with await import(mod) + const declarators = getNodeImportCalls(root, mod); + + for (const declarator of declarators) { + const name = declarator.field('name'); + if (name?.is('object_pattern')) { + const props = name.findAll({ + rule: { + any: [ + { kind: 'shorthand_property_identifier_pattern' }, + { kind: 'pair_pattern' }, + ], + }, + }); + const allSupported = + props.length > 0 && + props.every((p) => { + const key = + p.is('pair_pattern') ? p.field('key')?.text() || '' : p.text(); + return MODULE_EXPORTS[mod].has(key); + }); + + if (allSupported) { + const stringArg = declarator.find({ + rule: { kind: 'string' }, + }); + if (stringArg) { + edits.push(stringArg.replace("'node:http'")); + } + } + } + } + } + + // Chained .then(...) calls: import('_http_*').then(...) + const thenImports = rootNode.findAll({ rule: { kind: 'call_expression', - has: { - field: 'function', - kind: 'import', - }, + all: [ + { + has: { + field: 'function', + kind: 'member_expression', + has: { field: 'property', regex: '^then$' }, + }, + }, + ], }, }); - for (const call of dynamicImports) { - const args = call.field('arguments'); - if (!args) continue; + for (const thenCall of thenImports) { + const memberFn = thenCall.field('function'); + const objectCall = memberFn?.field('object'); + if (!objectCall?.is('call_expression')) continue; - const stringArg = args.find({ rule: { kind: 'string' } }); + const importFn = objectCall.field('function'); + if (importFn?.kind() !== 'import') continue; + + const stringArg = objectCall.field('arguments')?.find({ rule: { kind: 'string' } }); if (!stringArg) continue; const rawSource = getUnquotedText(stringArg); const internalMod = getInternalModuleName(rawSource); if (!internalMod) continue; - // Walk up to find if exports are destructured or accessed via .then - const current: SgNode | null = call; - let isSupported = false; + const callback = thenCall.field('arguments')?.child(1); + if (!callback) continue; - // Check parent: await import(...) - const parent = current.parent(); - if (parent?.is('await_expression')) { - const grandParent = parent.parent(); - if (grandParent?.is('variable_declarator')) { - const name = grandParent.field('name'); - if (name?.is('object_pattern')) { - const props = name.findAll({ - rule: { - any: [ - { kind: 'shorthand_property_identifier_pattern' }, - { kind: 'pair_pattern' }, - ], - }, - }); - const allSupported = - props.length > 0 && - props.every((p) => { - const key = - p.is('pair_pattern') ? p.field('key')?.text() || '' : p.text(); - return MODULE_EXPORTS[internalMod].has(key); - }); - if (allSupported) { - isSupported = true; - } - } + let isSupported = false; + const param = callback.field('parameters') || callback.field('parameter'); + if (param) { + const destructured = param.findAll({ + rule: { + any: [ + { kind: 'shorthand_property_identifier_pattern' }, + { kind: 'pair_pattern' }, + ], + }, + }); + if ( + destructured.length > 0 && + destructured.every((p) => { + const key = + p.is('pair_pattern') ? p.field('key')?.text() || '' : p.text(); + return MODULE_EXPORTS[internalMod].has(key); + }) + ) { + isSupported = true; } } - // Check chained .then: import(...).then(...) - const callParent = call.parent(); - if ( - callParent?.is('member_expression') && - callParent.field('property')?.text() === 'then' - ) { - const thenCall = callParent.parent(); - if (thenCall?.is('call_expression')) { - const thenArgs = thenCall.field('arguments'); - const callback = thenArgs?.child(1); // child(0) is '(', child(1) is callback function - if (callback) { - // Check if callback accesses supported member: m => m.Server or ({ Server }) => ... - const param = callback.field('parameters') || callback.field('parameter'); - if (param) { - const destructured = param.findAll({ - rule: { - any: [ - { kind: 'shorthand_property_identifier_pattern' }, - { kind: 'pair_pattern' }, - ], - }, - }); - if ( - destructured.length > 0 && - destructured.every((p) => { - const key = - p.is('pair_pattern') ? p.field('key')?.text() || '' : p.text(); - return MODULE_EXPORTS[internalMod].has(key); - }) - ) { - isSupported = true; - } - } - // Check return / body member expression: m.Server - const members = callback.findAll({ - rule: { kind: 'member_expression' }, - }); - for (const m of members) { - const prop = m.field('property')?.text() || ''; - if (MODULE_EXPORTS[internalMod].has(prop)) { - isSupported = true; - break; - } - } - } + const members = callback.findAll({ + rule: { kind: 'member_expression' }, + }); + for (const m of members) { + const prop = m.field('property')?.text() || ''; + if (MODULE_EXPORTS[internalMod].has(prop)) { + isSupported = true; + break; } } @@ -656,7 +705,7 @@ function processDynamicImports( } else { warn( root, - call, + thenCall, `Dynamic import of '${rawSource}' without verified public exports is skipped; review manually (DEP0199)`, ); } From b06d13a2b3bee67ff759d512f8497029cb0147e8 Mon Sep 17 00:00:00 2001 From: Vishal Raj <9031842908.vk@gmail.com> Date: Fri, 20 Nov 2026 00:04:05 +0530 Subject: [PATCH 3/4] refactor(http-internal-modules-to-node-http): address review feedback Use ast-grep string_fragment query instead of regex for unquoting string nodes. Simplify import and require handling by leveraging @nodejs/codemod-utils directly, replace kind() === checks with .is(), handle newlines dynamically, and update test fixtures. Signed-off-by: Vishal Raj <9031842908.vk@gmail.com> --- .../src/workflow.ts | 259 ++++++------------ .../tests/typescript/expected.ts | 2 +- .../tests/typescript/input.ts | 4 +- 3 files changed, 93 insertions(+), 172 deletions(-) diff --git a/recipes/http-internal-modules-to-node-http/src/workflow.ts b/recipes/http-internal-modules-to-node-http/src/workflow.ts index 99b62915..b98704f0 100644 --- a/recipes/http-internal-modules-to-node-http/src/workflow.ts +++ b/recipes/http-internal-modules-to-node-http/src/workflow.ts @@ -5,7 +5,10 @@ import type { SgRoot, } from '@codemod.com/jssg-types/main'; import type Js from '@codemod.com/jssg-types/langs/javascript'; -import { getNodeImportStatements, getNodeImportCalls } from '@nodejs/codemod-utils/ast-grep/import-statement'; +import { + getNodeImportStatements, + getNodeImportCalls, +} from '@nodejs/codemod-utils/ast-grep/import-statement'; import { getNodeRequireCalls } from '@nodejs/codemod-utils/ast-grep/require-call'; import { removeLines } from '@nodejs/codemod-utils/ast-grep/remove-lines'; @@ -35,7 +38,7 @@ function getInternalModuleName(specifier: string): string | null { } function getUnquotedText(node: SgNode): string { - return node.text().replace(/^['"`]|['"`]$/g, ''); + return node.find({ rule: { kind: 'string_fragment' } })?.text() ?? ''; } function warn(root: SgRoot, node: SgNode, message: string): void { @@ -57,7 +60,6 @@ type ImportStatementInfo = { sourceNode: SgNode; rawSource: string; internalMod: string; - isTypeOnly: boolean; supported: SpecifierInfo[]; unsupported: SpecifierInfo[]; }; @@ -69,28 +71,32 @@ export default function transform(root: SgRoot): string | null { const rootNode = root.root(); const edits: Edit[] = []; const linesToRemove: Range[] = []; + const nl = rootNode.text().includes('\r\n') ? '\r\n' : '\n'; // Warn on excluded modules like _http_common - const allStrings = rootNode.findAll({ rule: { kind: 'string' } }); - for (const str of allStrings) { - const unquoted = getUnquotedText(str); - if (unquoted.replace(/^node:/, '') === '_http_common') { - warn( - root, - str, - '_http_common internals such as HTTPParser are excluded from migration to node:http (DEP0199)', - ); - } + const allCommons = rootNode.findAll({ + rule: { + kind: 'string_fragment', + regex: '^(node:)?_http_common$', + }, + }); + for (const frag of allCommons) { + const str = frag.parent() ?? frag; + warn( + root, + str, + '_http_common internals such as HTTPParser are excluded from migration to node:http (DEP0199)', + ); } // 1. Process ESM import statements using getNodeImportStatements utility - processImportStatements(root, rootNode, edits, linesToRemove); + processImportStatements(root, rootNode, edits, linesToRemove, nl); // 2. Process ESM export statements (re-exports) processExportStatements(root, rootNode, edits); // 3. Process CommonJS require calls using getNodeRequireCalls utility - processRequireCalls(root, rootNode, edits); + processRequireCalls(root, rootNode, edits, nl); // 4. Process dynamic import(...) calls using getNodeImportCalls utility processDynamicImports(root, rootNode, edits); @@ -117,58 +123,22 @@ export default function transform(root: SgRoot): string | null { */ function processImportStatements( root: SgRoot, - rootNode: SgNode, + _rootNode: SgNode, edits: Edit[], linesToRemove: Range[], + nl: string, ): void { - // Find pre-existing node:http imports using the workspace utility and type import matching - const existingHttpStmts = [ - ...getNodeImportStatements(root, 'http'), - ...rootNode.findAll({ - rule: { - kind: 'import_statement', - has: { - field: 'source', - kind: 'string', - has: { - kind: 'string_fragment', - regex: '^(node:)?http$', - }, - }, - pattern: 'import type $$$IMPORTS from $SOURCE', - }, - }), - ]; - const existingHttpImports: { - statement: SgNode; - isTypeOnly: boolean; - namedImports: SgNode | null; - }[] = existingHttpStmts.map((stmt) => ({ + const existingHttpStmts = getNodeImportStatements(root, 'http'); + + const existingHttpImports = existingHttpStmts.map((stmt) => ({ statement: stmt, - isTypeOnly: stmt.text().startsWith('import type'), namedImports: stmt.find({ rule: { kind: 'named_imports' } }), })); const internalImports: ImportStatementInfo[] = []; for (const mod of TARGET_MODULES) { - const statements = [ - ...getNodeImportStatements(root, mod), - ...rootNode.findAll({ - rule: { - kind: 'import_statement', - has: { - field: 'source', - kind: 'string', - has: { - kind: 'string_fragment', - regex: `^(node:)?${mod}$`, - }, - }, - pattern: 'import type $$$IMPORTS from $SOURCE', - }, - }), - ]; + const statements = getNodeImportStatements(root, mod); for (const stmt of statements) { const sourceNode = stmt.field('source'); @@ -199,7 +169,6 @@ function processImportStatements( continue; } - const isTypeOnly = stmt.text().startsWith('import type'); const supported: SpecifierInfo[] = []; const unsupported: SpecifierInfo[] = []; @@ -237,7 +206,6 @@ function processImportStatements( sourceNode, rawSource, internalMod, - isTypeOnly, supported, unsupported, }); @@ -247,40 +215,28 @@ function processImportStatements( if (internalImports.length === 0) return; - // Group internal imports by type-only status - const valueInternal = internalImports.filter((i) => !i.isTypeOnly); - const typeInternal = internalImports.filter((i) => i.isTypeOnly); - - consolidateImportsGroup( - valueInternal, - existingHttpImports.find((e) => !e.isTypeOnly), - edits, - linesToRemove, - ); - - consolidateImportsGroup( - typeInternal, - existingHttpImports.find((e) => e.isTypeOnly), + consolidateImports( + internalImports, + existingHttpImports[0], edits, linesToRemove, + nl, ); } -function consolidateImportsGroup( +function consolidateImports( imports: ImportStatementInfo[], existingHttp: | { statement: SgNode; - isTypeOnly: boolean; namedImports: SgNode | null; } | undefined, edits: Edit[], linesToRemove: Range[], + nl: string, ): void { - if (imports.length === 0) return; - - // Case 1: Consolidate into pre-existing node:http import + // Case 1: An existing node:http import already exists if (existingHttp?.namedImports) { const existingNamedText = existingHttp.namedImports.text(); const existingSpecs = existingNamedText @@ -370,16 +326,15 @@ function consolidateImportsGroup( } } else { const remaining = first.unsupported.map((u) => u.text).join(', '); - const typePrefix = first.isTypeOnly ? 'type ' : ''; const firstSource = first.sourceNode.text(); - const newStmt = `import ${typePrefix}{ ${remaining} } from ${firstSource};\nimport ${typePrefix}{ ${consolidatedSpecs.join(', ')} } from 'node:http';`; + const newStmt = `import { ${remaining} } from ${firstSource};${nl}import { ${consolidatedSpecs.join(', ')} } from 'node:http';`; edits.push(first.statement.replace(newStmt)); } } /** * Handle ESM export statements (re-exports): - * - export { IncomingMessage } from '_http_incoming'; + * - export { Server } from '_http_server'; */ function processExportStatements( root: SgRoot, @@ -401,45 +356,33 @@ function processExportStatements( const specifiers = stmt.findAll({ rule: { kind: 'export_specifier' } }); if (specifiers.length === 0) continue; - const supported: SpecifierInfo[] = []; - const unsupported: SpecifierInfo[] = []; + const supportedNames: string[] = []; + const unsupportedNames: string[] = []; for (const spec of specifiers) { const nameNode = spec.field('name'); - const aliasNode = spec.field('alias'); - const imported = nameNode ? nameNode.text() : spec.text(); - const local = aliasNode ? aliasNode.text() : imported; - - if (MODULE_EXPORTS[internalMod].has(imported)) { - supported.push({ - node: spec, - text: spec.text(), - imported, - local, - }); + const exportedName = nameNode ? nameNode.text() : spec.text(); + + if (MODULE_EXPORTS[internalMod].has(exportedName)) { + supportedNames.push(spec.text()); } else { - unsupported.push({ - node: spec, - text: spec.text(), - imported, - local, - }); + unsupportedNames.push(spec.text()); warn( root, spec, - `Internal-only re-export '${imported}' from '${rawSource}' cannot be migrated to 'node:http' (DEP0199)`, + `Internal-only export '${exportedName}' from '${rawSource}' cannot be re-exported from 'node:http' (DEP0199)`, ); } } - if (supported.length > 0 && unsupported.length === 0) { + if (supportedNames.length > 0 && unsupportedNames.length === 0) { edits.push(sourceNode.replace("'node:http'")); - } else if (supported.length > 0 && unsupported.length > 0) { - const remaining = unsupported.map((u) => u.text).join(', '); - const supText = supported.map((s) => s.text).join(', '); - const sourceText = sourceNode.text(); - const newStmt = `export { ${remaining} } from ${sourceText};\nexport { ${supText} } from 'node:http';`; - edits.push(stmt.replace(newStmt)); + } else if (supportedNames.length > 0 && unsupportedNames.length > 0) { + warn( + root, + stmt, + `Export statement from '${rawSource}' contains mixed public and internal-only exports; review manually (DEP0199)`, + ); } } } @@ -453,69 +396,48 @@ function processExportStatements( */ function processRequireCalls( root: SgRoot, - rootNode: SgNode, + _rootNode: SgNode, edits: Edit[], + nl: string, ): void { - // Member expressions: const Server = require('_http_server').Server; - const memberRequires = rootNode.findAll({ - rule: { - kind: 'member_expression', - all: [ - { - has: { - field: 'object', - kind: 'call_expression', - all: [ - { - has: { - field: 'function', - kind: 'identifier', - regex: '^require$', - }, - }, - ], - }, - }, - ], - }, - }); - - for (const expr of memberRequires) { - const call = expr.field('object'); - const stringArg = call?.field('arguments')?.find({ rule: { kind: 'string' } }); - if (!stringArg) continue; - - const rawSource = getUnquotedText(stringArg); - const internalMod = getInternalModuleName(rawSource); - if (!internalMod) continue; - - const prop = expr.field('property'); - if (prop && MODULE_EXPORTS[internalMod].has(prop.text())) { - edits.push(stringArg.replace("'node:http'")); - } else { - warn( - root, - prop || expr, - `Unknown/internal property '${prop?.text()}' on '${rawSource}' is skipped; review manually (DEP0199)`, - ); - } - } - - // Use getNodeRequireCalls from local workspace utility for variable declarations for (const mod of TARGET_MODULES) { const declarators = getNodeRequireCalls(root, mod); for (const declarator of declarators) { - // Skip declarators whose value is a member_expression (handled above) - if (declarator.field('value')?.is('member_expression')) continue; + const value = declarator.field('value'); + if (!value) continue; - const call = declarator.find({ - rule: { - kind: 'call_expression', - has: { field: 'function', regex: '^require$' }, - }, - }); - const stringArg = call?.field('arguments')?.find({ rule: { kind: 'string' } }); + // Member expressions: const Server = require('_http_server').Server; + if (value.is('member_expression')) { + const call = value.find({ rule: { kind: 'call_expression' } }); + const stringArg = call?.find({ rule: { kind: 'string' } }); + if (!stringArg) continue; + + const prop = value.field('property'); + const propName = prop?.text() || ''; + + if (MODULE_EXPORTS[mod].has(propName)) { + edits.push(stringArg.replace("'node:http'")); + } else { + warn( + root, + prop || value, + `Unknown/internal property '${propName}' on '${getUnquotedText(stringArg)}' is skipped; review manually (DEP0199)`, + ); + } + continue; + } + + // Call expressions with destructuring: const { Server } = require('_http_server'); + const call = value.is('call_expression') + ? value + : value.find({ + rule: { + kind: 'call_expression', + has: { field: 'function', regex: '^require$' }, + }, + }); + const stringArg = call?.find({ rule: { kind: 'string' } }); if (!stringArg) continue; const rawSource = getUnquotedText(stringArg); @@ -567,8 +489,8 @@ function processRequireCalls( unsupportedNames.length > 0 ) { const declParent = declarator.parent(); - const kind = declParent?.kind() === 'lexical_declaration' ? 'const' : 'var'; - const newDecl = `${kind} { ${unsupportedNames.join(', ')} } = require(${stringArg.text()});\n${kind} { ${supportedNames.join(', ')} } = require('node:http');`; + const kind = declParent?.is('lexical_declaration') ? 'const' : 'var'; + const newDecl = `${kind} { ${unsupportedNames.join(', ')} } = require(${stringArg.text()});${nl}${kind} { ${supportedNames.join(', ')} } = require('node:http');`; if (declParent) { edits.push(declParent.replace(newDecl)); } @@ -590,7 +512,7 @@ function processRequireCalls( * Handle dynamic import(...) calls: * - Uses getNodeImportCalls from @nodejs/codemod-utils for target modules * - Handles: const { Server } = await import('_http_server'); - * - Handles: import('_http_agent').then(m => m.Agent); + * - Handles: import('_http_server').then(m => m.createServer); */ function processDynamicImports( root: SgRoot, @@ -598,7 +520,6 @@ function processDynamicImports( edits: Edit[], ): void { for (const mod of TARGET_MODULES) { - // Declarators with await import(mod) const declarators = getNodeImportCalls(root, mod); for (const declarator of declarators) { @@ -654,7 +575,7 @@ function processDynamicImports( if (!objectCall?.is('call_expression')) continue; const importFn = objectCall.field('function'); - if (importFn?.kind() !== 'import') continue; + if (!importFn?.is('import')) continue; const stringArg = objectCall.field('arguments')?.find({ rule: { kind: 'string' } }); if (!stringArg) continue; diff --git a/recipes/http-internal-modules-to-node-http/tests/typescript/expected.ts b/recipes/http-internal-modules-to-node-http/tests/typescript/expected.ts index f9fb9e0e..18245c94 100644 --- a/recipes/http-internal-modules-to-node-http/tests/typescript/expected.ts +++ b/recipes/http-internal-modules-to-node-http/tests/typescript/expected.ts @@ -1,3 +1,3 @@ -import type { IncomingMessage, ServerResponse } from 'node:http'; +import { IncomingMessage, ServerResponse } from 'node:http'; function handle(req: IncomingMessage, res: ServerResponse): void {} diff --git a/recipes/http-internal-modules-to-node-http/tests/typescript/input.ts b/recipes/http-internal-modules-to-node-http/tests/typescript/input.ts index 4a5408b6..249d2bb3 100644 --- a/recipes/http-internal-modules-to-node-http/tests/typescript/input.ts +++ b/recipes/http-internal-modules-to-node-http/tests/typescript/input.ts @@ -1,4 +1,4 @@ -import type { IncomingMessage } from '_http_incoming'; -import type { ServerResponse } from 'node:_http_server'; +import { IncomingMessage } from '_http_incoming'; +import { ServerResponse } from 'node:_http_server'; function handle(req: IncomingMessage, res: ServerResponse): void {} From 7cf2ff659b6254b8015208152db874a183274fbd Mon Sep 17 00:00:00 2001 From: Vishal Raj <9031842908.vk@gmail.com> Date: Fri, 20 Nov 2026 10:09:05 +0530 Subject: [PATCH 4/4] refactor(http-internal-modules-to-node-http): inline string_fragment query and remove helper function Signed-off-by: Vishal Raj <9031842908.vk@gmail.com> --- .../src/workflow.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/recipes/http-internal-modules-to-node-http/src/workflow.ts b/recipes/http-internal-modules-to-node-http/src/workflow.ts index b98704f0..bb204acd 100644 --- a/recipes/http-internal-modules-to-node-http/src/workflow.ts +++ b/recipes/http-internal-modules-to-node-http/src/workflow.ts @@ -37,10 +37,6 @@ function getInternalModuleName(specifier: string): string | null { return null; } -function getUnquotedText(node: SgNode): string { - return node.find({ rule: { kind: 'string_fragment' } })?.text() ?? ''; -} - function warn(root: SgRoot, node: SgNode, message: string): void { const { start } = node.range(); console.warn( @@ -144,7 +140,8 @@ function processImportStatements( const sourceNode = stmt.field('source'); if (!sourceNode) continue; - const rawSource = getUnquotedText(sourceNode); + const rawSource = + sourceNode.find({ rule: { kind: 'string_fragment' } })?.text() ?? ''; const internalMod = getInternalModuleName(rawSource); if (!internalMod) continue; @@ -349,7 +346,8 @@ function processExportStatements( const sourceNode = stmt.field('source'); if (!sourceNode) continue; - const rawSource = getUnquotedText(sourceNode); + const rawSource = + sourceNode.find({ rule: { kind: 'string_fragment' } })?.text() ?? ''; const internalMod = getInternalModuleName(rawSource); if (!internalMod) continue; @@ -422,7 +420,7 @@ function processRequireCalls( warn( root, prop || value, - `Unknown/internal property '${propName}' on '${getUnquotedText(stringArg)}' is skipped; review manually (DEP0199)`, + `Unknown/internal property '${propName}' on '${stringArg.find({ rule: { kind: 'string_fragment' } })?.text() ?? ''}' is skipped; review manually (DEP0199)`, ); } continue; @@ -440,7 +438,8 @@ function processRequireCalls( const stringArg = call?.find({ rule: { kind: 'string' } }); if (!stringArg) continue; - const rawSource = getUnquotedText(stringArg); + const rawSource = + stringArg.find({ rule: { kind: 'string_fragment' } })?.text() ?? ''; const namePattern = declarator.field('name'); if (namePattern?.is('object_pattern')) { @@ -580,7 +579,8 @@ function processDynamicImports( const stringArg = objectCall.field('arguments')?.find({ rule: { kind: 'string' } }); if (!stringArg) continue; - const rawSource = getUnquotedText(stringArg); + const rawSource = + stringArg.find({ rule: { kind: 'string_fragment' } })?.text() ?? ''; const internalMod = getInternalModuleName(rawSource); if (!internalMod) continue;