-
-
Notifications
You must be signed in to change notification settings - Fork 31
feat(timers deprecation): introduce #255
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
d81e531
feat(`timers-deprecations`): scaffould
AugustinMauroy 7409e1b
update
AugustinMauroy b679ff5
Update cleanup-imports.ts
AugustinMauroy a88c1c4
update and add more case
AugustinMauroy b5635b5
fix: support of windows
AugustinMauroy bfc9b18
split utility
AugustinMauroy c3b4d51
Merge branch 'main' into augustin/timers-deprecation
AugustinMauroy 3292eac
doc: use diff
AugustinMauroy d4b29f8
update
AugustinMauroy 6b56cc0
Merge branch 'main' into augustin/timers-deprecation
AugustinMauroy d148c73
Update package-lock.json
AugustinMauroy 7d3e420
Update package-lock.json
AugustinMauroy 71840fb
Merge branch 'main' into augustin/timers-deprecation
AugustinMauroy 9321583
Update
AugustinMauroy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
80
recipes/timers-deprecations/src/active-to-standard-timer.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)` }, | ||
| ], | ||
| }, | ||
| }); | ||
|
|
||
| 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);`; | ||
AugustinMauroy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| handledStatements.add(statement.id()); | ||
| edits.push(statement.replace(replacement)); | ||
| } | ||
| } | ||
|
|
||
| if (!edits.length) return null; | ||
|
|
||
| return rootNode.commitEdits(edits); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
AugustinMauroy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| let source = edits.length ? rootNode.commitEdits(edits) : rootNode.text(); | ||
|
|
||
| if (linesToRemove.length) { | ||
| source = removeLines(source, linesToRemove); | ||
| } | ||
AugustinMauroy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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:
Which isn't better