| 1 | import assert from "assert"; |
| 2 | import { numericLiteral, sequenceExpression } from "@babel/types"; |
| 3 | import type * as t from "@babel/types"; |
| 4 | import type { NodePath, Scope } from "@babel/traverse"; |
| 5 | import type { File } from "@babel/core"; |
| 6 | |
| 7 | import ImportBuilder from "./import-builder"; |
| 8 | import isModule from "./is-module"; |
| 9 | |
| 10 | export type ImportOptions = { |
| 11 | /** |
| 12 | * The module being referenced. |
| 13 | */ |
| 14 | importedSource: string | null; |
| 15 | /** |
| 16 | * The type of module being imported: |
| 17 | * |
| 18 | * * 'es6' - An ES6 module. |
| 19 | * * 'commonjs' - A CommonJS module. (Default) |
| 20 | */ |
| 21 | importedType: "es6" | "commonjs"; |
| 22 | /** |
| 23 | * The type of interop behavior for namespace/default/named when loading |
| 24 | * CommonJS modules. |
| 25 | * |
| 26 | * ## 'babel' (Default) |
| 27 | * |
| 28 | * Load using Babel's interop. |
| 29 | * |
| 30 | * If '.__esModule' is true, treat as 'compiled', else: |
| 31 | * |
| 32 | * * Namespace: A copy of the module.exports with .default |
| 33 | * populated by the module.exports object. |
| 34 | * * Default: The module.exports value. |
| 35 | * * Named: The .named property of module.exports. |
| 36 | * |
| 37 | * The 'ensureLiveReference' has no effect on the liveness of these. |
| 38 | * |
| 39 | * ## 'compiled' |
| 40 | * |
| 41 | * Assume the module is ES6 compiled to CommonJS. Useful to avoid injecting |
| 42 | * interop logic if you are confident that the module is a certain format. |
| 43 | * |
| 44 | * * Namespace: The root module.exports object. |
| 45 | * * Default: The .default property of the namespace. |
| 46 | * * Named: The .named property of the namespace. |
| 47 | * |
| 48 | * Will return erroneous results if the imported module is _not_ compiled |
| 49 | * from ES6 with Babel. |
| 50 | * |
| 51 | * ## 'uncompiled' |
| 52 | * |
| 53 | * Assume the module is _not_ ES6 compiled to CommonJS. Used a simplified |
| 54 | * access pattern that doesn't require additional function calls. |
| 55 | * |
| 56 | * Will return erroneous results if the imported module _is_ compiled |
| 57 | * from ES6 with Babel. |
| 58 | * |
| 59 | * * Namespace: The module.exports object. |
| 60 | * * Default: The module.exports object. |
| 61 | * * Named: The .named property of module.exports. |
| 62 | */ |
| 63 | importedInterop: "babel" | "node" | "compiled" | "uncompiled"; |
| 64 | /** |
| 65 | * The type of CommonJS interop included in the environment that will be |
| 66 | * loading the output code. |
| 67 | * |
| 68 | * * 'babel' - CommonJS modules load with Babel's interop. (Default) |
| 69 | * * 'node' - CommonJS modules load with Node's interop. |
| 70 | * |
| 71 | * See descriptions in 'importedInterop' for more details. |
| 72 | */ |
| 73 | importingInterop: "babel" | "node"; |
| 74 | /** |
| 75 | * Define whether we explicitly care that the import be a live reference. |
| 76 | * Only applies when importing default and named imports, not the namespace. |
| 77 | * |
| 78 | * * true - Force imported values to be live references. |
| 79 | * * false - No particular requirements. Keeps the code simplest. (Default) |
| 80 | */ |
| 81 | ensureLiveReference: boolean; |
| 82 | /** |
| 83 | * Define if we explicitly care that the result not be a property reference. |
| 84 | * |
| 85 | * * true - Force calls to exclude context. Useful if the value is going to |
| 86 | * be used as function callee. |
| 87 | * * false - No particular requirements for context of the access. (Default) |
| 88 | */ |
| 89 | ensureNoContext: boolean; |
| 90 | /** |
| 91 | * Define whether the import should be loaded before or after the existing imports. |
| 92 | * "after" is only allowed inside ECMAScript modules, since it's not possible to |
| 93 | * reliably pick the location _after_ require() calls but _before_ other code in CJS. |
| 94 | */ |
| 95 | importPosition: "before" | "after"; |
| 96 | |
| 97 | nameHint?: string; |
| 98 | blockHoist?: number; |
| 99 | }; |
| 100 | |
| 101 | /** |
| 102 | * A general helper classes add imports via transforms. See README for usage. |
| 103 | */ |
| 104 | export default class ImportInjector { |
| 105 | /** |
| 106 | * The path used for manipulation. |
| 107 | */ |
| 108 | declare _programPath: NodePath<t.Program>; |
| 109 | |
| 110 | /** |
| 111 | * The scope used to generate unique variable names. |
| 112 | */ |
| 113 | declare _programScope: Scope; |
| 114 | |
| 115 | /** |
| 116 | * The file used to inject helpers and resolve paths. |
| 117 | */ |
| 118 | declare _hub: File["hub"]; |
| 119 | |
| 120 | /** |
| 121 | * The default options to use with this instance when imports are added. |
| 122 | */ |
| 123 | _defaultOpts: ImportOptions = { |
| 124 | importedSource: null, |
| 125 | importedType: "commonjs", |
| 126 | importedInterop: "babel", |
| 127 | importingInterop: "babel", |
| 128 | ensureLiveReference: false, |
| 129 | ensureNoContext: false, |
| 130 | importPosition: "before", |
| 131 | }; |
| 132 | |
| 133 | constructor( |
| 134 | path: NodePath, |
| 135 | importedSource?: string, |
| 136 | opts?: Partial<ImportOptions>, |
| 137 | ) { |
| 138 | const programPath = path.find(p => p.isProgram()) as NodePath<t.Program>; |
| 139 | |
| 140 | this._programPath = programPath; |
| 141 | this._programScope = programPath.scope; |
| 142 | this._hub = programPath.hub as File["hub"]; |
| 143 | |
| 144 | this._defaultOpts = this._applyDefaults(importedSource, opts, true); |
| 145 | } |
| 146 | |
| 147 | addDefault(importedSourceIn: string, opts: Partial<ImportOptions>) { |
| 148 | return this.addNamed("default", importedSourceIn, opts); |
| 149 | } |
| 150 | |
| 151 | addNamed( |
| 152 | importName: string, |
| 153 | importedSourceIn: string, |
| 154 | opts: Partial<ImportOptions>, |
| 155 | ) { |
| 156 | assert(typeof importName === "string"); |
| 157 | |
| 158 | return this._generateImport( |
| 159 | this._applyDefaults(importedSourceIn, opts), |
| 160 | importName, |
| 161 | ); |
| 162 | } |
| 163 | |
| 164 | addNamespace(importedSourceIn: string, opts: Partial<ImportOptions>) { |
| 165 | return this._generateImport( |
| 166 | this._applyDefaults(importedSourceIn, opts), |
| 167 | null, |
| 168 | ); |
| 169 | } |
| 170 | |
| 171 | addSideEffect(importedSourceIn: string, opts: Partial<ImportOptions>) { |
| 172 | return this._generateImport( |
| 173 | this._applyDefaults(importedSourceIn, opts), |
| 174 | void 0, |
| 175 | ); |
| 176 | } |
| 177 | |
| 178 | _applyDefaults( |
| 179 | importedSource: string | Partial<ImportOptions>, |
| 180 | opts: Partial<ImportOptions> | undefined, |
| 181 | isInit = false, |
| 182 | ) { |
| 183 | let newOpts: ImportOptions; |
| 184 | if (typeof importedSource === "string") { |
| 185 | newOpts = { ...this._defaultOpts, importedSource, ...opts }; |
| 186 | } else { |
| 187 | assert(!opts, "Unexpected secondary arguments."); |
| 188 | newOpts = { ...this._defaultOpts, ...importedSource }; |
| 189 | } |
| 190 | |
| 191 | if (!isInit && opts) { |
| 192 | if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint; |
| 193 | if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist; |
| 194 | } |
| 195 | return newOpts; |
| 196 | } |
| 197 | |
| 198 | _generateImport( |
| 199 | opts: Partial<ImportOptions>, |
| 200 | importName: string | null | undefined, |
| 201 | ) { |
| 202 | const isDefault = importName === "default"; |
| 203 | const isNamed = !!importName && !isDefault; |
| 204 | const isNamespace = importName === null; |
| 205 | |
| 206 | const { |
| 207 | importedSource, |
| 208 | importedType, |
| 209 | importedInterop, |
| 210 | importingInterop, |
| 211 | ensureLiveReference, |
| 212 | ensureNoContext, |
| 213 | nameHint, |
| 214 | importPosition, |
| 215 | |
| 216 | // Not meant for public usage. Allows code that absolutely must control |
| 217 | // ordering to set a specific hoist value on the import nodes. |
| 218 | // This is ignored when "importPosition" is "after". |
| 219 | blockHoist, |
| 220 | } = opts; |
| 221 | |
| 222 | // Provide a hint for generateUidIdentifier for the local variable name |
| 223 | // to use for the import, if the code will generate a simple assignment |
| 224 | // to a variable. |
| 225 | let name = nameHint || importName; |
| 226 | |
| 227 | const isMod = isModule(this._programPath); |
| 228 | const isModuleForNode = isMod && importingInterop === "node"; |
| 229 | const isModuleForBabel = isMod && importingInterop === "babel"; |
| 230 | |
| 231 | if (importPosition === "after" && !isMod) { |
| 232 | throw new Error(`"importPosition": "after" is only supported in modules`); |
| 233 | } |
| 234 | |
| 235 | const builder = new ImportBuilder( |
| 236 | importedSource, |
| 237 | this._programScope, |
| 238 | this._hub, |
| 239 | ); |
| 240 | |
| 241 | if (importedType === "es6") { |
| 242 | if (!isModuleForNode && !isModuleForBabel) { |
| 243 | throw new Error("Cannot import an ES6 module from CommonJS"); |
| 244 | } |
| 245 | |
| 246 | // import * as namespace from ''; namespace |
| 247 | // import def from ''; def |
| 248 | // import { named } from ''; named |
| 249 | builder.import(); |
| 250 | if (isNamespace) { |
| 251 | builder.namespace(nameHint || importedSource); |
| 252 | } else if (isDefault || isNamed) { |
| 253 | builder.named(name, importName); |
| 254 | } |
| 255 | } else if (importedType !== "commonjs") { |
| 256 | throw new Error(`Unexpected interopType "${importedType}"`); |
| 257 | } else if (importedInterop === "babel") { |
| 258 | if (isModuleForNode) { |
| 259 | // import _tmp from ''; var namespace = interopRequireWildcard(_tmp); namespace |
| 260 | // import _tmp from ''; var def = interopRequireDefault(_tmp).default; def |
| 261 | // import _tmp from ''; _tmp.named |
| 262 | name = name !== "default" ? name : importedSource; |
| 263 | const es6Default = `${importedSource}$es6Default`; |
| 264 | |
| 265 | builder.import(); |
| 266 | if (isNamespace) { |
| 267 | builder |
| 268 | .default(es6Default) |
| 269 | .var(name || importedSource) |
| 270 | .wildcardInterop(); |
| 271 | } else if (isDefault) { |
| 272 | if (ensureLiveReference) { |
| 273 | builder |
| 274 | .default(es6Default) |
| 275 | .var(name || importedSource) |
| 276 | .defaultInterop() |
| 277 | .read("default"); |
| 278 | } else { |
| 279 | builder |
| 280 | .default(es6Default) |
| 281 | .var(name) |
| 282 | .defaultInterop() |
| 283 | .prop(importName); |
| 284 | } |
| 285 | } else if (isNamed) { |
| 286 | builder.default(es6Default).read(importName); |
| 287 | } |
| 288 | } else if (isModuleForBabel) { |
| 289 | // import * as namespace from ''; namespace |
| 290 | // import def from ''; def |
| 291 | // import { named } from ''; named |
| 292 | builder.import(); |
| 293 | if (isNamespace) { |
| 294 | builder.namespace(name || importedSource); |
| 295 | } else if (isDefault || isNamed) { |
| 296 | builder.named(name, importName); |
| 297 | } |
| 298 | } else { |
| 299 | // var namespace = interopRequireWildcard(require('')); |
| 300 | // var def = interopRequireDefault(require('')).default; def |
| 301 | // var named = require('').named; named |
| 302 | builder.require(); |
| 303 | if (isNamespace) { |
| 304 | builder.var(name || importedSource).wildcardInterop(); |
| 305 | } else if ((isDefault || isNamed) && ensureLiveReference) { |
| 306 | if (isDefault) { |
| 307 | name = name !== "default" ? name : importedSource; |
| 308 | builder.var(name).read(importName); |
| 309 | builder.defaultInterop(); |
| 310 | } else { |
| 311 | builder.var(importedSource).read(importName); |
| 312 | } |
| 313 | } else if (isDefault) { |
| 314 | builder.var(name).defaultInterop().prop(importName); |
| 315 | } else if (isNamed) { |
| 316 | builder.var(name).prop(importName); |
| 317 | } |
| 318 | } |
| 319 | } else if (importedInterop === "compiled") { |
| 320 | if (isModuleForNode) { |
| 321 | // import namespace from ''; namespace |
| 322 | // import namespace from ''; namespace.default |
| 323 | // import namespace from ''; namespace.named |
| 324 | |
| 325 | builder.import(); |
| 326 | if (isNamespace) { |
| 327 | builder.default(name || importedSource); |
| 328 | } else if (isDefault || isNamed) { |
| 329 | builder.default(importedSource).read(name); |
| 330 | } |
| 331 | } else if (isModuleForBabel) { |
| 332 | // import * as namespace from ''; namespace |
| 333 | // import def from ''; def |
| 334 | // import { named } from ''; named |
| 335 | // Note: These lookups will break if the module has no __esModule set, |
| 336 | // hence the warning that 'compiled' will not work on standard CommonJS. |
| 337 | |
| 338 | builder.import(); |
| 339 | if (isNamespace) { |
| 340 | builder.namespace(name || importedSource); |
| 341 | } else if (isDefault || isNamed) { |
| 342 | builder.named(name, importName); |
| 343 | } |
| 344 | } else { |
| 345 | // var namespace = require(''); namespace |
| 346 | // var namespace = require(''); namespace.default |
| 347 | // var namespace = require(''); namespace.named |
| 348 | // var named = require('').named; |
| 349 | builder.require(); |
| 350 | if (isNamespace) { |
| 351 | builder.var(name || importedSource); |
| 352 | } else if (isDefault || isNamed) { |
| 353 | if (ensureLiveReference) { |
| 354 | builder.var(importedSource).read(name); |
| 355 | } else { |
| 356 | builder.prop(importName).var(name); |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | } else if (importedInterop === "uncompiled") { |
| 361 | if (isDefault && ensureLiveReference) { |
| 362 | throw new Error("No live reference for commonjs default"); |
| 363 | } |
| 364 | |
| 365 | if (isModuleForNode) { |
| 366 | // import namespace from ''; namespace |
| 367 | // import def from ''; def; |
| 368 | // import namespace from ''; namespace.named |
| 369 | builder.import(); |
| 370 | if (isNamespace) { |
| 371 | builder.default(name || importedSource); |
| 372 | } else if (isDefault) { |
| 373 | builder.default(name); |
| 374 | } else if (isNamed) { |
| 375 | builder.default(importedSource).read(name); |
| 376 | } |
| 377 | } else if (isModuleForBabel) { |
| 378 | // import namespace from ''; |
| 379 | // import def from ''; |
| 380 | // import { named } from ''; named; |
| 381 | // Note: These lookups will break if the module has __esModule set, |
| 382 | // hence the warning that 'uncompiled' will not work on ES6 transpiled |
| 383 | // to CommonJS. |
| 384 | |
| 385 | builder.import(); |
| 386 | if (isNamespace) { |
| 387 | builder.default(name || importedSource); |
| 388 | } else if (isDefault) { |
| 389 | builder.default(name); |
| 390 | } else if (isNamed) { |
| 391 | builder.named(name, importName); |
| 392 | } |
| 393 | } else { |
| 394 | // var namespace = require(''); namespace |
| 395 | // var def = require(''); def |
| 396 | // var namespace = require(''); namespace.named |
| 397 | // var named = require('').named; |
| 398 | builder.require(); |
| 399 | if (isNamespace) { |
| 400 | builder.var(name || importedSource); |
| 401 | } else if (isDefault) { |
| 402 | builder.var(name); |
| 403 | } else if (isNamed) { |
| 404 | if (ensureLiveReference) { |
| 405 | builder.var(importedSource).read(name); |
| 406 | } else { |
| 407 | builder.var(name).prop(importName); |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | } else { |
| 412 | throw new Error(`Unknown importedInterop "${importedInterop}".`); |
| 413 | } |
| 414 | |
| 415 | const { statements, resultName } = builder.done(); |
| 416 | |
| 417 | this._insertStatements(statements, importPosition, blockHoist); |
| 418 | |
| 419 | if ( |
| 420 | (isDefault || isNamed) && |
| 421 | ensureNoContext && |
| 422 | resultName.type !== "Identifier" |
| 423 | ) { |
| 424 | return sequenceExpression([numericLiteral(0), resultName]); |
| 425 | } |
| 426 | return resultName; |
| 427 | } |
| 428 | |
| 429 | _insertStatements( |
| 430 | statements: t.Statement[], |
| 431 | importPosition = "before", |
| 432 | blockHoist = 3, |
| 433 | ) { |
| 434 | const body = this._programPath.get("body"); |
| 435 | |
| 436 | if (importPosition === "after") { |
| 437 | for (let i = body.length - 1; i >= 0; i--) { |
| 438 | if (body[i].isImportDeclaration()) { |
| 439 | body[i].insertAfter(statements); |
| 440 | return; |
| 441 | } |
| 442 | } |
| 443 | } else { |
| 444 | statements.forEach(node => { |
| 445 | // @ts-expect-error handle _blockHoist |
| 446 | node._blockHoist = blockHoist; |
| 447 | }); |
| 448 | |
| 449 | const targetPath = body.find(p => { |
| 450 | // @ts-expect-error todo(flow->ts): avoid mutations |
| 451 | const val = p.node._blockHoist; |
| 452 | return Number.isFinite(val) && val < 4; |
| 453 | }); |
| 454 | |
| 455 | if (targetPath) { |
| 456 | targetPath.insertBefore(statements); |
| 457 | return; |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | this._programPath.unshiftContainer("body", statements); |
| 462 | } |
| 463 | } |