Giter VIP home page Giter VIP logo

codemod-com / codemod Goto Github PK

View Code? Open in Web Editor NEW
307.0 1.0 24.0 72.26 MB

The end-to-end platform for creating, sharing, and running codemods with engines like jscodeshift, ast-grep, ts-morph, and more. Automate code migrations, cleanups, and refactors for you, your team, and the community. AI-powered and CLI-first.

Home Page: https://go.codemod.com/docs

License: Apache License 2.0

JavaScript 3.96% Shell 0.01% TypeScript 90.08% HTML 0.09% CSS 1.90% MDX 3.78% Dockerfile 0.18% Python 0.01%
codemod jscodeshift migration ts-morph upgrade ast-grep cleanup refactoring

codemod's Introduction

Codemod Registry Header


Registry · Community · Docs

Codemod

Codemod platform helps you create, distribute, and run codemods in codebases of any size.

The AI-powered, community-led codemods enable you to automate framework upgrades, large refactoring, and boilerplate programming with unparalleled speed and developer experience.

We are making dream migrations a reality for all developers in the world, one framework at a time.

Documentation

For details on how to use Codemod platform, check out our documentation.

Quickstart

To get started, you can install Codemod CLI:

npm i -g codemod

With Codemod CLI, you can:

1. Build codemods

You can easily build codemods using AI by opening a local project, making changes in a file, and running the following command:

codemod learn

2. Publish codemods

You can publish a compatible local codemod package to Codemod Registry with:

codemod publish

3. Run codemods

codemod [codemod name]

Community

Codemod community can be found on Slack, where you can ask questions, share your feedback, and contribute to the community.

Our Code of Conduct applies to all Codemod community channels.

Contributing

To contribute to Codemod platform, please refer to the contributing guide.

Contributors ✨

Alt

Thanks goes to these wonderful people (emoji key):

Max Leiter
Max Leiter

💻
Greg Pabian
Greg Pabian

💻 🐛 📖
DmytroHryshyn
DmytroHryshyn

💻 🐛
Alex Bit
Alex Bit

💻 📖
Benny Joo
Benny Joo

💻 🐛 📖
Mohab Sameh
Mohab Sameh

💻 📖
Serhii Melnyk
Serhii Melnyk

🤔
kevtran2
kevtran2

📖 💻
George W Langham
George W Langham

🐛
Aniello Falcone
Aniello Falcone

🐛
Sasha
Sasha

💻 🐛
Harsh Gupta
Harsh Gupta

💻
Mohamad Mohebifar
Mohamad Mohebifar

💻 🐛
Mikhail Demidoff
Mikhail Demidoff

💻
Nuurek
Nuurek

💻 🐛
Norayr Baghdasarov
Norayr Baghdasarov

💻 🐛
Grzegorz
Grzegorz

🐛 💻
Aleksy
Aleksy

💻 🐛
Espen Bye
Espen Bye

🐛
Jake Riordan
Jake Riordan

💻 🐛
Jonathan Giardino
Jonathan Giardino

💻 🐛
Mohamed Amine Diboune
Mohamed Amine Diboune

💻
Seif Ghezala
Seif Ghezala

💻
Ahmad Soliman
Ahmad Soliman

💻
Maciej Lotkowski
Maciej Lotkowski

🐛
Jahred Hope
Jahred Hope

💻
arshcodemod
arshcodemod

📖 📢
Jay Kumar
Jay Kumar

💻
Shinya Fujino
Shinya Fujino

📖 💻 🐛
coderaiser
coderaiser

💻
Zach Wolf
Zach Wolf

🐛
with-heart
with-heart

🐛 📖 🤔
Manish Jha
Manish Jha

🐛 💻
Henry Q. Dineen
Henry Q. Dineen

💻 🐛
Matthias
Matthias

🐛
Pardis Pashakhanloo
Pardis Pashakhanloo

💻 📝 🔣

This project follows the all-contributors specification. Contributions of any kind welcome!

codemod's People

Contributors

35c4n0r avatar alexbit-codemod avatar allcontributors[bot] avatar arshcodemod avatar arybitskiy avatar coderaiser avatar dependabot[bot] avatar dmytrohryshyn avatar farskid avatar grzim avatar grzpab avatar harsh24893 avatar hazetheai avatar hbjorbj avatar henryqdineen avatar manishjha-04 avatar mirai2k avatar mohab-sameh avatar mohebifar avatar morinokami avatar ppashakhanloo avatar r4zendev avatar with-heart avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

codemod's Issues

[codemod request] sentry.configureScope : Removal of Sentry.configureScope method

Removal of Sentry.configureScope

In Sentry JavaScript SDK 7.x to 8.x, this codemod removes top level Sentry.configureScope function. Instead, uses the Sentry.getCurrentScope() to access and mutate the current scope.

Examples

Code before transformation

Sentry.configureScope((scope) => {
  scope.setTag("key", "value");
});

Code after transformation

Sentry.getCurrentScope().setTag("key", "value");

Applicability Criteria

Sentry JavaScript SDK 7.x -> 8.x

Additional context or links

Sentry v7 to v8: Removal of Sentry.configureScope method

[codemod][new] Nuxt - migration to v4

Migration details

Official upgrade guide

[codemod][new] Web3.js - migration to v4.x

