| 1 |
import gensync, { type Handler } from "gensync"; |
| 2 |
import { forwardAsync, maybeAsync, isThenable } from "../gensync-utils/async"; |
| 3 |
|
| 4 |
import { mergeOptions } from "./util"; |
| 5 |
import * as context from "../index"; |
| 6 |
import Plugin from "./plugin"; |
| 7 |
import { getItemDescriptor } from "./item"; |
| 8 |
import { buildPresetChain } from "./config-chain"; |
| 9 |
import { finalize as freezeDeepArray } from "./helpers/deep-array"; |
| 10 |
import type { DeepArray, ReadonlyDeepArray } from "./helpers/deep-array"; |
| 11 |
import type { |
| 12 |
ConfigContext, |
| 13 |
ConfigChain, |
| 14 |
PresetInstance, |
| 15 |
} from "./config-chain"; |
| 16 |
import type { UnloadedDescriptor } from "./config-descriptors"; |
| 17 |
import traverse from "@babel/traverse"; |
| 18 |
import { makeWeakCache, makeWeakCacheSync } from "./caching"; |
| 19 |
import type { CacheConfigurator } from "./caching"; |
| 20 |
import { |
| 21 |
validate, |
| 22 |
checkNoUnwrappedItemOptionPairs, |
| 23 |
} from "./validation/options"; |
| 24 |
import type { PluginItem } from "./validation/options"; |
| 25 |
import { validatePluginObject } from "./validation/plugins"; |
| 26 |
import { makePluginAPI, makePresetAPI } from "./helpers/config-api"; |
| 27 |
import type { PluginAPI, PresetAPI } from "./helpers/config-api"; |
| 28 |
|
| 29 |
import loadPrivatePartialConfig from "./partial"; |
| 30 |
import type { ValidatedOptions } from "./validation/options"; |
| 31 |
|
| 32 |
import type * as Context from "./cache-contexts"; |
| 33 |
import ConfigError from "../errors/config-error"; |
| 34 |
|
| 35 |
type LoadedDescriptor = { |
| 36 |
value: {}; |
| 37 |
options: {}; |
| 38 |
dirname: string; |
| 39 |
alias: string; |
| 40 |
externalDependencies: ReadonlyDeepArray<string>; |
| 41 |
}; |
| 42 |
|
| 43 |
export type { InputOptions } from "./validation/options"; |
| 44 |
|
| 45 |
export type ResolvedConfig = { |
| 46 |
options: any; |
| 47 |
passes: PluginPasses; |
| 48 |
externalDependencies: ReadonlyDeepArray<string>; |
| 49 |
}; |
| 50 |
|
| 51 |
export type { Plugin }; |
| 52 |
export type PluginPassList = Array<Plugin>; |
| 53 |
export type PluginPasses = Array<PluginPassList>; |
| 54 |
|
| 55 |
export default gensync(function* loadFullConfig( |
| 56 |
inputOpts: unknown, |
| 57 |
): Handler<ResolvedConfig | null> { |
| 58 |
const result = yield* loadPrivatePartialConfig(inputOpts); |
| 59 |
if (!result) { |
| 60 |
return null; |
| 61 |
} |
| 62 |
const { options, context, fileHandling } = result; |
| 63 |
|
| 64 |
if (fileHandling === "ignored") { |
| 65 |
return null; |
| 66 |
} |
| 67 |
|
| 68 |
const optionDefaults = {}; |
| 69 |
|
| 70 |
const { plugins, presets } = options; |
| 71 |
|
| 72 |
if (!plugins || !presets) { |
| 73 |
throw new Error("Assertion failure - plugins and presets exist"); |
| 74 |
} |
| 75 |
|
| 76 |
const presetContext: Context.FullPreset = { |
| 77 |
...context, |
| 78 |
targets: options.targets, |
| 79 |
}; |
| 80 |
|
| 81 |
const toDescriptor = (item: PluginItem) => { |
| 82 |
const desc = getItemDescriptor(item); |
| 83 |
if (!desc) { |
| 84 |
throw new Error("Assertion failure - must be config item"); |
| 85 |
} |
| 86 |
|
| 87 |
return desc; |
| 88 |
}; |
| 89 |
|
| 90 |
const presetsDescriptors = presets.map(toDescriptor); |
| 91 |
const initialPluginsDescriptors = plugins.map(toDescriptor); |
| 92 |
const pluginDescriptorsByPass: Array<Array<UnloadedDescriptor>> = [[]]; |
| 93 |
const passes: Array<Array<Plugin>> = []; |
| 94 |
|
| 95 |
const externalDependencies: DeepArray<string> = []; |
| 96 |
|
| 97 |
const ignored = yield* enhanceError( |
| 98 |
context, |
| 99 |
function* recursePresetDescriptors( |
| 100 |
rawPresets: Array<UnloadedDescriptor>, |
| 101 |
pluginDescriptorsPass: Array<UnloadedDescriptor>, |
| 102 |
): Handler<true | void> { |
| 103 |
const presets: Array<{ |
| 104 |
preset: ConfigChain | null; |
| 105 |
pass: Array<UnloadedDescriptor>; |
| 106 |
}> = []; |
| 107 |
|
| 108 |
for (let i = 0; i < rawPresets.length; i++) { |
| 109 |
const descriptor = rawPresets[i]; |
| 110 |
if (descriptor.options !== false) { |
| 111 |
try { |
| 112 |
// eslint-disable-next-line no-var |
| 113 |
var preset = yield* loadPresetDescriptor(descriptor, presetContext); |
| 114 |
} catch (e) { |
| 115 |
if (e.code === "BABEL_UNKNOWN_OPTION") { |
| 116 |
checkNoUnwrappedItemOptionPairs(rawPresets, i, "preset", e); |
| 117 |
} |
| 118 |
throw e; |
| 119 |
} |
| 120 |
|
| 121 |
externalDependencies.push(preset.externalDependencies); |
| 122 |
|
| 123 |
// Presets normally run in reverse order, but if they |
| 124 |
// have their own pass they run after the presets |
| 125 |
// in the previous pass. |
| 126 |
if (descriptor.ownPass) { |
| 127 |
presets.push({ preset: preset.chain, pass: [] }); |
| 128 |
} else { |
| 129 |
presets.unshift({ |
| 130 |
preset: preset.chain, |
| 131 |
pass: pluginDescriptorsPass, |
| 132 |
}); |
| 133 |
} |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
// resolve presets |
| 138 |
if (presets.length > 0) { |
| 139 |
// The passes are created in the same order as the preset list, but are inserted before any |
| 140 |
// existing additional passes. |
| 141 |
pluginDescriptorsByPass.splice( |
| 142 |
1, |
| 143 |
0, |
| 144 |
...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass), |
| 145 |
); |
| 146 |
|
| 147 |
for (const { preset, pass } of presets) { |
| 148 |
if (!preset) return true; |
| 149 |
|
| 150 |
pass.push(...preset.plugins); |
| 151 |
|
| 152 |
const ignored = yield* recursePresetDescriptors(preset.presets, pass); |
| 153 |
if (ignored) return true; |
| 154 |
|
| 155 |
preset.options.forEach(opts => { |
| 156 |
mergeOptions(optionDefaults, opts); |
| 157 |
}); |
| 158 |
} |
| 159 |
} |
| 160 |
}, |
| 161 |
)(presetsDescriptors, pluginDescriptorsByPass[0]); |
| 162 |
|
| 163 |
if (ignored) return null; |
| 164 |
|
| 165 |
const opts: any = optionDefaults; |
| 166 |
mergeOptions(opts, options); |
| 167 |
|
| 168 |
const pluginContext: Context.FullPlugin = { |
| 169 |
...presetContext, |
| 170 |
assumptions: opts.assumptions ?? {}, |
| 171 |
}; |
| 172 |
|
| 173 |
yield* enhanceError(context, function* loadPluginDescriptors() { |
| 174 |
pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); |
| 175 |
|
| 176 |
for (const descs of pluginDescriptorsByPass) { |
| 177 |
const pass: Plugin[] = []; |
| 178 |
passes.push(pass); |
| 179 |
|
| 180 |
for (let i = 0; i < descs.length; i++) { |
| 181 |
const descriptor: UnloadedDescriptor = descs[i]; |
| 182 |
if (descriptor.options !== false) { |
| 183 |
try { |
| 184 |
// eslint-disable-next-line no-var |
| 185 |
var plugin = yield* loadPluginDescriptor(descriptor, pluginContext); |
| 186 |
} catch (e) { |
| 187 |
if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { |
| 188 |
// print special message for `plugins: ["@babel/foo", { foo: "option" }]` |
| 189 |
checkNoUnwrappedItemOptionPairs(descs, i, "plugin", e); |
| 190 |
} |
| 191 |
throw e; |
| 192 |
} |
| 193 |
pass.push(plugin); |
| 194 |
|
| 195 |
externalDependencies.push(plugin.externalDependencies); |
| 196 |
} |
| 197 |
} |
| 198 |
} |
| 199 |
})(); |
| 200 |
|
| 201 |
opts.plugins = passes[0]; |
| 202 |
opts.presets = passes |
| 203 |
.slice(1) |
| 204 |
.filter(plugins => plugins.length > 0) |
| 205 |
.map(plugins => ({ plugins })); |
| 206 |
opts.passPerPreset = opts.presets.length > 0; |
| 207 |
|
| 208 |
return { |
| 209 |
options: opts, |
| 210 |
passes: passes, |
| 211 |
externalDependencies: freezeDeepArray(externalDependencies), |
| 212 |
}; |
| 213 |
}); |
| 214 |
|
| 215 |
function enhanceError<T extends Function>(context: ConfigContext, fn: T): T { |
| 216 |
return function* (arg1: unknown, arg2: unknown) { |
| 217 |
try { |
| 218 |
return yield* fn(arg1, arg2); |
| 219 |
} catch (e) { |
| 220 |
// There are a few case where thrown errors will try to annotate themselves multiple times, so |
| 221 |
// to keep things simple we just bail out if re-wrapping the message. |
| 222 |
if (!/^\[BABEL\]/.test(e.message)) { |
| 223 |
e.message = `[BABEL] ${context.filename ?? "unknown file"}: ${ |
| 224 |
e.message |
| 225 |
}`; |
| 226 |
} |
| 227 |
|
| 228 |
throw e; |
| 229 |
} |
| 230 |
} as any; |
| 231 |
} |
| 232 |
|
| 233 |
/** |
| 234 |
* Load a generic plugin/preset from the given descriptor loaded from the config object. |
| 235 |
*/ |
| 236 |
const makeDescriptorLoader = <Context, API>( |
| 237 |
apiFactory: ( |
| 238 |
cache: CacheConfigurator<Context>, |
| 239 |
externalDependencies: Array<string>, |
| 240 |
) => API, |
| 241 |
) => |
| 242 |
makeWeakCache(function* ( |
| 243 |
{ value, options, dirname, alias }: UnloadedDescriptor, |
| 244 |
cache: CacheConfigurator<Context>, |
| 245 |
): Handler<LoadedDescriptor> { |
| 246 |
// Disabled presets should already have been filtered out |
| 247 |
if (options === false) throw new Error("Assertion failure"); |
| 248 |
|
| 249 |
options = options || {}; |
| 250 |
|
| 251 |
const externalDependencies: Array<string> = []; |
| 252 |
|
| 253 |
let item = value; |
| 254 |
if (typeof value === "function") { |
| 255 |
const factory = maybeAsync( |
| 256 |
value, |
| 257 |
`You appear to be using an async plugin/preset, but Babel has been called synchronously`, |
| 258 |
); |
| 259 |
|
| 260 |
const api = { |
| 261 |
...context, |
| 262 |
...apiFactory(cache, externalDependencies), |
| 263 |
}; |
| 264 |
try { |
| 265 |
item = yield* factory(api, options, dirname); |
| 266 |
} catch (e) { |
| 267 |
if (alias) { |
| 268 |
e.message += ` (While processing: ${JSON.stringify(alias)})`; |
| 269 |
} |
| 270 |
throw e; |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
if (!item || typeof item !== "object") { |
| 275 |
throw new Error("Plugin/Preset did not return an object."); |
| 276 |
} |
| 277 |
|
| 278 |
if (isThenable(item)) { |
| 279 |
// @ts-expect-error - if we want to support async plugins |
| 280 |
yield* []; |
| 281 |
|
| 282 |
throw new Error( |
| 283 |
`You appear to be using a promise as a plugin, ` + |
| 284 |
`which your current version of Babel does not support. ` + |
| 285 |
`If you're using a published plugin, ` + |
| 286 |
`you may need to upgrade your @babel/core version. ` + |
| 287 |
`As an alternative, you can prefix the promise with "await". ` + |
| 288 |
`(While processing: ${JSON.stringify(alias)})`, |
| 289 |
); |
| 290 |
} |
| 291 |
|
| 292 |
if ( |
| 293 |
externalDependencies.length > 0 && |
| 294 |
(!cache.configured() || cache.mode() === "forever") |
| 295 |
) { |
| 296 |
let error = |
| 297 |
`A plugin/preset has external untracked dependencies ` + |
| 298 |
`(${externalDependencies[0]}), but the cache `; |
| 299 |
if (!cache.configured()) { |
| 300 |
error += `has not been configured to be invalidated when the external dependencies change. `; |
| 301 |
} else { |
| 302 |
error += ` has been configured to never be invalidated. `; |
| 303 |
} |
| 304 |
error += |
| 305 |
`Plugins/presets should configure their cache to be invalidated when the external ` + |
| 306 |
`dependencies change, for example using \`api.cache.invalidate(() => ` + |
| 307 |
`statSync(filepath).mtimeMs)\` or \`api.cache.never()\`\n` + |
| 308 |
`(While processing: ${JSON.stringify(alias)})`; |
| 309 |
|
| 310 |
throw new Error(error); |
| 311 |
} |
| 312 |
|
| 313 |
return { |
| 314 |
value: item, |
| 315 |
options, |
| 316 |
dirname, |
| 317 |
alias, |
| 318 |
externalDependencies: freezeDeepArray(externalDependencies), |
| 319 |
}; |
| 320 |
}); |
| 321 |
|
| 322 |
const pluginDescriptorLoader = makeDescriptorLoader< |
| 323 |
Context.SimplePlugin, |
| 324 |
PluginAPI |
| 325 |
>(makePluginAPI); |
| 326 |
const presetDescriptorLoader = makeDescriptorLoader< |
| 327 |
Context.SimplePreset, |
| 328 |
PresetAPI |
| 329 |
>(makePresetAPI); |
| 330 |
|
| 331 |
const instantiatePlugin = makeWeakCache(function* ( |
| 332 |
{ value, options, dirname, alias, externalDependencies }: LoadedDescriptor, |
| 333 |
cache: CacheConfigurator<Context.SimplePlugin>, |
| 334 |
): Handler<Plugin> { |
| 335 |
const pluginObj = validatePluginObject(value); |
| 336 |
|
| 337 |
const plugin = { |
| 338 |
...pluginObj, |
| 339 |
}; |
| 340 |
if (plugin.visitor) { |
| 341 |
plugin.visitor = traverse.explode({ |
| 342 |
...plugin.visitor, |
| 343 |
}); |
| 344 |
} |
| 345 |
|
| 346 |
if (plugin.inherits) { |
| 347 |
const inheritsDescriptor: UnloadedDescriptor = { |
| 348 |
name: undefined, |
| 349 |
alias: `${alias}$inherits`, |
| 350 |
value: plugin.inherits, |
| 351 |
options, |
| 352 |
dirname, |
| 353 |
}; |
| 354 |
|
| 355 |
const inherits = yield* forwardAsync(loadPluginDescriptor, run => { |
| 356 |
// If the inherited plugin changes, reinstantiate this plugin. |
| 357 |
return cache.invalidate(data => run(inheritsDescriptor, data)); |
| 358 |
}); |
| 359 |
|
| 360 |
plugin.pre = chain(inherits.pre, plugin.pre); |
| 361 |
plugin.post = chain(inherits.post, plugin.post); |
| 362 |
plugin.manipulateOptions = chain( |
| 363 |
inherits.manipulateOptions, |
| 364 |
plugin.manipulateOptions, |
| 365 |
); |
| 366 |
plugin.visitor = traverse.visitors.merge([ |
| 367 |
inherits.visitor || {}, |
| 368 |
plugin.visitor || {}, |
| 369 |
]); |
| 370 |
|
| 371 |
if (inherits.externalDependencies.length > 0) { |
| 372 |
if (externalDependencies.length === 0) { |
| 373 |
externalDependencies = inherits.externalDependencies; |
| 374 |
} else { |
| 375 |
externalDependencies = freezeDeepArray([ |
| 376 |
externalDependencies, |
| 377 |
inherits.externalDependencies, |
| 378 |
]); |
| 379 |
} |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
return new Plugin(plugin, options, alias, externalDependencies); |
| 384 |
}); |
| 385 |
|
| 386 |
/** |
| 387 |
* Instantiate a plugin for the given descriptor, returning the plugin/options pair. |
| 388 |
*/ |
| 389 |
function* loadPluginDescriptor( |
| 390 |
descriptor: UnloadedDescriptor, |
| 391 |
context: Context.SimplePlugin, |
| 392 |
): Handler<Plugin> { |
| 393 |
if (descriptor.value instanceof Plugin) { |
| 394 |
if (descriptor.options) { |
| 395 |
throw new Error( |
| 396 |
"Passed options to an existing Plugin instance will not work.", |
| 397 |
); |
| 398 |
} |
| 399 |
|
| 400 |
return descriptor.value; |
| 401 |
} |
| 402 |
|
| 403 |
return yield* instantiatePlugin( |
| 404 |
yield* pluginDescriptorLoader(descriptor, context), |
| 405 |
context, |
| 406 |
); |
| 407 |
} |
| 408 |
|
| 409 |
const needsFilename = (val: unknown) => val && typeof val !== "function"; |
| 410 |
|
| 411 |
const validateIfOptionNeedsFilename = ( |
| 412 |
options: ValidatedOptions, |
| 413 |
descriptor: UnloadedDescriptor, |
| 414 |
): void => { |
| 415 |
if ( |
| 416 |
needsFilename(options.test) || |
| 417 |
needsFilename(options.include) || |
| 418 |
needsFilename(options.exclude) |
| 419 |
) { |
| 420 |
const formattedPresetName = descriptor.name |
| 421 |
? `"${descriptor.name}"` |
| 422 |
: "/* your preset */"; |
| 423 |
throw new ConfigError( |
| 424 |
[ |
| 425 |
`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, |
| 426 |
`\`\`\``, |
| 427 |
`babel.transformSync(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`, |
| 428 |
`\`\`\``, |
| 429 |
`See https://babeljs.io/docs/en/options#filename for more information.`, |
| 430 |
].join("\n"), |
| 431 |
); |
| 432 |
} |
| 433 |
}; |
| 434 |
|
| 435 |
const validatePreset = ( |
| 436 |
preset: PresetInstance, |
| 437 |
context: ConfigContext, |
| 438 |
descriptor: UnloadedDescriptor, |
| 439 |
): void => { |
| 440 |
if (!context.filename) { |
| 441 |
const { options } = preset; |
| 442 |
validateIfOptionNeedsFilename(options, descriptor); |
| 443 |
if (options.overrides) { |
| 444 |
options.overrides.forEach(overrideOptions => |
| 445 |
validateIfOptionNeedsFilename(overrideOptions, descriptor), |
| 446 |
); |
| 447 |
} |
| 448 |
} |
| 449 |
}; |
| 450 |
|
| 451 |
const instantiatePreset = makeWeakCacheSync( |
| 452 |
({ |
| 453 |
value, |
| 454 |
dirname, |
| 455 |
alias, |
| 456 |
externalDependencies, |
| 457 |
}: LoadedDescriptor): PresetInstance => { |
| 458 |
return { |
| 459 |
options: validate("preset", value), |
| 460 |
alias, |
| 461 |
dirname, |
| 462 |
externalDependencies, |
| 463 |
}; |
| 464 |
}, |
| 465 |
); |
| 466 |
|
| 467 |
/** |
| 468 |
* Generate a config object that will act as the root of a new nested config. |
| 469 |
*/ |
| 470 |
function* loadPresetDescriptor( |
| 471 |
descriptor: UnloadedDescriptor, |
| 472 |
context: Context.FullPreset, |
| 473 |
): Handler<{ |
| 474 |
chain: ConfigChain | null; |
| 475 |
externalDependencies: ReadonlyDeepArray<string>; |
| 476 |
}> { |
| 477 |
const preset = instantiatePreset( |
| 478 |
yield* presetDescriptorLoader(descriptor, context), |
| 479 |
); |
| 480 |
validatePreset(preset, context, descriptor); |
| 481 |
return { |
| 482 |
chain: yield* buildPresetChain(preset, context), |
| 483 |
externalDependencies: preset.externalDependencies, |
| 484 |
}; |
| 485 |
} |
| 486 |
|
| 487 |
function chain<Args extends any[]>( |
| 488 |
a: undefined | ((...args: Args) => void), |
| 489 |
b: undefined | ((...args: Args) => void), |
| 490 |
) { |
| 491 |
const fns = [a, b].filter(Boolean); |
| 492 |
if (fns.length <= 1) return fns[0]; |
| 493 |
|
| 494 |
return function (this: unknown, ...args: unknown[]) { |
| 495 |
for (const fn of fns) { |
| 496 |
fn.apply(this, args); |
| 497 |
} |
| 498 |
}; |
| 499 |
} |