| 1 |
// Fork of https://github.com/loganfsmyth/babel-plugin-proposal-decorators-legacy |
| 2 |
|
| 3 |
import { template, types as t, type PluginPass } from "@babel/core"; |
| 4 |
import type { NodePath, Visitor } from "@babel/traverse"; |
| 5 |
|
| 6 |
const buildClassDecorator = template.statement(` |
| 7 |
DECORATOR(CLASS_REF = INNER) || CLASS_REF; |
| 8 |
`) as (replacements: { |
| 9 |
DECORATOR: t.Expression; |
| 10 |
CLASS_REF: t.Identifier; |
| 11 |
INNER: t.Expression; |
| 12 |
}) => t.ExpressionStatement; |
| 13 |
|
| 14 |
const buildClassPrototype = template(` |
| 15 |
CLASS_REF.prototype; |
| 16 |
`) as (replacements: { CLASS_REF: t.Identifier }) => t.ExpressionStatement; |
| 17 |
|
| 18 |
const buildGetDescriptor = template(` |
| 19 |
Object.getOwnPropertyDescriptor(TARGET, PROPERTY); |
| 20 |
`) as (replacements: { |
| 21 |
TARGET: t.Expression; |
| 22 |
PROPERTY: t.Literal; |
| 23 |
}) => t.ExpressionStatement; |
| 24 |
|
| 25 |
const buildGetObjectInitializer = template(` |
| 26 |
(TEMP = Object.getOwnPropertyDescriptor(TARGET, PROPERTY), (TEMP = TEMP ? TEMP.value : undefined), { |
| 27 |
enumerable: true, |
| 28 |
configurable: true, |
| 29 |
writable: true, |
| 30 |
initializer: function(){ |
| 31 |
return TEMP; |
| 32 |
} |
| 33 |
}) |
| 34 |
`) as (replacements: { |
| 35 |
TEMP: t.Identifier; |
| 36 |
TARGET: t.Expression; |
| 37 |
PROPERTY: t.Literal; |
| 38 |
}) => t.ExpressionStatement; |
| 39 |
|
| 40 |
const WARNING_CALLS = new WeakSet(); |
| 41 |
|
| 42 |
// legacy decorator does not support ClassAccessorProperty |
| 43 |
type ClassDecoratableElement = |
| 44 |
| t.ClassMethod |
| 45 |
| t.ClassPrivateMethod |
| 46 |
| t.ClassProperty |
| 47 |
| t.ClassPrivateProperty; |
| 48 |
|
| 49 |
/** |
| 50 |
* If the decorator expressions are non-identifiers, hoist them to before the class so we can be sure |
| 51 |
* that they are evaluated in order. |
| 52 |
*/ |
| 53 |
function applyEnsureOrdering( |
| 54 |
path: NodePath<t.ClassExpression | t.ObjectExpression>, |
| 55 |
) { |
| 56 |
// TODO: This should probably also hoist computed properties. |
| 57 |
const decorators: t.Decorator[] = ( |
| 58 |
path.isClass() |
| 59 |
? [ |
| 60 |
path, |
| 61 |
...(path.get("body.body") as NodePath<ClassDecoratableElement>[]), |
| 62 |
] |
| 63 |
: path.get("properties") |
| 64 |
).reduce( |
| 65 |
( |
| 66 |
acc: t.Decorator[], |
| 67 |
prop: NodePath< |
| 68 |
t.ObjectMember | t.ClassExpression | ClassDecoratableElement |
| 69 |
>, |
| 70 |
) => acc.concat(prop.node.decorators || []), |
| 71 |
[], |
| 72 |
); |
| 73 |
|
| 74 |
const identDecorators = decorators.filter( |
| 75 |
decorator => !t.isIdentifier(decorator.expression), |
| 76 |
); |
| 77 |
if (identDecorators.length === 0) return; |
| 78 |
|
| 79 |
return t.sequenceExpression( |
| 80 |
identDecorators |
| 81 |
.map((decorator): t.Expression => { |
| 82 |
const expression = decorator.expression; |
| 83 |
const id = (decorator.expression = |
| 84 |
path.scope.generateDeclaredUidIdentifier("dec")); |
| 85 |
return t.assignmentExpression("=", id, expression); |
| 86 |
}) |
| 87 |
.concat([path.node]), |
| 88 |
); |
| 89 |
} |
| 90 |
|
| 91 |
/** |
| 92 |
* Given a class expression with class-level decorators, create a new expression |
| 93 |
* with the proper decorated behavior. |
| 94 |
*/ |
| 95 |
function applyClassDecorators(classPath: NodePath<t.ClassExpression>) { |
| 96 |
if (!hasClassDecorators(classPath.node)) return; |
| 97 |
|
| 98 |
const decorators = classPath.node.decorators || []; |
| 99 |
classPath.node.decorators = null; |
| 100 |
|
| 101 |
const name = classPath.scope.generateDeclaredUidIdentifier("class"); |
| 102 |
|
| 103 |
return decorators |
| 104 |
.map(dec => dec.expression) |
| 105 |
.reverse() |
| 106 |
.reduce(function (acc, decorator) { |
| 107 |
return buildClassDecorator({ |
| 108 |
CLASS_REF: t.cloneNode(name), |
| 109 |
DECORATOR: t.cloneNode(decorator), |
| 110 |
INNER: acc, |
| 111 |
}).expression; |
| 112 |
}, classPath.node); |
| 113 |
} |
| 114 |
|
| 115 |
function hasClassDecorators(classNode: t.Class) { |
| 116 |
return !!(classNode.decorators && classNode.decorators.length); |
| 117 |
} |
| 118 |
|
| 119 |
/** |
| 120 |
* Given a class expression with method-level decorators, create a new expression |
| 121 |
* with the proper decorated behavior. |
| 122 |
*/ |
| 123 |
function applyMethodDecorators( |
| 124 |
path: NodePath<t.ClassExpression>, |
| 125 |
state: PluginPass, |
| 126 |
) { |
| 127 |
if (!hasMethodDecorators(path.node.body.body)) return; |
| 128 |
|
| 129 |
return applyTargetDecorators( |
| 130 |
path, |
| 131 |
state, |
| 132 |
// @ts-expect-error ClassAccessorProperty is not supported in legacy decorator |
| 133 |
path.node.body.body, |
| 134 |
); |
| 135 |
} |
| 136 |
|
| 137 |
function hasMethodDecorators( |
| 138 |
body: t.ClassBody["body"] | t.ObjectExpression["properties"], |
| 139 |
) { |
| 140 |
return body.some( |
| 141 |
node => |
| 142 |
// @ts-expect-error decorators not in SpreadElement/StaticBlock |
| 143 |
node.decorators?.length, |
| 144 |
); |
| 145 |
} |
| 146 |
|
| 147 |
/** |
| 148 |
* Given an object expression with property decorators, create a new expression |
| 149 |
* with the proper decorated behavior. |
| 150 |
*/ |
| 151 |
function applyObjectDecorators( |
| 152 |
path: NodePath<t.ObjectExpression>, |
| 153 |
state: PluginPass, |
| 154 |
) { |
| 155 |
if (!hasMethodDecorators(path.node.properties)) return; |
| 156 |
|
| 157 |
return applyTargetDecorators( |
| 158 |
path, |
| 159 |
state, |
| 160 |
path.node.properties.filter( |
| 161 |
(prop): prop is t.ObjectMember => prop.type !== "SpreadElement", |
| 162 |
), |
| 163 |
); |
| 164 |
} |
| 165 |
|
| 166 |
/** |
| 167 |
* A helper to pull out property decorators into a sequence expression. |
| 168 |
*/ |
| 169 |
function applyTargetDecorators( |
| 170 |
path: NodePath<t.ClassExpression | t.ObjectExpression>, |
| 171 |
state: PluginPass, |
| 172 |
decoratedProps: (t.ObjectMember | ClassDecoratableElement)[], |
| 173 |
) { |
| 174 |
const name = path.scope.generateDeclaredUidIdentifier( |
| 175 |
path.isClass() ? "class" : "obj", |
| 176 |
); |
| 177 |
|
| 178 |
const exprs = decoratedProps.reduce(function (acc, node) { |
| 179 |
let decorators: t.Decorator[] = []; |
| 180 |
if (node.decorators != null) { |
| 181 |
decorators = node.decorators; |
| 182 |
node.decorators = null; |
| 183 |
} |
| 184 |
|
| 185 |
if (decorators.length === 0) return acc; |
| 186 |
|
| 187 |
if ( |
| 188 |
// @ts-expect-error computed is not in ClassPrivateProperty |
| 189 |
node.computed |
| 190 |
) { |
| 191 |
throw path.buildCodeFrameError( |
| 192 |
"Computed method/property decorators are not yet supported.", |
| 193 |
); |
| 194 |
} |
| 195 |
|
| 196 |
const property: t.Literal = t.isLiteral(node.key) |
| 197 |
? node.key |
| 198 |
: t.stringLiteral( |
| 199 |
// @ts-expect-error: should we handle ClassPrivateProperty? |
| 200 |
node.key.name, |
| 201 |
); |
| 202 |
|
| 203 |
const target = |
| 204 |
path.isClass() && !(node as ClassDecoratableElement).static |
| 205 |
? buildClassPrototype({ |
| 206 |
CLASS_REF: name, |
| 207 |
}).expression |
| 208 |
: name; |
| 209 |
|
| 210 |
if (t.isClassProperty(node, { static: false })) { |
| 211 |
const descriptor = path.scope.generateDeclaredUidIdentifier("descriptor"); |
| 212 |
|
| 213 |
const initializer = node.value |
| 214 |
? t.functionExpression( |
| 215 |
null, |
| 216 |
[], |
| 217 |
t.blockStatement([t.returnStatement(node.value)]), |
| 218 |
) |
| 219 |
: t.nullLiteral(); |
| 220 |
|
| 221 |
node.value = t.callExpression( |
| 222 |
state.addHelper("initializerWarningHelper"), |
| 223 |
[descriptor, t.thisExpression()], |
| 224 |
); |
| 225 |
|
| 226 |
WARNING_CALLS.add(node.value); |
| 227 |
|
| 228 |
acc.push( |
| 229 |
t.assignmentExpression( |
| 230 |
"=", |
| 231 |
t.cloneNode(descriptor), |
| 232 |
t.callExpression(state.addHelper("applyDecoratedDescriptor"), [ |
| 233 |
t.cloneNode(target), |
| 234 |
t.cloneNode(property), |
| 235 |
t.arrayExpression( |
| 236 |
decorators.map(dec => t.cloneNode(dec.expression)), |
| 237 |
), |
| 238 |
t.objectExpression([ |
| 239 |
t.objectProperty( |
| 240 |
t.identifier("configurable"), |
| 241 |
t.booleanLiteral(true), |
| 242 |
), |
| 243 |
t.objectProperty( |
| 244 |
t.identifier("enumerable"), |
| 245 |
t.booleanLiteral(true), |
| 246 |
), |
| 247 |
t.objectProperty( |
| 248 |
t.identifier("writable"), |
| 249 |
t.booleanLiteral(true), |
| 250 |
), |
| 251 |
t.objectProperty(t.identifier("initializer"), initializer), |
| 252 |
]), |
| 253 |
]), |
| 254 |
), |
| 255 |
); |
| 256 |
} else { |
| 257 |
acc.push( |
| 258 |
t.callExpression(state.addHelper("applyDecoratedDescriptor"), [ |
| 259 |
t.cloneNode(target), |
| 260 |
t.cloneNode(property), |
| 261 |
t.arrayExpression(decorators.map(dec => t.cloneNode(dec.expression))), |
| 262 |
t.isObjectProperty(node) || t.isClassProperty(node, { static: true }) |
| 263 |
? buildGetObjectInitializer({ |
| 264 |
TEMP: path.scope.generateDeclaredUidIdentifier("init"), |
| 265 |
TARGET: t.cloneNode(target), |
| 266 |
PROPERTY: t.cloneNode(property), |
| 267 |
}).expression |
| 268 |
: buildGetDescriptor({ |
| 269 |
TARGET: t.cloneNode(target), |
| 270 |
PROPERTY: t.cloneNode(property), |
| 271 |
}).expression, |
| 272 |
t.cloneNode(target), |
| 273 |
]), |
| 274 |
); |
| 275 |
} |
| 276 |
|
| 277 |
return acc; |
| 278 |
}, []); |
| 279 |
|
| 280 |
return t.sequenceExpression([ |
| 281 |
t.assignmentExpression("=", t.cloneNode(name), path.node), |
| 282 |
t.sequenceExpression(exprs), |
| 283 |
t.cloneNode(name), |
| 284 |
]); |
| 285 |
} |
| 286 |
|
| 287 |
function decoratedClassToExpression({ node, scope }: NodePath<t.Class>) { |
| 288 |
if (!hasClassDecorators(node) && !hasMethodDecorators(node.body.body)) { |
| 289 |
return; |
| 290 |
} |
| 291 |
|
| 292 |
const ref = node.id |
| 293 |
? t.cloneNode(node.id) |
| 294 |
: scope.generateUidIdentifier("class"); |
| 295 |
|
| 296 |
return t.variableDeclaration("let", [ |
| 297 |
t.variableDeclarator(ref, t.toExpression(node)), |
| 298 |
]); |
| 299 |
} |
| 300 |
|
| 301 |
const visitor: Visitor<PluginPass> = { |
| 302 |
ExportDefaultDeclaration(path) { |
| 303 |
const decl = path.get("declaration"); |
| 304 |
if (!decl.isClassDeclaration()) return; |
| 305 |
|
| 306 |
const replacement = decoratedClassToExpression(decl); |
| 307 |
if (replacement) { |
| 308 |
const [varDeclPath] = path.replaceWithMultiple([ |
| 309 |
replacement, |
| 310 |
t.exportNamedDeclaration(null, [ |
| 311 |
t.exportSpecifier( |
| 312 |
// @ts-expect-error todo(flow->ts) might be add more specific return type for decoratedClassToExpression |
| 313 |
t.cloneNode(replacement.declarations[0].id), |
| 314 |
t.identifier("default"), |
| 315 |
), |
| 316 |
]), |
| 317 |
]); |
| 318 |
|
| 319 |
if (!decl.node.id) { |
| 320 |
path.scope.registerDeclaration(varDeclPath); |
| 321 |
} |
| 322 |
} |
| 323 |
}, |
| 324 |
ClassDeclaration(path) { |
| 325 |
const replacement = decoratedClassToExpression(path); |
| 326 |
if (replacement) { |
| 327 |
const [newPath] = path.replaceWith(replacement); |
| 328 |
|
| 329 |
const decl = newPath.get("declarations.0"); |
| 330 |
const id = decl.node.id as t.Identifier; |
| 331 |
|
| 332 |
// TODO: Maybe add this logic to @babel/traverse |
| 333 |
const binding = path.scope.getOwnBinding(id.name); |
| 334 |
binding.identifier = id; |
| 335 |
binding.path = decl; |
| 336 |
} |
| 337 |
}, |
| 338 |
ClassExpression(path, state) { |
| 339 |
// Create a replacement for the class node if there is one. We do one pass to replace classes with |
| 340 |
// class decorators, and a second pass to process method decorators. |
| 341 |
const decoratedClass = |
| 342 |
applyEnsureOrdering(path) || |
| 343 |
applyClassDecorators(path) || |
| 344 |
applyMethodDecorators(path, state); |
| 345 |
|
| 346 |
if (decoratedClass) path.replaceWith(decoratedClass); |
| 347 |
}, |
| 348 |
ObjectExpression(path, state) { |
| 349 |
const decoratedObject = |
| 350 |
applyEnsureOrdering(path) || applyObjectDecorators(path, state); |
| 351 |
|
| 352 |
if (decoratedObject) path.replaceWith(decoratedObject); |
| 353 |
}, |
| 354 |
|
| 355 |
AssignmentExpression(path, state) { |
| 356 |
if (!WARNING_CALLS.has(path.node.right)) return; |
| 357 |
|
| 358 |
path.replaceWith( |
| 359 |
t.callExpression(state.addHelper("initializerDefineProperty"), [ |
| 360 |
// @ts-expect-error todo(flow->ts) typesafe NodePath.get |
| 361 |
t.cloneNode(path.get("left.object").node), |
| 362 |
t.stringLiteral( |
| 363 |
// @ts-expect-error todo(flow->ts) typesafe NodePath.get |
| 364 |
path.get("left.property").node.name || |
| 365 |
// @ts-expect-error todo(flow->ts) typesafe NodePath.get |
| 366 |
path.get("left.property").node.value, |
| 367 |
), |
| 368 |
// @ts-expect-error todo(flow->ts) |
| 369 |
t.cloneNode(path.get("right.arguments")[0].node), |
| 370 |
// @ts-expect-error todo(flow->ts) |
| 371 |
t.cloneNode(path.get("right.arguments")[1].node), |
| 372 |
]), |
| 373 |
); |
| 374 |
}, |
| 375 |
|
| 376 |
CallExpression(path, state) { |
| 377 |
if (path.node.arguments.length !== 3) return; |
| 378 |
if (!WARNING_CALLS.has(path.node.arguments[2])) return; |
| 379 |
|
| 380 |
// If the class properties plugin isn't enabled, this line will add an unused helper |
| 381 |
// to the code. It's not ideal, but it's ok since the configuration is not valid anyway. |
| 382 |
// @ts-expect-error todo(flow->ts) check that `callee` is Identifier |
| 383 |
if (path.node.callee.name !== state.addHelper("defineProperty").name) { |
| 384 |
return; |
| 385 |
} |
| 386 |
|
| 387 |
path.replaceWith( |
| 388 |
t.callExpression(state.addHelper("initializerDefineProperty"), [ |
| 389 |
t.cloneNode(path.get("arguments")[0].node), |
| 390 |
t.cloneNode(path.get("arguments")[1].node), |
| 391 |
// @ts-expect-error todo(flow->ts) |
| 392 |
t.cloneNode(path.get("arguments.2.arguments")[0].node), |
| 393 |
// @ts-expect-error todo(flow->ts) |
| 394 |
t.cloneNode(path.get("arguments.2.arguments")[1].node), |
| 395 |
]), |
| 396 |
); |
| 397 |
}, |
| 398 |
}; |
| 399 |
|
| 400 |
export default visitor; |