Migration details

Link to upgrade guide


To contributors working on this task:

  • Framework Expert: For each codemod use case in this migration, provide the Codemod Studio link (example) with detailed specifications. Include before/after pairs, transformation logic in comments, and edge cases. Even if the transformation is tricky, provide instructions on detecting the patterns. This helps estimate the effort needed and guides developers to the areas requiring manual changes.

  • Codemod Creator: Build and publish quality codemods that handle most edge cases. False negatives are acceptable, but there should be no false positives.

  • Questions? -> Community

[codemod request] react-native 0.74 : Batched onLayout updates

##Batched onLayout updates

Codemod description

State updates in onLayout callbacks are now batched. Previously, each state update in the onLayout event would result in a new render commit.In 0.74, setState1 and setState2 updates are batched together. This change is expected behavior in React and allows for less re-renders.

Examples

Code before transformation

function MyComponent(props) {
  const [state1, setState1] = useState(false);
  const [state2, setState2] = useState(false);

  return (
    <View>
      <View
        onLayout={() => {
          setState1(true);
       }}>
      <View
         onLayout={() => {
          // When this event is executed, state1's new value is no longer observable here.
          setState2(true);
        }}>
      </View>
    </View>
  );
}

Code after transformation

import React, { useState } from 'react';
import { View } from 'react-native';

function MyComponent(props) {
  const [state1, setState1] = useState(false);
  const [state2, setState2] = useState(false);

  return (
    <View>
      <View
        onLayout={() => {
          setState1(true);
          setState2(true); // Batched with setState1
        }}>
      </View>
    </View>
  );
}

export default MyComponent;

Applicability Criteria

React Native Upgrade to 0.74

Additional context or links

Migration Guide for the upgrade

react/prop-types-typescript removes prop types regardless of the --preserver-prop-types option

I just copy-pasted the components, but I believe their content is irrelevant. The problem is that the codemod doesn't respect passed options.

Faulty codemod

react-prop-types-typescript doesn't respect the preserver-prop-types (in both VS Code and CLI).

Code before transformation

import { styled } from '@mui/material/styles'
import PropTypes from 'prop-types'

const Root = styled('button', {
  name: 'SegmentedTab',
  shouldForwardProp: (property) => property !== 'isSelected',
  // @ts-expect-error TS(2339): Property 'isSelected' does not exist on type 'MUIS... Remove this comment to see the full error message
})(({ isSelected, theme }) => ({
  '&:hover': {
    // @ts-expect-error TS(2339): Property 'neutral' does not exist on type 'Palette... Remove this comment to see the full error message
    background: theme.palette.neutral[200],
  },
  alignItems: 'center',
  background: 'transparent',
  border: 'none',
  borderRadius: 999,
  color: theme.palette.text.primary,
  cursor: 'pointer',
  display: 'flex',
  flex: 1,
  fontFamily: theme.typography.fontFamily,
  fontSize: 'inherit',
  fontWeight: 'inherit',
  justifyContent: 'center',
  padding: 0,
  textDecoration: 'none',
  ...(isSelected && {
    '&, &:hover': {
      background: 'white',
    },
  }),
}))

export default function SegmentedTab({
  component = 'button',
  isSelected,
  ...other
}: any) {
  const Component = Root.withComponent(component)

  return <Component isSelected={isSelected} {...other} />
}

SegmentedTab.propTypes = {
  /** React component or HTML element name that is used to render tabs. */
  component: PropTypes.elementType,
  /** Marks the tab as a selected. */
  isSelected: PropTypes.bool.isRequired,
}

Expected code after transformation

import { styled } from '@mui/material/styles'

const Root = styled('button', {
  name: 'SegmentedTab',
  shouldForwardProp: (property) => property !== 'isSelected',
  // @ts-expect-error TS(2339): Property 'isSelected' does not exist on type 'MUIS... Remove this comment to see the full error message
})(({ isSelected, theme }) => ({
  '&:hover': {
    // @ts-expect-error TS(2339): Property 'neutral' does not exist on type 'Palette... Remove this comment to see the full error message
    background: theme.palette.neutral[200],
  },
  alignItems: 'center',
  background: 'transparent',
  border: 'none',
  borderRadius: 999,
  color: theme.palette.text.primary,
  cursor: 'pointer',
  display: 'flex',
  flex: 1,
  fontFamily: theme.typography.fontFamily,
  fontSize: 'inherit',
  fontWeight: 'inherit',
  justifyContent: 'center',
  padding: 0,
  textDecoration: 'none',
  ...(isSelected && {
    '&, &:hover': {
      background: 'white',
    },
  }),
}))

interface SegmentedTabProps {
  /** React component or HTML element name that is used to render tabs. */
  component?: React.ElementType;
  /** Marks the tab as a selected. */
  isSelected: boolean;
}

export default function SegmentedTab({
  component = 'button',
  isSelected,
  ...other
}: SegmentedTabProps) {
  const Component = Root.withComponent(component)

  return <Component isSelected={isSelected} {...other} />
}

SegmentedTab.propTypes = {
  /** React component or HTML element name that is used to render tabs. */
  component: PropTypes.elementType,
  /** Marks the tab as a selected. */
  isSelected: PropTypes.bool.isRequired,
}

Actual code after transformation

import { styled } from '@mui/material/styles'

const Root = styled('button', {
  name: 'SegmentedTab',
  shouldForwardProp: (property) => property !== 'isSelected',
  // @ts-expect-error TS(2339): Property 'isSelected' does not exist on type 'MUIS... Remove this comment to see the full error message
})(({ isSelected, theme }) => ({
  '&:hover': {
    // @ts-expect-error TS(2339): Property 'neutral' does not exist on type 'Palette... Remove this comment to see the full error message
    background: theme.palette.neutral[200],
  },
  alignItems: 'center',
  background: 'transparent',
  border: 'none',
  borderRadius: 999,
  color: theme.palette.text.primary,
  cursor: 'pointer',
  display: 'flex',
  flex: 1,
  fontFamily: theme.typography.fontFamily,
  fontSize: 'inherit',
  fontWeight: 'inherit',
  justifyContent: 'center',
  padding: 0,
  textDecoration: 'none',
  ...(isSelected && {
    '&, &:hover': {
      background: 'white',
    },
  }),
}))

interface SegmentedTabProps {
  /** React component or HTML element name that is used to render tabs. */
  component?: React.ElementType;
  /** Marks the tab as a selected. */
  isSelected: boolean;
}

export default function SegmentedTab({
  component = 'button',
  isSelected,
  ...other
}: SegmentedTabProps) {
  const Component = Root.withComponent(component)

  return <Component isSelected={isSelected} {...other} />
}

Estimated severity

It's quite a sever issue to us. We have hundreds of components we want to add types to, preserving prop types. Doing it manually is not an option.

Looks like a trivial issue to fix. The codemod doesn't pick up the preserver-prop-types option, neither from VS Code nor from the console. Feels like a typo to me, but I couldn't find a way to debug it myself.

Environment:

  • Codemod CLI version: v0.10.14
  • OS: macOS 14.4.1
  • Node.js version: v18.19.1

[codemod request] socket.io 4.0 : wsEngine option

socket.io 4.0 : wsEngine option

Codemod description

The format of the wsEngine option was updated in order to get rid of the following error:
Critical dependency: the request of a dependency is an expression

when bundling the server with webpack.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

const io = require("socket.io")(httpServer, {
  wsEngine: "eiows"
});

Code after transformation

const io = require("socket.io")(httpServer, {
  wsEngine: require("eiows").Server
});

Applicability Criteria

Migrate from socket.io 3.0->4.0

