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

fix: cloneNode(deep, withoutLoc) handles absent comments #12602

Merged
merged 1 commit into from
Jan 13, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 11 additions & 3 deletions packages/babel-types/src/clone/cloneNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ export default function cloneNode<T extends t.Node>(
return newNode;
}

function cloneCommentsWithoutLoc<T extends t.Comment>(comments: T[]): T[] {
function cloneCommentsWithoutLoc<T extends t.Comment>(
comments: ReadonlyArray<T>,
): T[] {
return comments.map(
({ type, value }) =>
({
Expand All @@ -113,6 +115,12 @@ function cloneCommentsWithoutLoc<T extends t.Comment>(comments: T[]): T[] {
);
}

function maybeCloneComments(comments, deep, withoutLoc) {
return deep && withoutLoc ? cloneCommentsWithoutLoc(comments) : comments;
function maybeCloneComments<T extends t.Comment>(
comments: ReadonlyArray<T> | null,
deep: boolean,
withoutLoc: boolean,
): ReadonlyArray<T> | null {
return deep && withoutLoc && comments
? cloneCommentsWithoutLoc(comments)
: comments;
}
8 changes: 8 additions & 0 deletions packages/babel-types/test/cloning.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ describe("cloneNode", function () {
expect(t.isNodesEquivalent(node, cloned)).toBe(true);
});

it("should handle deep cloning without loc of fragments", function () {
const program = "foo();";
const node = parse(program);
const cloned = t.cloneNode(node, /* deep */ true, /* withoutLoc */ true);
expect(node).not.toBe(cloned);
expect(t.isNodesEquivalent(node, cloned)).toBe(true);
});

it("should handle missing array element", function () {
const node = parse("[,0]");
const cloned = t.cloneNode(node);
Expand Down