Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
19 changes: 19 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions recipes/timers-deprecations/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Node.js Timers Deprecations

This recipe migrates deprecated internals from `node:timers` to the supported public timers API. It replaces usages of `timers.enroll()`, `timers.unenroll()`, `timers.active()`, and `timers._unrefActive()` with standard constructs built on top of `setTimeout()`, `clearTimeout()`, and `Timer#unref()`.

See the upstream notices: [DEP0095](https://nodejs.org/api/deprecations.html#DEP0095), [DEP0096](https://nodejs.org/api/deprecations.html#DEP0096), [DEP0126](https://nodejs.org/api/deprecations.html#DEP0126), and [DEP0127](https://nodejs.org/api/deprecations.html#DEP0127).

## Example

### Replace `timers.enroll()`

```diff
- const timers = require('node:timers');
- const resource = { _idleTimeout: 1500 };
- timers.enroll(resource, 1500);
+ const resource = { timeout: setTimeout(() => {
+ // timeout handler
+ }, 1500) };
```

### Replace `timers.unenroll()`

```diff
- timers.unenroll(resource);
+ clearTimeout(resource.timeout);
```

### Replace `timers.active()` and `timers._unrefActive()`

```diff
- const timers = require('node:timers');
- timers.active(resource);
- timers._unrefActive(resource);
+ const handle = setTimeout(onTimeout, delay);
+ handle.unref();
```

## Caveats

The legacy APIs exposed internal timer bookkeeping fields such as `_idleStart` or `_idleTimeout`. Those internals have no public equivalent. The codemod focuses on migrating the control flow to modern timers and leaves application specific bookkeeping to the developer. Carefully review the transformed code to ensure that any custom metadata is still updated as expected.
21 changes: 21 additions & 0 deletions recipes/timers-deprecations/codemod.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
schema_version: "1.0"
name: "@nodejs/timers-deprecations"
version: 1.0.0
description: Migrate deprecated node:timers APIs to public timer functions.
author: Augustin Mauroy
license: MIT
workflow: workflow.yaml
category: migration

targets:
languages:
- javascript
- typescript

keywords:
- migration
- timers

registry:
access: public
visibility: public
29 changes: 29 additions & 0 deletions recipes/timers-deprecations/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "@nodejs/timers-deprecations",
"version": "1.0.0",
"description": "Migrate deprecated node:timers APIs to public timer functions.",
"type": "module",
"scripts": {
"test": "node --run test:enroll && node --run test:unenroll && node --run test:active && node --run test:unref && node --run test:imports",
"test:enroll": "npx codemod jssg test -l typescript ./src/enroll-to-set-timeout.ts ./tests/ --filter dep0095",
"test:unenroll": "npx codemod jssg test -l typescript ./src/unenroll-to-clear-timer.ts ./tests/ --filter dep0096",
"test:active": "npx codemod jssg test -l typescript ./src/active-to-standard-timer.ts ./tests/ --filter active",
"test:unref": "npx codemod jssg test -l typescript ./src/unref-active-to-unref.ts ./tests/ --filter unref",
"test:imports": "npx codemod jssg test -l typescript ./src/cleanup-imports.ts ./tests/ --filter imports"
},
"repository": {
"type": "git",
"url": "git+https://github.com/nodejs/userland-migrations.git",
"directory": "recipes/timers-deprecations",
"bugs": "https://github.com/nodejs/userland-migrations/issues"
},
"author": "Augustin Mauroy",
"license": "MIT",
"homepage": "https://github.com/nodejs/userland-migrations/tree/main/recipes/timers-deprecations#readme",
"devDependencies": {
"@codemod.com/jssg-types": "^1.0.9"
},
"dependencies": {
"@nodejs/codemod-utils": "*"
}
}
80 changes: 80 additions & 0 deletions recipes/timers-deprecations/src/active-to-standard-timer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { EOL } from 'node:os';
import { resolveBindingPath } from '@nodejs/codemod-utils/ast-grep/resolve-binding-path';
import {
detectIndentUnit,
getLineIndent,
} from '@nodejs/codemod-utils/ast-grep/indent';
import { getModuleDependencies } from '@nodejs/codemod-utils/ast-grep/module-dependencies';
import type { Edit, SgRoot } from '@codemod.com/jssg-types/main';
import type Js from '@codemod.com/jssg-types/langs/javascript';

