Skip to content
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

Updating setter function's parameter cause invalid output #567

Open
pionxzh opened this issue Sep 9, 2023 · 4 comments
Open

Updating setter function's parameter cause invalid output #567

pionxzh opened this issue Sep 9, 2023 · 4 comments

Comments

@pionxzh
Copy link

pionxzh commented Sep 9, 2023

Adding/removing any parameter in an object's setter function generates wrong output.

Transform

export default function transformer(file, api) {
  const j = api.jscodeshift;

  return j(file.source)
    .find(j.FunctionExpression)
    .forEach(path => {
      path.node.params.push(j.identifier('test'))
    })
    .toSource();
}

Input

const obj = {
    set field (num) {}
};

Expected Output

const obj = {
    set field (num, test) {}
};

Actual Output

const obj = {
    set field function(num, test) {}
};

path.node.params.splice(0) can also trigger the error.

It can be verified on astexplorer.

Hot Fix

You can manually fix it by recreating the Property

if (j.Property.check(path.parentPath.node)) {
    const newProperty = j.property(
        path.parentPath.node.kind,
        path.parentPath.node.key,
        j.functionExpression(
            path.node.id,
            path.node.params,
            path.node.body,
            path.node.generator,
            path.node.expression,
        ),
    )

    path.parentPath.replace(newProperty)
}
@ElonVolo
Copy link
Collaborator

ElonVolo commented Sep 11, 2023 via email

@pionxzh
Copy link
Author

pionxzh commented Sep 11, 2023

@ElonVolo I'm not familiar with how recast handles it, but removing the parameter can also trigger the error.

path.node.params.splice(0)

@ElonVolo
Copy link
Collaborator

ElonVolo commented Sep 11, 2023 via email

@pionxzh
Copy link
Author

pionxzh commented Sep 13, 2023

Let me provide another example that alters the parameter with an assignment pattern.

path.node.params.splice(0, 1, j.assignmentPattern(j.identifier('num'), j.literal(1)))

This also generate wrong output.

const obj = {
    set field function(num = 1) {}
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants