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: cloned node should be synthesized #167

Merged
merged 1 commit into from
Jun 30, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/clone-node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@ import ts from "typescript";
import { cloneNode } from "./clone-node.js";

describe(cloneNode, () => {
it("should create a synthesized node", () => {
const orig: ts.Node = ts.factory.createIdentifier("hoge");
(orig as any).flags = 0;
const cloned = cloneNode(orig);
expect(cloned.flags & ts.NodeFlags.Synthesized).toBe(ts.NodeFlags.Synthesized);
});

it("should not link to original node", () => {
const orig: ts.Node = ts.factory.createIdentifier("hoge");
const cloned = cloneNode(orig);
expect(ts.getOriginalNode(cloned)).toBe(cloned);
});

it("should copy from node", () => {
const orig: ts.Node = ts.factory.createIdentifier("hoge");
const cloned = cloneNode(orig);
Expand Down
15 changes: 6 additions & 9 deletions src/clone-node.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import ts from "typescript";

type Mutable<T> = { -readonly [K in keyof T]: T[K] };
// Typescript undocumented API, see Ron Buckton's explaination why it's not public:
// https://github.com/microsoft/TypeScript/issues/40507#issuecomment-737628756
// But it's very fit our case
const { cloneNode: _cloneNode } = ts.factory as any;

export function cloneNode<T extends ts.Node>(node: T): T {
const props = { ...node } as Mutable<T>;
props.pos = -1;
props.end = -1;
const base = new (node as any).constructor();
Object.keys(props).forEach(k => {
base[k] = props[k as keyof T];
});
return base as T;
const cloned = _cloneNode(node);
return ts.setOriginalNode(cloned, undefined); // remove original
}