Additional context or links[

Migration Guide for the upgrade](https://socket.io/docs/v4/migrating-from-3-x-to-4-0/#wsengine-option)

[codemod][issue] MSW v2 - ctx.json mistakes generic param for body

Faulty codemod

msw/2/response-usages -> codemod source to be updated

Code before transformation

import { Foo } from "somewhere"; // Foo is { x: string, y: number }

const y = 0;
const handler = http.get("/url", (_req, res, ctx) =>
    res(
        ctx.json<Foo>({
            x: "string",
            y,
        }),
    )
);

Expected code after transformation

import { Foo } from "somewhere"; // Foo is { x: string, y: number }

const y = 0;
const handler = http.get("/url", () =>
    HttpResponse.json<Foo>({
        x: "string",
        y,
    }),
);

Actual code after transformation

import { Foo } from "somewhere"; // Foo is { x: string, y: number }

const handler = http.get("/url", () =>
    HttpResponse.json(Foo),
);

Estimated severity

Fairly low - was easy to find because it's a type error. I had one occurrence of this out of ~50 MSW handlers and it wasn't too hard to put the original body back, and put back any references that were wrongly "cleaned up" (const y = 0; in my above example)

Environment:

  • Codemod CLI version: 0.11.17
  • OS: MacOS 14.5
  • Node.js version: v20.14.0

Additional context

Add any other context about the problem here. This might include the target project, explanation of faulty output related to business logic, relevant links, etc.

[codemod request] web3.js : batch.execute()

web3.js : batch.execute()

Codemod description

In 4.x execute returns a promise, where 1.x was based on the callbacks of requests passed to add.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

batch.execute();

Code after transformation

const responses = await batch.execute();

Applicability Criteria

Migrate from web3.js 1.x->4.x

Additional context or links

Migration Guide for the upgrade.

[codemod][new] vuejs - migration from 2 -> 3

Migration details

[Link to upgrade guide]


To contributors working on this task:

  • Framework Expert: For each codemod use case in this migration, provide the Codemod Studio link (example) with detailed specifications. Include before/after pairs, transformation logic in comments, and edge cases. Even if the transformation is tricky, provide instructions on detecting the patterns. This helps estimate the effort needed and guides developers to the areas requiring manual changes.

  • Codemod Creator: Build and publish quality codemods that handle most edge cases. False negatives are acceptable, but there should be no false positives. Even if the transformation is tricky, build a codemod that can detect and add comments to guide developers to the areas needing manual changes.

  • Questions? -> Community

[codemod request] types-react: remove deprecated ReactChildren

on behalf of eps1lon:

"It's very often just misused. Most of the time might be best to typeof React.Children.
Needs real world codebase with usage to test on."

Note: The example section helps codemod contributors identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

//insert your code before transformation here

Code after transformation

//insert the expected **correct** output here

Applicability Criteria

Which types-react versions include the deprecated ReactChildren?

Additional context or links

Add any other context about the problem here. This might include extra considerations, edge cases, relevant business logic, existing migration guides, relevant links, etc.

[codemod request] nuxt 4: replacing template utilities (serialize, importName, importSources) with utilities from 'knitwork'

Replacing template utilities

Codemod description

Nuxt used lodash/template to compile templates located on the file system using the .ejs file format/syntax.
In addition, we provided some template utilities (serialize, importName, importSources) which could be used for code-generation within these templates, which are now being removed.

Also, providing code serialization functions directly within Nuxt is not ideal. Instead, we maintain projects like unjs/knitwork which can be dependencies of your project, and where security issues can be reported/resolved directly without requiring an upgrade of Nuxt itself

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

//insert your code before transformation here

Code after transformation

import { genDynamicImport, genImport, genSafeVariableName } from 'knitwork'

const serialize = (data: any) => JSON.stringify(data, null, 2).replace(/"{(.+)}"(?=,?$)/gm, r => JSON.parse(r).replace(/^{(.*)}$/, '$1'))

const importSources = (sources: string | string[], { lazy = false } = {}) => {
  return toArray(sources).map((src) => {
    if (lazy) {
      return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`
    }
    return genImport(src, genSafeVariableName(src))
  }).join('\n')
}

const importName = genSafeVariableName

Applicability Criteria

Migrating from Nuxt 3 -> Nuxt 4

[codemod request] ether.js v6 : Utilities for property manipulation

Codemod name

Give an understandable name for the codemod.

Codemod description

In version 5 of ethers.js, developers utilized ethers.utils.defineReadOnly() to define a read-only property on an object.

With the evolution to version 6, this functionality has been enhanced and expanded into ethers.defineProperties(). This method now allows developers to define multiple properties on an object with various attributes, including read-only properties. The syntax ethers.defineProperties(obj, { name: value }); signifies the definition of properties, where obj is the target object, name is the property being defined, and value is the value assigned to that property.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

ethers.utils.defineReadOnly(obj, "name", value)

Code after transformation

ethers.defineProperties(obj, { name: value });

Applicability Criteria

Migrating from ether.js v5->v6

Additional context or links

Upgrade guide for Migration

[codemod request] ether.js v6 : utilities for data manipulation

ether.js v6 : utilities for data manipulation

Codemod description

In version 5 of the ethers.js library, the methods ethers.utils.hexDataSlice() and ethers.utils.hexZeroPad() were utilized for slicing and zero-padding hexadecimal data respectively. Additionally, there was a method hexlify() specifically used for converting numbers to hexadecimal strings.

With the release of version 6, these functionalities have been restructured for clarity and consistency. The ethers namespace is now used for both slicing and zero-padding operations, with the methods ethers.dataSlice() and ethers.zeroPadValue() serving the respective purposes. Similarly, for converting numbers to hexadecimal strings, the method toBeHex() has been introduced in version 6.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

// v5
slice = ethers.utils.hexDataSlice(value, start, end)
padded = ethers.utils.hexZeroPad(value, length)

// v5; converting numbers to hexstrings
hex = hexlify(35)

Code after transformation

// v6
slice = ethers.dataSlice(value, start, end)
padded = ethers.zeroPadValue(value, length)

// v6; converting numbers to hexstrings
hex = toBeHex(35)

Applicability Criteria

Migrate for ether.js v5->v6

Additional context or links

Migration guide for the upgarde

[codemod request] svelte 4 : stricter types for createEventDispatcher, Action , ActionReturn , and onMount

svelte 4 : stricter types for createEventDispatcher, Action , ActionReturn , and onMount

Codemod description

createEventDispatcher now supports specifying that a payload is optional, required, or non-existent, and the call sites are checked accordingly (#7224)

Action and ActionReturn have a default parameter type of undefined now, which means you need to type the generic if you want to specify that this action receives a parameter. The migration script will migrate this automatically (#7442)

onMount now shows a type error if you return a function asynchronously from it, because this is likely a bug in your code where you expect the callback to be called on destroy, which it will only do for synchronously returned functions (#8136)

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

const action: Action<HTMLElement, string> = (node, params) => { .. } 
async () => {
     const something = await foo();

Code after transformation

const action: Action<HTMLElement, string> = (node, params) => { .. } 
() => {
foo().then(something =>  ..

Applicability Criteria

Migration for Svelte 3->4

Additional context or links

Migration Guide for Svelte

[codemod request] web3.js 4.x : PromiEvent

web3.js 4.x : PromiEvent

Codemod description

Starting 4.x releases, the package web3-core-promievent will not be maintained and the class are now moved to the web3-core package.The PromiEvent class does not support removeEventListener or addEventListener. Instead we recommend to use on and off.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

import Web3PromiEvent from 'web3-core-promievent';

Code after transformation

import { Web3PromiEvent } from 'web3-core';

Applicability Criteria

Migration of web3.js 1.x->4.x

Additional context or links

Migration Guide for the upgrade

[codemod request] Angular 18 : deprecation of ServerTransferStateModule

Deprecation of ServerTransferStateModule

Codemod description

Remove all imports of ServerTransferStateModule from your application. It is no longer needed.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ServerTransferStateModule } from '@angular/platform-server'; // Importing ServerTransferStateModule

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ServerTransferStateModule // Importing ServerTransferStateModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Code after transformation

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Applicability Criteria

Write the applicable framework/library for this codemod.
Migrate from Angular 17->18

Additional context or links

Migration Guide for Angular 17 -> 18

[codemod request] web3.js 4.x : New Block Headers event

web3.js 4.x : New Block Headers event

Codemod description

n 1.x, web3.eth.subscribe('newBlockHeaders') was used to subscribe to new block headers.

In 4.x, either web3.eth.subscribe('newHeads') or web3.eth.subscribe('newBlockHeaders') can be used to subscribe to new block headers.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

var subscription = web3.eth.subscribe('newBlockHeaders', function (error, result) {
	if (!error) console.log(result);
});
web3.eth.clearSubscriptions(function (error, success) {
	console.log(success); // true
});

Code after transformation

const subscription = await web3.eth.subscribe('newHeads');

newBlocksSubscription.on('data', async blockhead => {
	console.log('New block header: ', blockhead);
});
newBlocksSubscription.on('error', error =>
	console.log('Error when subscribing to New block header: ', error),
);

const ids = await web3.eth.clearSubscriptions();
console.log(ids);

Applicability Criteria

Migrate from web3.js 1.x->4.x

Additional context or links

Migration Guide for Upgrade

[codemod request] web3.js 4.x : require('web3') will now return all web3 exported-objects

web3.js 4.x : require('web3') will now return all web3 exported-objects

Give an understandable name for the codemod.

Codemod description

The web3 package will return all web3.js exported objects
require('web3') will now return all web3 exported-objects organized in namespaces (and few are available on top level).

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

const Web3 = require('web3');

const web3 = new Web3();

Code after transformation

const { Web3 } = require('web3');

const web3 = new Web3();

Applicability Criteria

Upgrading from web3.js 1.x to web3.js 4.x.

Additional context or links

Migration Guide for the upgrade.

[codemod request] ether v6: utilities for hex conversion

ether v6: utilities for hex conversion

Codemod description

In version 5 of ethers.js, developers utilized ethers.utils.hexValue() to convert a value to a hexadecimal representation, and ethers.utils.arrayify() to convert a value to a byte array.

With the transition to version 6, these functionalities have been refined and relocated within the ethers.js library. Now, the method ethers.toQuantity() is employed for converting a value to its hexadecimal representation, aligning with a more intuitive naming convention. Similarly, the operation of converting a value to a byte array is now accomplished through the method ethers.getBytes(), providing a clearer and more descriptive function name.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

hex = ethers.utils.hexValue(value);
array = ethers.utils.arrayify(value);

Code after transformation

hex = ethers.toQuantity(value)
array = ethers.getBytes(value)

Applicability Criteria

Migrate from ether.js v5->v6

Additional context or links

Migration guide for the upgrade.

[codemod][new] svelte - migration to svelte 4

Migration details

[Link to upgrade guide]


To contributors working on this task:

  • Framework Expert: For each codemod use case in this migration, provide the Codemod Studio link (example) with detailed specifications. Include before/after pairs, transformation logic in comments, and edge cases. Even if the transformation is tricky, provide instructions on detecting the patterns. This helps estimate the effort needed and guides developers to the areas requiring manual changes.

  • Codemod Creator: Build and publish quality codemods that handle most edge cases. False negatives are acceptable, but there should be no false positives. Even if the transformation is tricky, build a codemod that can detect and add comments to guide developers to the areas needing manual changes.

  • Questions? -> Community

[codemod request] Nuxt 4: Filemod for new directory structure (low priority)

  • the new Nuxt default srcDir is app/ by default, and most things are resolved from there.
  • serverDir now defaults to <rootDir>/server rather than <srcDir>/server
  • modules and public are resolved relative to <rootDir> by default
  • a new dir.app is added, which is the directory we look for router.options.ts and spa-loading-template.html - this defaults to <srcDir>/

The filemod should do the following changes:

  1. Create a new directory called app/.
  2. Move your assets/, components/, composables/, layouts/, middleware/, pages/, plugins/ and utils/ folders under it, as well as app.vue, error.vue, app.config.ts. If you have an app/router-options.ts or app/spa-loading-template.html, these paths remain the same.
  3. Make sure your nuxt.config.ts, modules/, public/ and server/ folders remain outside the app/ folder, in the root of your project.

Example of new directory structure

.output/
.nuxt/
app/
  assets/
  components/
  composables/
  layouts/
  middleware/
  pages/
  plugins/
  utils/
  app.config.ts
  app.vue
  router.options.ts
modules/
node_modules/
public/
server/
  api/
  middleware/
  plugins/
  routes/
  utils/
nuxt.config.ts

For more details, see the PR implementing this change.

Applicability Criteria

Nuxt 3 to Nuxt 4

Additional context or links

[codemod request] svelte 4 : SvelteComponentTyped is deprecated

svelte 4 : SvelteComponentTyped is deprecated

Codemod description

SvelteComponentTyped
is deprecated, as
SvelteComponent
now has all its typing capabilities. Replace all instances of
SvelteComponentTyped
with
SvelteComponent
.If you have used
SvelteComponent
as the component instance type previously, you may see a somewhat opaque type error now, which is solved by changing : typeof
SvelteComponent
to : typeof
SvelteComponent
.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

 import { SvelteComponentTyped } from 'svelte';

 export class Foo extends SvelteComponentTyped<{ aProp: string }> {}

Code after transformation

 import { SvelteComponent } from 'svelte';
 export class Foo extends SvelteComponent<{ aProp: string }> {}

Applicability Criteria

Migrate from Svelte 3->4

Additional context or links

[Migration Guide for Svelte here]( import { SvelteComponent } from 'svelte';
)

[codemod request]react native 0.74 : set the initialNotification on RCTPushNotificationManager

set the initialNotification on RCTPushNotificationManager

Codemod description

In order to retrieve the notification which launched the app using getInitialNotification(), you’ll now need to explicitly set the initialNotification on RCTPushNotificationManager

Examples

Code before transformation

#import <React/RCTPushNotificationManager.h>
#import <UIKit/UIKit.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
  UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
  if (notification) {
    [RCTPushNotificationManager didReceiveLocalNotification:notification];
  }
  
}

Code after transformation

#import <React/RCTPushNotificationManager.h>
#import <UIKit/UIKit.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
  UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
  if (notification) {
    NSDictionary *response = @{@"notification": notification};
    [RCTPushNotificationManager setInitialNotification:response];
  }
  
}

Applicability Criteria

React Native Upgrade to 0.74

Additional context or links

Migration Guide for React Native 0.74

[codemod request] ether.js v6 : Importing packages

Importing packages

Codemod description

In v5, the project was maintained as a large set of sub-packages managed as a monorepo.

In v6 all imports are available in the root package, and for those who wish to have finer-grained control, the pkg.exports makes certain folders available directly.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

import { ethers } from "ethers"
import { providers } from "ethers"
const { InfuraProvider } = providers

import { InfuraProvider } from "@ethersproject/providers"

Code after transformation

import { ethers } from "ethers"
import { InfuraProvider } from "ethers"
import { InfuraProvider } from "ethers/providers"

Applicability Criteria

Migrate from ether.js v5->v6

Additional context or links

Migration Guide for the upgrade

[codemod request] nuxt 4: useAsyncData and useFetch returns shallowRef rather than a ref.

Shallow Data Reactivity in useAsyncData and useFetch

Codemod description

The data object returned from useAsyncData, useFetch, useLazyAsyncData and useLazyFetch is now a shallowRef rather than a ref.
When new data is fetched, anything depending on data will still be reactive because the entire object is replaced. But if your code changes a property within that data structure, this will not trigger any reactivity in your app.
This brings a significant performance improvement for deeply nested objects and arrays because Vue does not need to watch every single property/array for modification. In most cases, data should also be immutable.

Examples

Code before transformation

const { data } = useFetch('/api/test')

This can apply to all useAsyncData, useFetch, useLazyAsyncData and useLazyFetch

Code after transformation

const { data } = useFetch('/api/test', { deep: true })

Applicability Criteria

Write the applicable framework/library for this codemod.
Migrate from Nuxt 3->Nuxt 4

[codemod][new] elastic javascript client - migration to v8.14

Codemod description

As described in the upgrade guide:
"The returned value of an API call will no longer be the body, statusCode, and headers for callbacks, and only the body for promises. The new returned value will be a unique object containing the body, statusCode, headers, warnings, and meta, for both callback and promises."


To contributors working on this task:

  • Subject Matter/Framework Expert: Share the Codemod Studio link (example) with detailed specs from the framework expert, including before/after pairs and transformation logic, along with edge cases.
  • Codemod Expert: Build and publish quality codemods that cover most edge cases (false negatives are acceptable) with no false positives.
  • Questions? -> Community

[codemod request] Svelte 4: Custom Elements with Svelte

Svelte 4: Custom Elements with Svelte

Codemod description

The creation of custom elements with Svelte has been overhauled and significantly improved. The tag option is deprecated in favor of the new customElement option.This change was made to allow more configurability for advanced use cases. The migration script will adjust your code automatically. The update timing of properties has changed slightly as well.

Code before transformation

<svelte:options tag="my-component" />

Code after transformation

<svelte:options customElement="my-component" />

Applicability Criteria

Migration from Svelte 3-> Svelte 4

Additional context or links

Migration Guide is linked here.

[codemod request] electronjs 30 : Removed: The --disable-color-correct-rendering switch

electronjs 30 : Removed: The --disable-color-correct-rendering switch

Codemod description

This switch was never formally documented but it's removal is being noted here regardless. Chromium itself now has better support for color spaces so this flag should not be needed.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

const { app, BrowserWindow } = require('electron');

app.on('ready', () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // Disable color correction rendering
      disableColorCorrection: true
    }
  });

  mainWindow.loadFile('index.html');
});

Code after transformation

const { app, BrowserWindow } = require('electron');

app.on('ready', () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // Chromium now handles color spaces better, so disabling color correction is unnecessary
    }
  });

  mainWindow.loadFile('index.html');
});

Applicability Criteria

Migration to electron.js 30

Additional context or links

Migration Guide for the upgrade.

[codemod][issue] MSW v2 - issue with arrow function shorthand and delay

Faulty codemod

msw/2/response-usages -> codemod source to be updated

Code before transformation

import { http } from "msw";

const handler = http.post("/url", (_req, res, ctx) => (
    res(ctx.delay(3000), ctx.json({})),
);

Expected code after transformation

import { http, delay, HttpResponse } from "msw";

const handler = http.post("/url", async (_req, res, ctx) => {
    await delay(3000);
    return HttpResponse.json({});
});

Actual code after transformation

Fails to transform.

Though if I wrap my arrow function shorthand into a body with a return statement, I get this output instead:

import { http, delay, HttpResponse } from "msw";

const handler = http.post("/url", (_req, res, ctx) => {
    return HttpResponse.json({});
});

(which is almost correct, but missing the delay(3000) statement and the async function marker.

Estimated severity

Medium? It seems like it's a fairly small tweak: if the callback has an expression body, replace it with a block body before continuing, but I couldn't find a good way to do that without breaking all the existing 'handles'. Maybe it would need to happen as a separate pass before the rest of the codemod - either targetted (look for the usage of 'delay'), or just a general pass that gets rid of the shorthand syntax for msw callbacks.

Environment:

  • Codemod CLI version: 0.11.17
  • OS: MacOS 14.5
  • Node.js version: v20.14.0

Additional context

Add any other context about the problem here. This might include the target project, explanation of faulty output related to business logic, relevant links, etc.

Cannot sign in using Cursor

The issue arises when attempting to authenticate the Codemod extension in Cursor. After successful authentication on the web, the website attempts to redirect using the vscode:// URL scheme. However, the Cursor application does not recognize this URL scheme. A workaround has been found where manually changing the URL scheme to cursor:// allows the redirect to work as expected.

Steps to Replicate

  1. Open the Cursor application.
  2. Install the Codemod extension within the Cursor application.
  3. Click on the 'Sign In' button within the Codemod extension.
  4. Authenticate with the required credentials on the web.
  5. After successful authentication, the website attempts to redirect using the vscode:// URL scheme.

At this point, the Cursor application fails to recognize the vscode:// URL scheme and thus Codemod cannot sign in.

[codemod request] Angular 18 : includeRequestsWithAuthHeaders: true in withHttpTransferCache

includeRequestsWithAuthHeaders: true in withHttpTransferCache

Codemod description

Use includeRequestsWithAuthHeaders: true in withHttpTransferCache to opt-out of caching for HTTP requests that require authorization.

Examples

Code before transformation

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Code after transformation

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { withHttpTransferCache } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useValue: withHttpTransferCache({ includeRequestsWithAuthHeaders: true }),
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Applicability Criteria

Angular Upgrade 17->18

Additional context or links

Migration Guide for Angular 18

[codemod request] ether.js v6 : Transactions in ether.js

ether.js v6 : Transactions in ether.js

Give an understandable name for the codemod.

Codemod description

The transaction helpers present in v5 were all wrapped into a Transaction class, which can handle any supported transaction format to be further processed

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

tx = parseTransaction(txBytes)
txBytes = serializeTransaction(tx)
txBytes = serializeTransaction(tx, sig)

Code after transformation

tx = Transaction.from(txBytes)
txBytes = Transaction.from(tx).serialized```

### Applicability Criteria

Migrate from ether.js v5->v6

### Additional context or links
[Migration Guide for the upgrade is here](https://docs.ethers.org/v6/migrating/#migrate-transactions)

ESLint & Prettier to Biome.js Migration

This is to migrate our monorepo's linting and formatting from ESLint & Prettier to Biome.js.

Why:

  1. Two in One: Biome comes with 190 lint rules from ESlint, TypeScript ESlint, and other sources with 97% compatibility with Prettier. Biome can be used as a replacement for two.
  2. Biome adds new CLI options that enables to format and lint only files that changed (using Git)
  3. its rust-based and 10x+ faster than eslint!!!

Biome Impact:

based on local run of biome on our monorepo, it runs the checks 10x faster (from 15.6 seconds down to just 1.6 seconds)

migration plan:

  1. Run eslint/biome/migrate-rules codemod and make minor tweaks. (156 files changed
  2. run biome to apply the required formatting (609 files changed)
  3. fixed the linting issues manually for each part of the platform (cli, vsce, studio, etc.)
  4. by now all lintings should work fine, so we enable the linting check for github action.

Codemod Impact:

If we were to manually migrate the Codemod Monorepo alone, we would have to:

  • adjust 134 existing package.json files:
    • replace ESLint scripts (1 minute per file);
    • replace ESLint deps (1 minute per file);
  • find a corresponding rule for each of the existing ESLint rules (2 minutes per rule);
  • replace Prettier configuration (5 minutes)

It would have taken up to a whole day of boring mechanical work to perform the migration manually without performing any additional troubleshooting

[codemod request] ethers v6 : contracts in ether.js

contracts in ether.js

Codemod description

In v5, in the case of an ambiguous method, it was necessary to look up a method by its canonical normalized signature. In v6 the signature does not need to be normalized and the Typed API provides a cleaner way to access the desired method.

In v5, duplicate definitions also injected warnings into the console, since there was no way to detect them at run-time.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

abi = [
  "function foo(address bar)",
  "function foo(uint160 bar)",
]
contract = new Contract(address, abi, provider)

contract["foo(address)"](addr)

contract["foo(address )"](addr)
contract["foo(address addr)"](addr)

contract.foo(addr)

Code after transformation

abi = [
  "function foo(address bar)",
  "function foo(uint160 bar)",
]
contract = new Contract(address, abi, provider)

contract["foo(address)"](addr)
contract["foo(address )"](addr)
contract["foo(address addr)"](addr)

contract.foo(addr)

contract.foo(Typed.address(addr))

Applicability Criteria

Migrate from ethers v5->v6

Additional context or links

Migration Guide for the upgrade.

[codemod request] ether.js v6 : Signature class facilitating the parsing and serializing.

ether.js v6 : Signature class facilitating the parsing and serializing.

Codemod description

The Signature is now a class which facilitates all the parsing and serializing.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

splitSig = splitSignature(sigBytes)
sigBytes = joinSignature(splitSig)

Code after transformation

splitSig = ethers.Signature.from(sigBytes)
sigBytes = ethers.Signature.from(splitSig).serialized

Applicability Criteria

Migrate from ether.js v5->v6

Additional context or links

Migration Guide for the upgrade

[codemod request] render-fucntion: Migrate Render Function API

Migrate Render Function API

In Vue 3.x, h is now globally imported instead of being automatically passed as an argument. This codemod migrates the render function API to be compatible with Vue 3.x.

Examples

Code before transformation

export default {
  render(h) {
    return h('div')
  }
}

Code after transformation

import { h } from 'vue'

export default {
  render() {
    return h('div')
  }
}

Applicability Criteria

Write the applicable framework/library for this codemod.
Vue 2.x -> 3.x

Additional context or links

[codemod request] Nuxt 4: shared prerender data

This codemod should ensure that any unique key of your data is always resolvable to the same data. For example, if you are using useAsyncData to fetch data related to a particular page, it should be changed to a key that uniquely matches that data. (useFetch should do this automatically for you.)

Examples

Code before transformation

const route = useRoute()
const { data } = await useAsyncData(async () => {
  return await $fetch(`/api/my-page/${route.params.slug}`)
})

Code after transformation

const route = useRoute()
const { data } = await useAsyncData(route.params.slug, async () => {
  return await $fetch(`/api/my-page/${route.params.slug}`)
})

Applicability Criteria

Nuxt 3 to Nuxt 4

Additional context or links

[codemod request] types-react: remove deprecated ReactHTML and ReactSVG

on behalf of eps1lon:

" ReactHMTL and ReactSVG were related to createFactories but we found usage using it as a list of possible built-in browser element types.

We now have HTMLElementType and SVGElementType which can be used instead of keyof ReactHTML and keyof ReactSVG respectively.

Needs real world codebase with usage to test on."

Note: The example section helps codemod contributors identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

//insert your code before transformation here

Code after transformation

//insert the expected **correct** output here

Applicability Criteria

Which types-react versions include the deprecated pattern?

Additional context or links

Add any other context about the problem here. This might include extra considerations, edge cases, relevant business logic, existing migration guides, relevant links, etc.

[codemod request] example codemod

⚠️⚠️ Please do not include any proprietary code in the issue. ⚠️⚠️


Codemod name

Give an understandable name for the codemod.

Codemod description

Write a short description of the changes that should be made by this codemod.

Examples

Note: The example section helps codemod champions identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

//insert your code before transformation here

Code after transformation

//insert the expected **correct** output here

Applicability Criteria

Write the applicable framework/library for this codemod.
A codemod can:

  • Migrate from one version to another [ex: React 18 -> React 19]
  • Migrate from one framework to another [ex: ESLint -> Biome]
  • Clean up or refactor code of the same framework/library version [ex: React 18 -> React 18]

Additional context or links

Add any other context about the problem here. This might include extra considerations, edge cases, relevant business logic, existing migration guides, relevant links, etc.

[codemod][new] ether.js - migration to v6

Migration details

[Link to upgrade guide]


To contributors working on this task:

  • Framework Expert: For each codemod use case in this migration, provide the Codemod Studio link (example) with detailed specifications. Include before/after pairs, transformation logic in comments, and edge cases. Even if the transformation is tricky, provide instructions on detecting the patterns. This helps estimate the effort needed and guides developers to the areas requiring manual changes.

  • Codemod Creator: Build and publish quality codemods that handle most edge cases. False negatives are acceptable, but there should be no false positives. Even if the transformation is tricky, build a codemod that can detect and add comments to guide developers to the areas needing manual changes.

  • Questions? -> Community

[codemod][new] types-react: remove deprecated types related to mixins

on behalf of eps1lon:

"ComponentSpec and Mixin are now in create-react-class. It might be easiest to fork the deprecated-prop-types-types but with create-react-class instead of prop-types as the target package.

Needs real world codebase with usage to test on."

Note: The example section helps codemod contributors identify all the transformation patterns that this codemod should handle. Repeat before/after snippets for every transformation example you can find.

Code before transformation

//insert your code before transformation here

Code after transformation

//insert the expected **correct** output here

Applicability Criteria

Which types-react versions include the deprecated pattern?

Additional context or links

Add any other context about the problem here. This might include extra considerations, edge cases, relevant business logic, existing migration guides, relevant links, etc.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.