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

ts-morph incorrectly transforms nodes which begin with whitespace #1591

Open
ofersadgat opened this issue Dec 10, 2024 · 0 comments · May be fixed by #1592
Open

ts-morph incorrectly transforms nodes which begin with whitespace #1591

ofersadgat opened this issue Dec 10, 2024 · 0 comments · May be fixed by #1592

Comments

@ofersadgat
Copy link

ofersadgat commented Dec 10, 2024

if you have a node such as:

<Text><Text>Foo</Text> is great</Text>

and you do a transform:

node.transform((traversal) => {
    if (ts.isJsxText(traversal.currentNode) && traversal.currentNode.text != 'Foo'){
        return traversal.factory.createJsxText(' is NOT great', false);
    } else {
        return traversal.visitChildren();
    }
});

the result should be:

<Text><Text>Foo</Text> is NOT great</Text>

but it is:

<Text><Text>Foo</Text>  is NOT great</Text>

instead. Notice how an extra space was added. This is due to the following error in the code:

        function handleTransformation(oldNode, newNode) {
            if (oldNode === newNode && newNode.emitNode == null)
                return;
            const start = oldNode.getStart(compilerSourceFile, true); //This is the error: start should be oldNode.pos which correctly accounts for whitespace
            const end = oldNode.end;
            let lastTransformation;
            while ((lastTransformation = transformations[transformations.length - 1]) && lastTransformation.start > start)
                transformations.pop();
            const wrappedNode = compilerFactory.getExistingNodeFromCompilerNode(oldNode);
            transformations.push({
                start,
                end,
                compilerNode: newNode,
            });
            if (wrappedNode != null) {
                if (oldNode.kind !== newNode.kind)
                    wrappedNode.forget();
                else
                    wrappedNode.forgetDescendants();
            }
        }

As I noted in the comment, it is using an incorrect way of getting the start of the node and should be using .pos.

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

Successfully merging a pull request may close this issue.

1 participant