const TARGET_METHOD = 'active';

export default function transform(root: SgRoot<Js>): string | null {
const rootNode = root.root();
const sourceCode = rootNode.text();
const indentUnit = detectIndentUnit(sourceCode);
const edits: Edit[] = [];
const handledStatements = new Set<number>();

const importNodes = getModuleDependencies(root, 'timers');

for (const importNode of importNodes) {
if (importNode.is('expression_statement')) continue;
const bindingPath = resolveBindingPath(importNode, `$.${TARGET_METHOD}`);
if (!bindingPath) continue;

const matches = rootNode.findAll({
rule: {
any: [
{ pattern: `${bindingPath}($RESOURCE)` },
{ pattern: `${bindingPath}($RESOURCE, $$$REST)` },
],
},
});

Comment on lines +27 to +35
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about having just one rule that always returns all arguments, and then we just take the first one, since that’s the only one that matters?

Suggested change
const matches = rootNode.findAll({
rule: {
any: [
{ pattern: `${bindingPath}($RESOURCE)` },
{ pattern: `${bindingPath}($RESOURCE, $$$REST)` },
],
},
});
const args = rootNode.findAll({
rule: {
any: [
{ pattern: `${bindingPath}($$$ARGS)` },
],
},
});
firstArg = args[0]

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's will need to write something like that:

const argsNode = match.field('arguments');
			if (!argsNode) continue;
			const argNodes = argsNode
				.children()
				.filter((c) => ![',', '(', ')'].includes(c.kind()));
			const resourceNode = argNodes.length ? argNodes[0] : null;

Which isn't better

for (const match of matches) {
const resourceNode = match.getMatch('RESOURCE');
if (!resourceNode) continue;

const isSafeResourceTarget =
resourceNode.is('identifier') || resourceNode.is('member_expression');
if (!isSafeResourceTarget) continue;

const statement = match.find({
rule: {
inside: {
kind: 'expression_statement',
stopBy: 'end',
},
},
});

if (!statement) continue;

if (handledStatements.has(statement.id())) continue;

const indent = getLineIndent(sourceCode, statement.range().start.index);
const resourceText = resourceNode.text();
const childIndent = indent + indentUnit;
const innerIndent = childIndent + indentUnit;

const replacement =
`if (${resourceText}.timeout != null) {${EOL}` +
`${childIndent}clearTimeout(${resourceText}.timeout);${EOL}` +
`${indent}}${EOL}${EOL}` +
`${indent}${resourceText}.timeout = setTimeout(() => {${EOL}` +
`${childIndent}if (typeof ${resourceText}._onTimeout === "function") {${EOL}` +
`${innerIndent}${resourceText}._onTimeout();${EOL}` +
`${childIndent}}${EOL}` +
`${indent}}, ${resourceText}._idleTimeout);`;

handledStatements.add(statement.id());
edits.push(statement.replace(replacement));
}
}

if (!edits.length) return null;

return rootNode.commitEdits(edits);
}
165 changes: 165 additions & 0 deletions recipes/timers-deprecations/src/cleanup-imports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import { getDefaultImportIdentifier } from '@nodejs/codemod-utils/ast-grep/import-statement';
import { getRequireNamespaceIdentifier } from '@nodejs/codemod-utils/ast-grep/require-call';
import { getModuleDependencies } from '@nodejs/codemod-utils/ast-grep/module-dependencies';
import { removeBinding } from '@nodejs/codemod-utils/ast-grep/remove-binding';
import { removeLines } from '@nodejs/codemod-utils/ast-grep/remove-lines';
import { resolveBindingPath } from '@nodejs/codemod-utils/ast-grep/resolve-binding-path';
import type { Edit, Range, SgNode, SgRoot } from '@codemod.com/jssg-types/main';
import type Js from '@codemod.com/jssg-types/langs/javascript';

