Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
227 changes: 115 additions & 112 deletions package-lock.json

Large diffs are not rendered by default.

121 changes: 18 additions & 103 deletions recipes/util-is/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
# `util.is**()`

This codemod replaces deprecated `util.is**()` methods with their modern equivalents.

See these deprecations handled by this codemod:
This codemod replaces the following deprecated `util.is**()` methods with their modern equivalents:
- [DEP0044: `util.isArray()`](https://nodejs.org/docs/latest/api/deprecations.html#DEP0044)
- [DEP0045: `util.isBoolean()`](https://nodejs.org/docs/latest/api/deprecations.html#dep0045-utilisboolean)
- [DEP0046: `util.isBuffer()`](https://nodejs.org/docs/latest/api/deprecations.html#dep0046-utilisbuffer)
Expand All @@ -21,103 +19,20 @@ See these deprecations handled by this codemod:

## Examples

**Before:**
```js
import util from 'node:util';

if (util.isArray(someValue)) {
console.log('someValue is an array');
}
if (util.isBoolean(someValue)) {
console.log('someValue is a boolean');
}
if (util.isBuffer(someValue)) {
console.log('someValue is a buffer');
}
if (util.isDate(someValue)) {
console.log('someValue is a date');
}
if (util.isError(someValue)) {
console.log('someValue is an error');
}
if (util.isFunction(someValue)) {
console.log('someValue is a function');
}
if (util.isNull(someValue)) {
console.log('someValue is null');
}
if (util.isNullOrUndefined(someValue)) {
console.log('someValue is null or undefined');
}
if (util.isNumber(someValue)) {
console.log('someValue is a number');
}
if (util.isObject(someValue)) {
console.log('someValue is an object');
}
if (util.isPrimitive(someValue)) {
console.log('someValue is a primitive');
}
if (util.isRegExp(someValue)) {
console.log('someValue is a regular expression');
}
if (util.isString(someValue)) {
console.log('someValue is a string');
}
if (util.isSymbol(someValue)) {
console.log('someValue is a symbol');
}
if (util.isUndefined(someValue)) {
console.log('someValue is undefined');
}
```

**After:**
```js

if (Array.isArray(someValue)) {
console.log('someValue is an array');
}
if (typeof someValue === 'boolean') {
console.log('someValue is a boolean');
}
if (Buffer.isBuffer(someValue)) {
console.log('someValue is a buffer');
}
if (someValue instanceof Date) {
console.log('someValue is a date');
}
if (Error.isError(someValue)) {
console.log('someValue is an error');
}
if (typeof someValue === 'function') {
console.log('someValue is a function');
}
if (someValue === null) {
console.log('someValue is null');
}
if (someValue == null) {
console.log('someValue is null or undefined');
}
if (typeof someValue === 'number') {
console.log('someValue is a number');
}
if (someValue && typeof someValue === 'object') {
console.log('someValue is an object');
}
if (Object(someValue) !== someValue) {
console.log('someValue is a primitive');
}
if (someValue instanceof RegExp) {
console.log('someValue is a regular expression');
}
if (typeof someValue === 'string') {
console.log('someValue is a string');
}
if (typeof someValue === 'symbol') {
console.log('someValue is a symbol');
}
if (typeof someValue === 'undefined') {
console.log('someValue is undefined');
}
```
| **Before** | **After** |
|--------------------------------|---------------------------------|
| `util.isArray(someValue` | `Array.isArray(someValue` |
| `util.isBoolean(someValue` | `typeof someValue === 'boolean'`|
| `util.isBuffer(someValue` | `Buffer.isBuffer(someValue` |
| `util.isDate(someValue` | `someValue instanceof Date` |
| `util.isError(someValue` | `Error.isError(someValue` |
| `util.isFunction(someValue` | `typeof someValue === 'function'`|
| `util.isNull(someValue` | `someValue === null` |
| `util.isNullOrUndefined(someValue` | `someValue == null` |
| `util.isNumber(someValue` | `typeof someValue === 'number'` |
| `util.isObject(someValue` | `someValue && typeof someValue === 'object'` |
| `util.isPrimitive(someValue` | `Object(someValue) !== someValue`|
| `util.isRegExp(someValue` | `someValue instanceof RegExp` |
| `util.isString(someValue` | `typeof someValue === 'string'` |
| `util.isSymbol(someValue` | `typeof someValue === 'symbol'` |
| `util.isUndefined(someValue` | `typeof someValue === 'undefined'` |
2 changes: 1 addition & 1 deletion recipes/util-is/codemod.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
schema_version: "1.0"
name: "@nodejs/util-is"
version: 1.0.0
description: "Replaces deprecated `util.is**()` methods with their modern equivalents."
description: "Replaces deprecated `util.is*()` methods with their modern equivalents."
author: Augustin Mauroy
license: MIT
workflow: workflow.yaml
Expand Down
8 changes: 3 additions & 5 deletions recipes/util-is/package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
{
"name": "@nodejs/util-is",
"version": "1.0.0",
"description": "",
"description": "Replaces deprecated `util.is*()` methods with their modern equivalents.",
"type": "module",
"scripts": {
"test": "npx codemod@next jssg test -l typescript ./src/workflow.ts ./",
"test:update-snapshots": "npx codemod@next jssg test --update-snapshots -l typescript ./src/workflow.ts ./"
"test": "npx codemod@next jssg test -l typescript ./src/workflow.ts ./"
},
"repository": {
"type": "git",
Expand All @@ -17,10 +16,9 @@
"license": "MIT",
"homepage": "https://github.com/nodejs/userland-migrations/blob/main/recipes/util-is/README.md",
"devDependencies": {
"@types/node": "^24.0.3"
"@codemod.com/jssg-types": "^1.0.3"
},
"dependencies": {
"@ast-grep/napi": "^0.39.1",
"@nodejs/codemod-utils": "0.0.0"
}
}
110 changes: 68 additions & 42 deletions recipes/util-is/src/workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,56 @@ import {
import { removeBinding } from "@nodejs/codemod-utils/ast-grep/remove-binding";
import { resolveBindingPath } from "@nodejs/codemod-utils/ast-grep/resolve-binding-path";
import { removeLines } from "@nodejs/codemod-utils/ast-grep/remove-lines";
import type { SgRoot, Edit, Range } from "@ast-grep/napi";
import type { SgRoot, Edit, Range } from "@codemod.com/jssg-types/main";
import type { SgNode } from "@ast-grep/napi";

// Clean up unused imports using removeBinding
const allIsMethods = [
'isArray',
'isBoolean',
'isBuffer',
'isDate',
'isError',
'isFunction',
'isNull',
'isNullOrUndefined',
'isNumber',
'isObject',
'isPrimitive',
'isRegExp',
'isString',
'isSymbol',
'isUndefined'
];

// helper to test named import specifiers (kept at module root so it's not re-created per run)
function hasAnyOtherNamedImports(spec: SgNode): boolean {
const firstIdent = spec.find({ rule: { kind: 'identifier' } });
const name = firstIdent?.text();
return Boolean(name && allIsMethods.includes(name));
}

// Map deprecated util.is*() calls to their modern equivalents
const replacements = new Map<string, (arg: string) => string>([
['isArray', (arg: string) => `Array.isArray(${arg})`],
['isBoolean', (arg: string) => `typeof ${arg} === 'boolean'`],
['isBuffer', (arg: string) => `Buffer.isBuffer(${arg})`],
['isDate', (arg: string) => `${arg} instanceof Date`],
['isError', (arg: string) => `Error.isError(${arg})`],
['isFunction', (arg: string) => `typeof ${arg} === 'function'`],
['isNull', (arg: string) => `${arg} === null`],
['isNullOrUndefined', (arg: string) => `${arg} == null`],
['isNumber', (arg: string) => `typeof ${arg} === 'number'`],
['isObject', (arg: string) => `${arg} && typeof ${arg} === 'object'`],
['isPrimitive', (arg: string) => `Object(${arg}) !== ${arg}`],
['isRegExp', (arg: string) => `${arg} instanceof RegExp`],
['isString', (arg: string) => `typeof ${arg} === 'string'`],
['isSymbol', (arg: string) => `typeof ${arg} === 'symbol'`],
['isUndefined', (arg: string) => `typeof ${arg} === 'undefined'`],
]);

/**
* Transform function that converts deprecated util.is**() calls
* Transform function that converts deprecated util.is*() calls
* to their modern equivalents.
*
* Handles:
Expand All @@ -37,24 +83,6 @@ export default function transform(root: SgRoot): string | null {
const edits: Edit[] = [];
const linesToRemove: Range[] = [];

const replacements = {
isArray: (arg: string) => `Array.isArray(${arg})`,
isBoolean: (arg: string) => `typeof ${arg} === 'boolean'`,
isBuffer: (arg: string) => `Buffer.isBuffer(${arg})`,
isDate: (arg: string) => `${arg} instanceof Date`,
isError: (arg: string) => `Error.isError(${arg})`,
isFunction: (arg: string) => `typeof ${arg} === 'function'`,
isNull: (arg: string) => `${arg} === null`,
isNullOrUndefined: (arg: string) => `${arg} == null`,
isNumber: (arg: string) => `typeof ${arg} === 'number'`,
isObject: (arg: string) => `${arg} && typeof ${arg} === 'object'`,
isPrimitive: (arg: string) => `Object(${arg}) !== ${arg}`,
isRegExp: (arg: string) => `${arg} instanceof RegExp`,
isString: (arg: string) => `typeof ${arg} === 'string'`,
isSymbol: (arg: string) => `typeof ${arg} === 'symbol'`,
isUndefined: (arg: string) => `typeof ${arg} === 'undefined'`
};

const usedMethods = new Set<string>();
const nonIsMethodsUsed = new Set<string>();

Expand All @@ -77,9 +105,15 @@ export default function transform(root: SgRoot): string | null {
}

// default import: import util from 'node:util'
const importClause = node.kind() === 'import_statement' || node.kind() === 'import_clause'
? node.find({ rule: { kind: 'import_clause' } }) ?? node
: null;
const importClause = (
node.kind() === 'import_statement'
|| node.kind() === 'import_clause'
)
&& (
node.find({ rule: { kind: 'import_clause' } })
?? node
);

if (importClause) {
const hasNamed = Boolean(
importClause.find({ rule: { kind: 'named_imports' } })
Expand All @@ -93,7 +127,7 @@ export default function transform(root: SgRoot): string | null {
}

// require namespace: const util = require('node:util')
const reqNs = getRequireNamespaceIdentifier(node);
const reqNs = getRequireNamespaceIdentifier(node);
if (reqNs) namespaceBindings.add(reqNs.text());
}

Expand All @@ -104,25 +138,28 @@ export default function transform(root: SgRoot): string | null {
const methodMatch = usage.getMatch('METHOD');
if (methodMatch) {
const methodName = methodMatch.text();
if (!(methodName in replacements)) nonIsMethodsUsed.add(methodName);
if (!replacements.has(methodName)) nonIsMethodsUsed.add(methodName);
}
}
}

// Resolve local bindings for each util.is* and replace invocations
const localRefsByMethod = new Map<string, Set<string>>();
for (const [method] of Object.entries(replacements)) {
for (const method of replacements.keys()) {
localRefsByMethod.set(method, new Set());
for (const node of importOrRequireNodes) {
const resolved = resolveBindingPath(node, `$.${method}`);
if (resolved) localRefsByMethod.get(method)!.add(resolved);
}
}

for (const [method, replacement] of Object.entries(replacements)) {
for (const [method, replacement] of replacements) {
const refs = localRefsByMethod.get(method)!;
for (const ref of refs) {
const calls = rootNode.findAll({ rule: { pattern: `${ref}($ARG)` } });

if (!calls.length) continue;

for (const call of calls) {
const arg = call.getMatch('ARG');
if (!arg) continue;
Expand All @@ -135,13 +172,6 @@ export default function transform(root: SgRoot): string | null {

if (!edits.length) return null;

// Clean up unused imports using removeBinding
const allIsMethods = [
'isArray', 'isBoolean', 'isBuffer', 'isDate', 'isError', 'isFunction',
'isNull', 'isNullOrUndefined', 'isNumber', 'isObject', 'isPrimitive',
'isRegExp', 'isString', 'isSymbol', 'isUndefined'
];

const importStatements = getNodeImportStatements(root, 'util');
for (const importNode of importStatements) {
const hasNamespace = Boolean(importNode.find({ rule: { kind: 'namespace_import' } }));
Expand All @@ -152,24 +182,20 @@ export default function transform(root: SgRoot): string | null {
// If all named specifiers are util.is* and there is no default or namespace, drop whole line
if (
hasNamed && !defaultIdentifier && !hasNamespace &&
namedImportSpecifiers.every((spec) => {
const firstIdent = spec.find({ rule: { kind: 'identifier' } });
const name = firstIdent?.text();
return name ? allIsMethods.includes(name) : false;
})
namedImportSpecifiers.every(spec => hasAnyOtherNamedImports(spec as SgNode))
) {
linesToRemove.push(importNode.range());
continue;
}

// Otherwise, remove named is* bindings; after replacement they are unused
// Otherwise, remove only named is* bindings; after replacement they are unused
for (const method of allIsMethods) {
const change = removeBinding(importNode, method);
if (change?.edit) edits.push(change.edit);
if (change?.lineToRemove) linesToRemove.push(change.lineToRemove);
}

// If no other util.* methods are used, drop default/namespace imports entirely
// If no other util.is* methods are used, drop default/namespace imports entirely
if (nonIsMethodsUsed.size === 0) {
if ((hasNamespace && !hasNamed) || (defaultIdentifier && !hasNamed)) {
linesToRemove.push(importNode.range());
Expand All @@ -195,7 +221,7 @@ export default function transform(root: SgRoot): string | null {
}
}

// Otherwise, remove named is* bindings; after replacement they are unused
// Otherwise, remove named util.is* bindings; after replacement they are unused
for (const method of allIsMethods) {
const change = removeBinding(requireNode, method);
if (change?.edit) edits.push(change.edit);
Expand Down
2 changes: 1 addition & 1 deletion recipes/util-is/workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ nodes:
runtime:
type: direct
steps:
- name: "Replaces deprecated `util.is**()` methods with their modern equivalents."
- name: "Replaces deprecated `util.is*()` methods with their modern equivalents."
js-ast-grep:
js_file: src/workflow.ts
base_path: .
Expand Down
Loading
Loading