| 1 |
import { declare } from "@babel/helper-plugin-utils"; |
| 2 |
import { types as t } from "@babel/core"; |
| 3 |
import type { NodePath } from "@babel/traverse"; |
| 4 |
|
| 5 |
export default declare(api => { |
| 6 |
api.assertVersion(7); |
| 7 |
|
| 8 |
return { |
| 9 |
name: "transform-new-target", |
| 10 |
|
| 11 |
visitor: { |
| 12 |
MetaProperty(path) { |
| 13 |
const meta = path.get("meta"); |
| 14 |
const property = path.get("property"); |
| 15 |
const { scope } = path; |
| 16 |
|
| 17 |
if ( |
| 18 |
meta.isIdentifier({ name: "new" }) && |
| 19 |
property.isIdentifier({ name: "target" }) |
| 20 |
) { |
| 21 |
const func = path.findParent(path => { |
| 22 |
if (path.isClass()) return true; |
| 23 |
if (path.isFunction() && !path.isArrowFunctionExpression()) { |
| 24 |
if (path.isClassMethod({ kind: "constructor" })) { |
| 25 |
return false; |
| 26 |
} |
| 27 |
|
| 28 |
return true; |
| 29 |
} |
| 30 |
return false; |
| 31 |
}) as NodePath< |
| 32 |
| t.FunctionDeclaration |
| 33 |
| t.FunctionExpression |
| 34 |
| t.Class |
| 35 |
| t.ClassMethod |
| 36 |
| t.ClassPrivateMethod |
| 37 |
>; |
| 38 |
|
| 39 |
if (!func) { |
| 40 |
throw path.buildCodeFrameError( |
| 41 |
"new.target must be under a (non-arrow) function or a class.", |
| 42 |
); |
| 43 |
} |
| 44 |
|
| 45 |
const { node } = func; |
| 46 |
if (t.isMethod(node)) { |
| 47 |
path.replaceWith(scope.buildUndefinedNode()); |
| 48 |
return; |
| 49 |
} |
| 50 |
|
| 51 |
const constructor = t.memberExpression( |
| 52 |
t.thisExpression(), |
| 53 |
t.identifier("constructor"), |
| 54 |
); |
| 55 |
|
| 56 |
if (func.isClass()) { |
| 57 |
path.replaceWith(constructor); |
| 58 |
return; |
| 59 |
} |
| 60 |
|
| 61 |
if (!node.id) { |
| 62 |
node.id = scope.generateUidIdentifier("target"); |
| 63 |
} else { |
| 64 |
// packages/babel-helper-create-class-features-plugin/src/fields.ts#L192 unshadow |
| 65 |
let scope = path.scope; |
| 66 |
const name = node.id.name; |
| 67 |
while (scope !== func.parentPath.scope) { |
| 68 |
if ( |
| 69 |
scope.hasOwnBinding(name) && |
| 70 |
!scope.bindingIdentifierEquals(name, node.id) |
| 71 |
) { |
| 72 |
scope.rename(name); |
| 73 |
} |
| 74 |
scope = scope.parent; |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
path.replaceWith( |
| 79 |
t.conditionalExpression( |
| 80 |
t.binaryExpression( |
| 81 |
"instanceof", |
| 82 |
t.thisExpression(), |
| 83 |
t.cloneNode(node.id), |
| 84 |
), |
| 85 |
constructor, |
| 86 |
scope.buildUndefinedNode(), |
| 87 |
), |
| 88 |
); |
| 89 |
} |
| 90 |
}, |
| 91 |
}, |
| 92 |
}; |
| 93 |
}); |