const DEPRECATED_METHODS = ['enroll', 'unenroll', 'active', '_unrefActive'];

export default function transform(root: SgRoot<Js>): string | null {
const rootNode = root.root();
const edits: Edit[] = [];
const linesToRemove: Range[] = [];

const importNodes = getModuleDependencies(root, 'timers');

for (const statement of importNodes) {
if (statement.is('expression_statement')) continue;
if (shouldRemoveEntireStatement(statement)) {
linesToRemove.push(statement.range());
continue;
}

let statementMarkedForRemoval = false;
const removedBindings = new Set<string>();

for (const method of DEPRECATED_METHODS) {
const bindingPath = resolveBindingPath(statement, `$.${method}`);
if (!bindingPath) continue;

const localBinding = bindingPath.split('.').at(-1);
if (!localBinding || removedBindings.has(localBinding)) continue;

if (isBindingStillUsed(rootNode, statement, localBinding)) continue;

const removal = removeBinding(statement, localBinding);
if (!removal) continue;

if (removal.edit) edits.push(removal.edit);
if (removal.lineToRemove) {
linesToRemove.push(removal.lineToRemove);
removedBindings.add(localBinding);
statementMarkedForRemoval = true;
break;
}

removedBindings.add(localBinding);
}

if (statementMarkedForRemoval) continue;

const namespaceIdentifier = getNamespaceIdentifier(statement);
if (!namespaceIdentifier) continue;

const nsName = namespaceIdentifier.text();
if (removedBindings.has(nsName)) continue;
if (isBindingStillUsed(rootNode, statement, nsName)) continue;

const removal = removeBinding(statement, nsName);
if (!removal) continue;

if (removal.edit) edits.push(removal.edit);
if (removal.lineToRemove) linesToRemove.push(removal.lineToRemove);
}

if (!edits.length && !linesToRemove.length) {
return null;
}

let source = edits.length ? rootNode.commitEdits(edits) : rootNode.text();

if (linesToRemove.length) {
source = removeLines(source, linesToRemove);
}

return source;
}

function isBindingStillUsed(
rootNode: SgNode<Js>,
statement: SgNode<Js>,
binding: string,
): boolean {
const occurrences = rootNode.findAll({ rule: { pattern: binding } });
for (const occurrence of occurrences) {
if (isInsideNode(occurrence, statement)) continue;
return true;
}
return false;
}

function isInsideNode(node: SgNode<Js>, container: SgNode<Js>): boolean {
for (const ancestor of node.ancestors()) {
if (ancestor.id() === container.id()) return true;
}
return false;
}

function getNamespaceIdentifier(statement: SgNode<Js>): SgNode<Js> | null {
const requireIdent = getRequireNamespaceIdentifier(statement);
if (requireIdent) return requireIdent;

const namespaceImport = statement.find({
rule: {
kind: 'identifier',
inside: { kind: 'namespace_import' },
},
});
if (namespaceImport) return namespaceImport;

const dynamicImportIdentifier = statement.find({
rule: {
kind: 'identifier',
inside: { kind: 'variable_declarator' },
not: { inside: { kind: 'object_pattern' } },
},
});
if (dynamicImportIdentifier) return dynamicImportIdentifier;

return getDefaultImportIdentifier(statement);
}

function shouldRemoveEntireStatement(statement: SgNode<Js>): boolean {
const supportedMethods = statement.findAll({
constraints: {
METHOD: {
regex: `^(${DEPRECATED_METHODS.join('|')})$`,
},
},
rule: {
any: [
{
inside: {
kind: 'object_pattern',
},
kind: 'shorthand_property_identifier_pattern',
pattern: '$METHOD',
},
{
inside: {
kind: 'pair_pattern',
inside: {
kind: 'object_pattern',
},
},
kind: 'property_identifier',
pattern: '$METHOD',
},
{
inside: {
kind: 'import_specifier',
inside: {
kind: 'named_imports',
},
},
kind: 'identifier',
pattern: '$METHOD',
},
],
},
});
return Boolean(supportedMethods.length);
}
Loading
Loading