@babel/core
Advanced tools
| import gensync from 'gensync'; | ||
| const runGenerator = gensync(function* (item) { | ||
| return yield* item; | ||
| }); | ||
| const isAsync = gensync({ | ||
| sync: () => false, | ||
| errback: cb => cb(null, true) | ||
| }); | ||
| function maybeAsync(fn, message) { | ||
| return gensync({ | ||
| sync(...args) { | ||
| const result = fn.apply(this, args); | ||
| if (isThenable(result)) throw new Error(message); | ||
| return result; | ||
| }, | ||
| async(...args) { | ||
| return Promise.resolve(fn.apply(this, args)); | ||
| } | ||
| }); | ||
| } | ||
| const withKind = gensync({ | ||
| sync: cb => cb("sync"), | ||
| async: async cb => cb("async") | ||
| }); | ||
| function forwardAsync(action, cb) { | ||
| const g = gensync(action); | ||
| return withKind(kind => { | ||
| const adapted = g[kind]; | ||
| return cb(adapted); | ||
| }); | ||
| } | ||
| const onFirstPause = gensync({ | ||
| name: "onFirstPause", | ||
| arity: 2, | ||
| sync: function (item) { | ||
| return runGenerator.sync(item); | ||
| }, | ||
| errback: function (item, firstPause, cb) { | ||
| let completed = false; | ||
| runGenerator.errback(item, (err, value) => { | ||
| completed = true; | ||
| cb(err, value); | ||
| }); | ||
| if (!completed) { | ||
| firstPause(); | ||
| } | ||
| } | ||
| }); | ||
| const waitFor = gensync({ | ||
| sync: x => x, | ||
| async: async x => x | ||
| }); | ||
| function isThenable(val) { | ||
| return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; | ||
| } | ||
| function mergeOptions(target, source) { | ||
| for (const k of Object.keys(source)) { | ||
| if ((k === "parserOpts" || k === "generatorOpts" || k === "assumptions") && source[k]) { | ||
| const parserOpts = source[k]; | ||
| const targetObj = target[k] || (target[k] = {}); | ||
| mergeDefaultFields(targetObj, parserOpts); | ||
| } else { | ||
| const val = source[k]; | ||
| if (val !== undefined) target[k] = val; | ||
| } | ||
| } | ||
| } | ||
| function mergeDefaultFields(target, source) { | ||
| for (const k of Object.keys(source)) { | ||
| const val = source[k]; | ||
| if (val !== undefined) target[k] = val; | ||
| } | ||
| } | ||
| function isIterableIterator(value) { | ||
| return !!value && typeof value.next === "function" && typeof value[Symbol.iterator] === "function"; | ||
| } | ||
| const synchronize = gen => { | ||
| return gensync(gen).sync; | ||
| }; | ||
| function* genTrue() { | ||
| return true; | ||
| } | ||
| function makeWeakCache(handler) { | ||
| return makeCachedFunction(WeakMap, handler); | ||
| } | ||
| function makeWeakCacheSync(handler) { | ||
| return synchronize(makeWeakCache(handler)); | ||
| } | ||
| function makeStrongCache(handler) { | ||
| return makeCachedFunction(Map, handler); | ||
| } | ||
| function makeStrongCacheSync(handler) { | ||
| return synchronize(makeStrongCache(handler)); | ||
| } | ||
| function makeCachedFunction(CallCache, handler) { | ||
| const callCacheSync = new CallCache(); | ||
| const callCacheAsync = new CallCache(); | ||
| const futureCache = new CallCache(); | ||
| return function* cachedFunction(arg, data) { | ||
| const asyncContext = yield* isAsync(); | ||
| const callCache = asyncContext ? callCacheAsync : callCacheSync; | ||
| const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data); | ||
| if (cached.valid) return cached.value; | ||
| const cache = new CacheConfigurator(data); | ||
| const handlerResult = handler(arg, cache); | ||
| let finishLock; | ||
| let value; | ||
| if (isIterableIterator(handlerResult)) { | ||
| value = yield* onFirstPause(handlerResult, () => { | ||
| finishLock = setupAsyncLocks(cache, futureCache, arg); | ||
| }); | ||
| } else { | ||
| value = handlerResult; | ||
| } | ||
| updateFunctionCache(callCache, cache, arg, value); | ||
| if (finishLock) { | ||
| futureCache.delete(arg); | ||
| finishLock.release(value); | ||
| } | ||
| return value; | ||
| }; | ||
| } | ||
| function* getCachedValue(cache, arg, data) { | ||
| const cachedValue = cache.get(arg); | ||
| if (cachedValue) { | ||
| for (const { | ||
| value, | ||
| valid | ||
| } of cachedValue) { | ||
| if (yield* valid(data)) return { | ||
| valid: true, | ||
| value | ||
| }; | ||
| } | ||
| } | ||
| return { | ||
| valid: false, | ||
| value: null | ||
| }; | ||
| } | ||
| function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) { | ||
| const cached = yield* getCachedValue(callCache, arg, data); | ||
| if (cached.valid) { | ||
| return cached; | ||
| } | ||
| if (asyncContext) { | ||
| const cached = yield* getCachedValue(futureCache, arg, data); | ||
| if (cached.valid) { | ||
| const value = yield* waitFor(cached.value.promise); | ||
| return { | ||
| valid: true, | ||
| value | ||
| }; | ||
| } | ||
| } | ||
| return { | ||
| valid: false, | ||
| value: null | ||
| }; | ||
| } | ||
| function setupAsyncLocks(config, futureCache, arg) { | ||
| const finishLock = new Lock(); | ||
| updateFunctionCache(futureCache, config, arg, finishLock); | ||
| return finishLock; | ||
| } | ||
| function updateFunctionCache(cache, config, arg, value) { | ||
| if (!config.configured()) config.forever(); | ||
| let cachedValue = cache.get(arg); | ||
| config.deactivate(); | ||
| switch (config.mode()) { | ||
| case "forever": | ||
| cachedValue = [{ | ||
| value, | ||
| valid: genTrue | ||
| }]; | ||
| cache.set(arg, cachedValue); | ||
| break; | ||
| case "invalidate": | ||
| cachedValue = [{ | ||
| value, | ||
| valid: config.validator() | ||
| }]; | ||
| cache.set(arg, cachedValue); | ||
| break; | ||
| case "valid": | ||
| if (cachedValue) { | ||
| cachedValue.push({ | ||
| value, | ||
| valid: config.validator() | ||
| }); | ||
| } else { | ||
| cachedValue = [{ | ||
| value, | ||
| valid: config.validator() | ||
| }]; | ||
| cache.set(arg, cachedValue); | ||
| } | ||
| } | ||
| } | ||
| class CacheConfigurator { | ||
| _active = true; | ||
| _never = false; | ||
| _forever = false; | ||
| _invalidate = false; | ||
| _configured = false; | ||
| _pairs = []; | ||
| _data; | ||
| constructor(data) { | ||
| this._data = data; | ||
| } | ||
| simple() { | ||
| return makeSimpleConfigurator(this); | ||
| } | ||
| mode() { | ||
| if (this._never) return "never"; | ||
| if (this._forever) return "forever"; | ||
| if (this._invalidate) return "invalidate"; | ||
| return "valid"; | ||
| } | ||
| forever() { | ||
| if (!this._active) { | ||
| throw new Error("Cannot change caching after evaluation has completed."); | ||
| } | ||
| if (this._never) { | ||
| throw new Error("Caching has already been configured with .never()"); | ||
| } | ||
| this._forever = true; | ||
| this._configured = true; | ||
| } | ||
| never() { | ||
| if (!this._active) { | ||
| throw new Error("Cannot change caching after evaluation has completed."); | ||
| } | ||
| if (this._forever) { | ||
| throw new Error("Caching has already been configured with .forever()"); | ||
| } | ||
| this._never = true; | ||
| this._configured = true; | ||
| } | ||
| using(handler) { | ||
| if (!this._active) { | ||
| throw new Error("Cannot change caching after evaluation has completed."); | ||
| } | ||
| if (this._never || this._forever) { | ||
| throw new Error("Caching has already been configured with .never or .forever()"); | ||
| } | ||
| this._configured = true; | ||
| const key = handler(this._data); | ||
| const fn = maybeAsync(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`); | ||
| if (isThenable(key)) { | ||
| return key.then(key => { | ||
| this._pairs.push([key, fn]); | ||
| return key; | ||
| }); | ||
| } | ||
| this._pairs.push([key, fn]); | ||
| return key; | ||
| } | ||
| invalidate(handler) { | ||
| this._invalidate = true; | ||
| return this.using(handler); | ||
| } | ||
| validator() { | ||
| const pairs = this._pairs; | ||
| return function* (data) { | ||
| for (const [key, fn] of pairs) { | ||
| if (key !== (yield* fn(data))) return false; | ||
| } | ||
| return true; | ||
| }; | ||
| } | ||
| deactivate() { | ||
| this._active = false; | ||
| } | ||
| configured() { | ||
| return this._configured; | ||
| } | ||
| } | ||
| function makeSimpleConfigurator(cache) { | ||
| function cacheFn(val) { | ||
| if (typeof val === "boolean") { | ||
| if (val) cache.forever();else cache.never(); | ||
| return; | ||
| } | ||
| return cache.using(() => assertSimpleType(val())); | ||
| } | ||
| cacheFn.forever = () => cache.forever(); | ||
| cacheFn.never = () => cache.never(); | ||
| cacheFn.using = cb => cache.using(() => assertSimpleType(cb())); | ||
| cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb())); | ||
| return cacheFn; | ||
| } | ||
| function assertSimpleType(value) { | ||
| if (isThenable(value)) { | ||
| throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`); | ||
| } | ||
| if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") { | ||
| throw new Error("Cache keys must be either string, boolean, number, null, or undefined."); | ||
| } | ||
| return value; | ||
| } | ||
| class Lock { | ||
| released = false; | ||
| promise; | ||
| _resolve; | ||
| constructor() { | ||
| this.promise = new Promise(resolve => { | ||
| this._resolve = resolve; | ||
| }); | ||
| } | ||
| release(value) { | ||
| this.released = true; | ||
| this._resolve(value); | ||
| } | ||
| } | ||
| export { makeWeakCache as a, makeWeakCacheSync as b, makeStrongCacheSync as c, assertSimpleType as d, mergeOptions as e, maybeAsync as f, isThenable as g, forwardAsync as h, isAsync as i, makeStrongCache as m, waitFor as w }; | ||
| //# sourceMappingURL=caching-2iA7hK9v.js.map |
| {"version":3,"file":"caching-2iA7hK9v.js","sources":["../src/gensync-utils/async.ts","../src/config/util.ts","../src/config/caching.ts"],"sourcesContent":["import gensync, { type Gensync, type Handler, type Callback } from \"gensync\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nconst runGenerator: {\n sync<Return>(gen: Handler<Return>): Return;\n async<Return>(gen: Handler<Return>): Promise<Return>;\n errback<Return>(gen: Handler<Return>, cb: Callback<Return>): void;\n} = gensync(function* (item: Handler<any>): Handler<any> {\n return yield* item;\n});\n\n// This Gensync returns true if the current execution context is\n// asynchronous, otherwise it returns false.\nexport const isAsync = gensync({\n sync: () => false,\n errback: cb => cb(null, true),\n});\n\n// This function wraps any functions (which could be either synchronous or\n// asynchronous) with a Gensync. If the wrapped function returns a promise\n// but the current execution context is synchronous, it will throw the\n// provided error.\n// This is used to handle user-provided functions which could be asynchronous.\nexport function maybeAsync<Args extends unknown[], Return>(\n fn: (...args: Args) => Return,\n message: string,\n): Gensync<Args, Return> {\n return gensync({\n sync(...args) {\n const result = fn.apply(this, args);\n if (isThenable(result)) throw new Error(message);\n return result;\n },\n async(...args) {\n return Promise.resolve(fn.apply(this, args));\n },\n });\n}\n\nconst withKind = gensync({\n sync: cb => cb(\"sync\"),\n async: async cb => cb(\"async\"),\n}) as <T>(cb: (kind: \"sync\" | \"async\") => MaybePromise<T>) => Handler<T>;\n\n// This function wraps a generator (or a Gensync) into another function which,\n// when called, will run the provided generator in a sync or async way, depending\n// on the execution context where this forwardAsync function is called.\n// This is useful, for example, when passing a callback to a function which isn't\n// aware of gensync, but it only knows about synchronous and asynchronous functions.\n// An example is cache.using, which being exposed to the user must be as simple as\n// possible:\n// yield* forwardAsync(gensyncFn, wrappedFn =>\n// cache.using(x => {\n// // Here we don't know about gensync. wrappedFn is a\n// // normal sync or async function\n// return wrappedFn(x);\n// })\n// )\nexport function forwardAsync<Args extends unknown[], Return>(\n action: (...args: Args) => Handler<Return>,\n cb: (\n adapted: (...args: Args) => MaybePromise<Return>,\n ) => MaybePromise<Return>,\n): Handler<Return> {\n const g = gensync(action);\n return withKind(kind => {\n const adapted = g[kind];\n return cb(adapted);\n });\n}\n\n// If the given generator is executed asynchronously, the first time that it\n// is paused (i.e. When it yields a gensync generator which can't be run\n// synchronously), call the \"firstPause\" callback.\nexport const onFirstPause = gensync<\n [gen: Handler<unknown>, firstPause: () => void],\n unknown\n>({\n name: \"onFirstPause\",\n arity: 2,\n sync: function (item) {\n return runGenerator.sync(item);\n },\n errback: function (item, firstPause, cb) {\n let completed = false;\n\n runGenerator.errback(item, (err, value) => {\n completed = true;\n cb(err, value);\n });\n\n if (!completed) {\n firstPause();\n }\n },\n}) as <T>(gen: Handler<T>, firstPause: () => void) => Handler<T>;\n\n// Wait for the given promise to be resolved\nexport const waitFor = gensync({\n sync: x => x,\n async: async x => x,\n}) as <T>(p: T | Promise<T>) => Handler<T>;\n\nexport function isThenable<T = any>(val: any): val is PromiseLike<T> {\n return (\n !!val &&\n (typeof val === \"object\" || typeof val === \"function\") &&\n !!val.then &&\n typeof val.then === \"function\"\n );\n}\n","import type { InputOptions, ResolvedOptions } from \"./validation/options.ts\";\n\nexport function mergeOptions(\n target: InputOptions | ResolvedOptions,\n source: InputOptions,\n): void {\n for (const k of Object.keys(source)) {\n if (\n (k === \"parserOpts\" || k === \"generatorOpts\" || k === \"assumptions\") &&\n source[k]\n ) {\n const parserOpts = source[k];\n const targetObj = target[k] || (target[k] = {});\n mergeDefaultFields(targetObj, parserOpts);\n } else {\n //@ts-expect-error k must index source\n const val = source[k];\n //@ts-expect-error assigning source to target\n if (val !== undefined) target[k] = val as any;\n }\n }\n}\n\nfunction mergeDefaultFields<T extends object>(target: T, source: T) {\n for (const k of Object.keys(source) as (keyof T)[]) {\n const val = source[k];\n if (val !== undefined) target[k] = val;\n }\n}\n\nexport function isIterableIterator(value: any): value is IterableIterator<any> {\n return (\n !!value &&\n typeof value.next === \"function\" &&\n typeof value[Symbol.iterator] === \"function\"\n );\n}\n","import gensync from \"gensync\";\nimport type { Handler } from \"gensync\";\nimport {\n maybeAsync,\n isAsync,\n onFirstPause,\n waitFor,\n isThenable,\n} from \"../gensync-utils/async.ts\";\nimport { isIterableIterator } from \"./util.ts\";\n\nexport type { CacheConfigurator };\n\nexport type SimpleCacheConfigurator = {\n (forever: boolean): void;\n <T extends SimpleType>(handler: () => T): T;\n\n forever: () => void;\n never: () => void;\n using: <T extends SimpleType>(handler: () => T) => T;\n invalidate: <T extends SimpleType>(handler: () => T) => T;\n};\n\nexport type CacheEntry<ResultT, SideChannel> = {\n value: ResultT;\n valid: (channel: SideChannel) => Handler<boolean>;\n}[];\n\nconst synchronize = <ArgsT extends unknown[], ResultT>(\n gen: (...args: ArgsT) => Handler<ResultT>,\n): ((...args: ArgsT) => ResultT) => {\n return gensync(gen).sync;\n};\n\n// eslint-disable-next-line require-yield\nfunction* genTrue() {\n return true;\n}\n\nexport function makeWeakCache<ArgT extends object, ResultT, SideChannel>(\n handler: (\n arg: ArgT,\n cache: CacheConfigurator<SideChannel>,\n ) => Handler<ResultT> | ResultT,\n): (arg: ArgT, data: SideChannel) => Handler<ResultT> {\n return makeCachedFunction<ArgT, ResultT, SideChannel>(WeakMap, handler);\n}\n\nexport function makeWeakCacheSync<ArgT extends object, ResultT, SideChannel>(\n handler: (arg: ArgT, cache?: CacheConfigurator<SideChannel>) => ResultT,\n): (arg: ArgT, data?: SideChannel) => ResultT {\n return synchronize<[ArgT, SideChannel], ResultT>(\n makeWeakCache<ArgT, ResultT, SideChannel>(handler),\n );\n}\n\nexport function makeStrongCache<ArgT, ResultT, SideChannel>(\n handler: (\n arg: ArgT,\n cache: CacheConfigurator<SideChannel>,\n ) => Handler<ResultT> | ResultT,\n): (arg: ArgT, data: SideChannel) => Handler<ResultT> {\n return makeCachedFunction<ArgT, ResultT, SideChannel>(Map, handler);\n}\n\nexport function makeStrongCacheSync<ArgT, ResultT, SideChannel>(\n handler: (arg: ArgT, cache?: CacheConfigurator<SideChannel>) => ResultT,\n): (arg: ArgT, data?: SideChannel) => ResultT {\n return synchronize<[ArgT, SideChannel], ResultT>(\n makeStrongCache<ArgT, ResultT, SideChannel>(handler),\n );\n}\n\n/* NOTE: Part of the logic explained in this comment is explained in the\n * getCachedValueOrWait and setupAsyncLocks functions.\n *\n * > There are only two hard things in Computer Science: cache invalidation and naming things.\n * > -- Phil Karlton\n *\n * I don't know if Phil was also thinking about handling a cache whose invalidation function is\n * defined asynchronously is considered, but it is REALLY hard to do correctly.\n *\n * The implemented logic (only when gensync is run asynchronously) is the following:\n * 1. If there is a valid cache associated to the current \"arg\" parameter,\n * a. RETURN the cached value\n * 3. If there is a FinishLock associated to the current \"arg\" parameter representing a valid cache,\n * a. Wait for that lock to be released\n * b. RETURN the value associated with that lock\n * 5. Start executing the function to be cached\n * a. If it pauses on a promise, then\n * i. Let FinishLock be a new lock\n * ii. Store FinishLock as associated to the current \"arg\" parameter\n * iii. Wait for the function to finish executing\n * iv. Release FinishLock\n * v. Send the function result to anyone waiting on FinishLock\n * 6. Store the result in the cache\n * 7. RETURN the result\n */\nfunction makeCachedFunction<ArgT, ResultT, SideChannel>(\n CallCache: new <Cached>() => CacheMap<ArgT, Cached, SideChannel>,\n handler: (\n arg: ArgT,\n cache: CacheConfigurator<SideChannel>,\n ) => Handler<ResultT> | ResultT,\n): (arg: ArgT, data: SideChannel) => Handler<ResultT> {\n const callCacheSync = new CallCache<ResultT>();\n const callCacheAsync = new CallCache<ResultT>();\n const futureCache = new CallCache<Lock<ResultT>>();\n\n return function* cachedFunction(arg: ArgT, data: SideChannel) {\n const asyncContext = yield* isAsync();\n const callCache = asyncContext ? callCacheAsync : callCacheSync;\n\n const cached = yield* getCachedValueOrWait<ArgT, ResultT, SideChannel>(\n asyncContext,\n callCache,\n futureCache,\n arg,\n data,\n );\n if (cached.valid) return cached.value;\n\n const cache = new CacheConfigurator(data);\n\n const handlerResult: Handler<ResultT> | ResultT = handler(arg, cache);\n\n let finishLock: Lock<ResultT>;\n let value: ResultT;\n\n if (isIterableIterator(handlerResult)) {\n value = yield* onFirstPause(handlerResult, () => {\n finishLock = setupAsyncLocks(cache, futureCache, arg);\n });\n } else {\n value = handlerResult;\n }\n\n updateFunctionCache(callCache, cache, arg, value);\n\n if (finishLock!) {\n futureCache.delete(arg);\n finishLock.release(value);\n }\n\n return value;\n };\n}\n\ntype CacheMap<ArgT, ResultT, SideChannel> =\n | Map<ArgT, CacheEntry<ResultT, SideChannel>>\n // @ts-expect-error todo(flow->ts): add `extends object` constraint to ArgT\n | WeakMap<ArgT, CacheEntry<ResultT, SideChannel>>;\n\nfunction* getCachedValue<ArgT, ResultT, SideChannel>(\n cache: CacheMap<ArgT, ResultT, SideChannel>,\n arg: ArgT,\n data: SideChannel,\n): Handler<{ valid: true; value: ResultT } | { valid: false; value: null }> {\n const cachedValue: CacheEntry<ResultT, SideChannel> | void = cache.get(arg);\n\n if (cachedValue) {\n for (const { value, valid } of cachedValue) {\n if (yield* valid(data)) return { valid: true, value };\n }\n }\n\n return { valid: false, value: null };\n}\n\nfunction* getCachedValueOrWait<ArgT, ResultT, SideChannel>(\n asyncContext: boolean,\n callCache: CacheMap<ArgT, ResultT, SideChannel>,\n futureCache: CacheMap<ArgT, Lock<ResultT>, SideChannel>,\n arg: ArgT,\n data: SideChannel,\n): Handler<{ valid: true; value: ResultT } | { valid: false; value: null }> {\n const cached = yield* getCachedValue(callCache, arg, data);\n if (cached.valid) {\n return cached;\n }\n\n if (asyncContext) {\n const cached = yield* getCachedValue(futureCache, arg, data);\n if (cached.valid) {\n const value = yield* waitFor<ResultT>(cached.value.promise);\n return { valid: true, value };\n }\n }\n\n return { valid: false, value: null };\n}\n\nfunction setupAsyncLocks<ArgT, ResultT, SideChannel>(\n config: CacheConfigurator<SideChannel>,\n futureCache: CacheMap<ArgT, Lock<ResultT>, SideChannel>,\n arg: ArgT,\n): Lock<ResultT> {\n const finishLock = new Lock<ResultT>();\n\n updateFunctionCache(futureCache, config, arg, finishLock);\n\n return finishLock;\n}\n\nfunction updateFunctionCache<\n ArgT,\n ResultT,\n SideChannel,\n Cache extends CacheMap<ArgT, ResultT, SideChannel>,\n>(\n cache: Cache,\n config: CacheConfigurator<SideChannel>,\n arg: ArgT,\n value: ResultT,\n) {\n if (!config.configured()) config.forever();\n\n let cachedValue: CacheEntry<ResultT, SideChannel> | void = cache.get(arg);\n\n config.deactivate();\n\n switch (config.mode()) {\n case \"forever\":\n cachedValue = [{ value, valid: genTrue }];\n cache.set(arg, cachedValue);\n break;\n case \"invalidate\":\n cachedValue = [{ value, valid: config.validator() }];\n cache.set(arg, cachedValue);\n break;\n case \"valid\":\n if (cachedValue) {\n cachedValue.push({ value, valid: config.validator() });\n } else {\n cachedValue = [{ value, valid: config.validator() }];\n cache.set(arg, cachedValue);\n }\n }\n}\n\nclass CacheConfigurator<SideChannel = void> {\n _active: boolean = true;\n _never: boolean = false;\n _forever: boolean = false;\n _invalidate: boolean = false;\n\n _configured: boolean = false;\n\n _pairs: [\n cachedValue: unknown,\n handler: (data: SideChannel) => Handler<unknown>,\n ][] = [];\n\n _data: SideChannel;\n\n constructor(data: SideChannel) {\n this._data = data;\n }\n\n simple() {\n return makeSimpleConfigurator(this);\n }\n\n mode() {\n if (this._never) return \"never\";\n if (this._forever) return \"forever\";\n if (this._invalidate) return \"invalidate\";\n return \"valid\";\n }\n\n forever() {\n if (!this._active) {\n throw new Error(\"Cannot change caching after evaluation has completed.\");\n }\n if (this._never) {\n throw new Error(\"Caching has already been configured with .never()\");\n }\n this._forever = true;\n this._configured = true;\n }\n\n never() {\n if (!this._active) {\n throw new Error(\"Cannot change caching after evaluation has completed.\");\n }\n if (this._forever) {\n throw new Error(\"Caching has already been configured with .forever()\");\n }\n this._never = true;\n this._configured = true;\n }\n\n using<T>(handler: (data: SideChannel) => T): T {\n if (!this._active) {\n throw new Error(\"Cannot change caching after evaluation has completed.\");\n }\n if (this._never || this._forever) {\n throw new Error(\n \"Caching has already been configured with .never or .forever()\",\n );\n }\n this._configured = true;\n\n const key = handler(this._data);\n\n const fn = maybeAsync(\n handler,\n `You appear to be using an async cache handler, but Babel has been called synchronously`,\n );\n\n if (isThenable(key)) {\n // @ts-expect-error todo(flow->ts): improve function return type annotation\n return key.then((key: unknown) => {\n this._pairs.push([key, fn]);\n return key;\n });\n }\n\n this._pairs.push([key, fn]);\n return key;\n }\n\n invalidate<T>(handler: (data: SideChannel) => T): T {\n this._invalidate = true;\n return this.using(handler);\n }\n\n validator(): (data: SideChannel) => Handler<boolean> {\n const pairs = this._pairs;\n return function* (data: SideChannel) {\n for (const [key, fn] of pairs) {\n if (key !== (yield* fn(data))) return false;\n }\n return true;\n };\n }\n\n deactivate() {\n this._active = false;\n }\n\n configured() {\n return this._configured;\n }\n}\n\nfunction makeSimpleConfigurator(\n cache: CacheConfigurator<any>,\n): SimpleCacheConfigurator {\n function cacheFn(val: any) {\n if (typeof val === \"boolean\") {\n if (val) cache.forever();\n else cache.never();\n return;\n }\n\n return cache.using(() => assertSimpleType(val()));\n }\n cacheFn.forever = () => cache.forever();\n cacheFn.never = () => cache.never();\n cacheFn.using = (cb: () => SimpleType) =>\n cache.using(() => assertSimpleType(cb()));\n cacheFn.invalidate = (cb: () => SimpleType) =>\n cache.invalidate(() => assertSimpleType(cb()));\n\n return cacheFn as any;\n}\n\n// Types are limited here so that in the future these values can be used\n// as part of Babel's caching logic.\nexport type SimpleType =\n | string\n | boolean\n | number\n | null\n | undefined\n | Promise<SimpleType>;\nexport function assertSimpleType(value: unknown): SimpleType {\n if (isThenable(value)) {\n throw new Error(\n `You appear to be using an async cache handler, ` +\n `which your current version of Babel does not support. ` +\n `We may add support for this in the future, ` +\n `but if you're on the most recent version of @babel/core and still ` +\n `seeing this error, then you'll need to synchronously handle your caching logic.`,\n );\n }\n\n if (\n value != null &&\n typeof value !== \"string\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"number\"\n ) {\n throw new Error(\n \"Cache keys must be either string, boolean, number, null, or undefined.\",\n );\n }\n return value;\n}\n\nclass Lock<T> {\n released: boolean = false;\n promise: Promise<T>;\n _resolve: undefined | ((value: T) => void);\n\n constructor() {\n this.promise = new Promise(resolve => {\n this._resolve = resolve;\n });\n }\n\n release(value: T) {\n this.released = true;\n this._resolve!(value);\n }\n}\n"],"names":["runGenerator","gensync","item","isAsync","sync","errback","cb","maybeAsync","fn","message","args","result","apply","isThenable","Error","async","Promise","resolve","withKind","forwardAsync","action","g","kind","adapted","onFirstPause","name","arity","firstPause","completed","err","value","waitFor","x","val","then","mergeOptions","target","source","k","Object","keys","parserOpts","targetObj","mergeDefaultFields","undefined","isIterableIterator","next","Symbol","iterator","synchronize","gen","genTrue","makeWeakCache","handler","makeCachedFunction","WeakMap","makeWeakCacheSync","makeStrongCache","Map","makeStrongCacheSync","CallCache","callCacheSync","callCacheAsync","futureCache","cachedFunction","arg","data","asyncContext","callCache","cached","getCachedValueOrWait","valid","cache","CacheConfigurator","handlerResult","finishLock","setupAsyncLocks","updateFunctionCache","delete","release","getCachedValue","cachedValue","get","promise","config","Lock","configured","forever","deactivate","mode","set","validator","push","_active","_never","_forever","_invalidate","_configured","_pairs","_data","constructor","simple","makeSimpleConfigurator","never","using","key","invalidate","pairs","cacheFn","assertSimpleType","released","_resolve"],"mappings":";;AAIA,MAAMA,YAIL,GAAGC,OAAO,CAAC,WAAWC,IAAkB,EAAgB;AACvD,EAAA,OAAO,OAAOA,IAAI,CAAA;AACpB,CAAC,CAAC,CAAA;AAIWC,MAAAA,OAAO,GAAGF,OAAO,CAAC;EAC7BG,IAAI,EAAEA,MAAM,KAAK;AACjBC,EAAAA,OAAO,EAAEC,EAAE,IAAIA,EAAE,CAAC,IAAI,EAAE,IAAI,CAAA;AAC9B,CAAC,EAAC;AAOK,SAASC,UAAUA,CACxBC,EAA6B,EAC7BC,OAAe,EACQ;AACvB,EAAA,OAAOR,OAAO,CAAC;IACbG,IAAIA,CAAC,GAAGM,IAAI,EAAE;MACZ,MAAMC,MAAM,GAAGH,EAAE,CAACI,KAAK,CAAC,IAAI,EAAEF,IAAI,CAAC,CAAA;MACnC,IAAIG,UAAU,CAACF,MAAM,CAAC,EAAE,MAAM,IAAIG,KAAK,CAACL,OAAO,CAAC,CAAA;AAChD,MAAA,OAAOE,MAAM,CAAA;KACd;IACDI,KAAKA,CAAC,GAAGL,IAAI,EAAE;AACb,MAAA,OAAOM,OAAO,CAACC,OAAO,CAACT,EAAE,CAACI,KAAK,CAAC,IAAI,EAAEF,IAAI,CAAC,CAAC,CAAA;AAC9C,KAAA;AACF,GAAC,CAAC,CAAA;AACJ,CAAA;AAEA,MAAMQ,QAAQ,GAAGjB,OAAO,CAAC;AACvBG,EAAAA,IAAI,EAAEE,EAAE,IAAIA,EAAE,CAAC,MAAM,CAAC;AACtBS,EAAAA,KAAK,EAAE,MAAMT,EAAE,IAAIA,EAAE,CAAC,OAAO,CAAA;AAC/B,CAAC,CAAuE,CAAA;AAgBjE,SAASa,YAAYA,CAC1BC,MAA0C,EAC1Cd,EAEyB,EACR;AACjB,EAAA,MAAMe,CAAC,GAAGpB,OAAO,CAACmB,MAAM,CAAC,CAAA;EACz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Ac;AAC3D,EAAA,IAAIjB,UAAU,CAACiB,KAAK,CAAC,EAAE;AACrB,IAAA,MAAM,IAAIhB,KAAK,CACb,CAAA,+CAAA,CAAiD,GAC/C,CAAA,sDAAA,CAAwD,GACxD,CAAA,2CAAA,CAA6C,GAC7C,CAAA,kEAAA,CAAoE,GACpE,CAAA,+EAAA,CACJ,CAAC,CAAA;AACH,GAAA;AAEA,EAAA,IACEgB,KAAK,IAAI,IAAI,IACb,OAAOA,KAAK,KAAK,QAAQ,IACzB,OAAOA,KAAK,KAAK,SAAS,IAC1B,OAAOA,KAAK,KAAK,QAAQ,EACzB;AACA,IAAA,MAAM,IAAIhB,KAAK,CACb,wEACF,CAAC,CAAA;AACH,GAAA;AACA,EAAA,OAAOgB,KAAK,CAAA;AACd,CAAA;AAEA,MAAMuD,IAAI,CAAI;AACZyB,EAAAA,QAAQ,GAAY,KAAK,CAAA;EACzB3B,OAAO,CAAA;EACP4B,QAAQ,CAAA;AAERX,EAAAA,WAAWA,GAAG;AACZ,IAAA,IAAI,CAACjB,OAAO,GAAG,IAAInE,OAAO,CAACC,OAAO,IAAI;MACpC,IAAI,CAAC8F,QAAQ,GAAG9F,OAAO,CAAA;AACzB,KAAC,CAAC,CAAA;AACJ,GAAA;EAEA8D,OAAOA,CAACjD,KAAQ,EAAE;IAChB,IAAI,CAACgF,QAAQ,GAAG,IAAI,CAAA;AACpB,IAAA,IAAI,CAACC,QAAQ,CAAEjF,KAAK,CAAC,CAAA;AACvB,GAAA;AACF;;;;"} |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| import gensync from 'gensync'; | ||
| import { l as loadConfig, r as run } from './index-BVo3ANpX.js'; | ||
| import fs from 'node:fs'; | ||
| const readFile = gensync({ | ||
| sync: fs.readFileSync, | ||
| errback: fs.readFile | ||
| }); | ||
| const stat = gensync({ | ||
| sync: fs.statSync, | ||
| errback: fs.stat | ||
| }); | ||
| const transformFileRunner = gensync(function* (filename, opts) { | ||
| const options = { | ||
| ...opts, | ||
| filename | ||
| }; | ||
| const config = yield* loadConfig(options); | ||
| if (config === null) return null; | ||
| const code = yield* readFile(filename, "utf8"); | ||
| return yield* run(config, code); | ||
| }); | ||
| function transformFile(...args) { | ||
| transformFileRunner.errback(...args); | ||
| } | ||
| function transformFileSync(...args) { | ||
| return transformFileRunner.sync(...args); | ||
| } | ||
| function transformFileAsync(...args) { | ||
| return transformFileRunner.async(...args); | ||
| } | ||
| export { transformFile as a, transformFileAsync as b, readFile as r, stat as s, transformFileSync as t }; | ||
| //# sourceMappingURL=transform-file-Cc6w1JPg.js.map |
| {"version":3,"file":"transform-file-Cc6w1JPg.js","sources":["../src/gensync-utils/fs.ts","../src/transform-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport gensync from \"gensync\";\n\nexport const readFile = gensync<[filepath: string, encoding: \"utf8\"], string>({\n sync: fs.readFileSync,\n errback: fs.readFile,\n});\n\nexport const stat = gensync({\n sync: fs.statSync,\n errback: fs.stat,\n});\n","import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config/index.ts\";\nimport type { InputOptions, ResolvedConfig } from \"./config/index.ts\";\nimport { run } from \"./transformation/index.ts\";\nimport type { FileResult, FileResultCallback } from \"./transformation/index.ts\";\nimport * as fs from \"./gensync-utils/fs.ts\";\n\ntype transformFileBrowserType = typeof import(\"./transform-file-browser\");\ntype transformFileType = typeof import(\"./transform-file\");\n\n// Kind of gross, but essentially asserting that the exports of this module are the same as the\n// exports of transform-file-browser, since this file may be replaced at bundle time with\n// transform-file-browser.\n// eslint-disable-next-line @typescript-eslint/no-unused-expressions\n({}) as any as transformFileBrowserType as transformFileType;\n\nconst transformFileRunner = gensync(function* (\n filename: string,\n opts?: InputOptions,\n): Handler<FileResult | null> {\n const options = { ...opts, filename };\n\n const config: ResolvedConfig | null = yield* loadConfig(options);\n if (config === null) return null;\n\n const code = yield* fs.readFile(filename, \"utf8\");\n return yield* run(config, code);\n});\n\n// @ts-expect-error TS doesn't detect that this signature is compatible\nexport function transformFile(\n filename: string,\n callback: FileResultCallback,\n): void;\nexport function transformFile(\n filename: string,\n opts: InputOptions | undefined | null,\n callback: FileResultCallback,\n): void;\nexport function transformFile(\n ...args: Parameters<typeof transformFileRunner.errback>\n) {\n transformFileRunner.errback(...args);\n}\n\nexport function transformFileSync(\n ...args: Parameters<typeof transformFileRunner.sync>\n) {\n return transformFileRunner.sync(...args);\n}\nexport function transformFileAsync(\n ...args: Parameters<typeof transformFileRunner.async>\n) {\n return transformFileRunner.async(...args);\n}\n"],"names":["readFile","gensync","sync","fs","readFileSync","errback","stat","statSync","transformFileRunner","filename","opts","options","config","loadConfig","code","run","transformFile","args","transformFileSync","transformFileAsync","async"],"mappings":";;;;AAGaA,MAAAA,QAAQ,GAAGC,OAAO,CAA+C;EAC5EC,IAAI,EAAEC,EAAE,CAACC,YAAY;EACrBC,OAAO,EAAEF,EAAE,CAACH,QAAAA;AACd,CAAC,EAAC;AAEWM,MAAAA,IAAI,GAAGL,OAAO,CAAC;EAC1BC,IAAI,EAAEC,EAAE,CAACI,QAAQ;EACjBF,OAAO,EAAEF,EAAE,CAACG,IAAAA;AACd,CAAC;;ACMD,MAAME,mBAAmB,GAAGP,OAAO,CAAC,WAClCQ,QAAgB,EAChBC,IAAmB,EACS;AAC5B,EAAA,MAAMC,OAAO,GAAG;AAAE,IAAA,GAAGD,IAAI;AAAED,IAAAA,QAAAA;GAAU,CAAA;AAErC,EAAA,MAAMG,MAA6B,GAAG,OAAOC,UAAU,CAACF,OAAO,CAAC,CAAA;AAChE,EAAA,IAAIC,MAAM,KAAK,IAAI,EAAE,OAAO,IAAI,CAAA;EAEhC,MAAME,IAAI,GAAG,OAAOX,QAAW,CAACM,QAAQ,EAAE,MAAM,CAAC,CAAA;AACjD,EAAA,OAAO,OAAOM,GAAG,CAACH,MAAM,EAAEE,IAAI,CAAC,CAAA;AACjC,CAAC,CAAC,CAAA;AAYK,SAASE,aAAaA,CAC3B,GAAGC,IAAoD,EACvD;AACAT,EAAAA,mBAAmB,CAACH,OAAO,CAAC,GAAGY,IAAI,CAAC,CAAA;AACtC,CAAA;AAEO,SAASC,iBAAiBA,CAC/B,GAAGD,IAAiD,EACpD;AACA,EAAA,OAAOT,mBAAmB,CAACN,IAAI,CAAC,GAAGe,IAAI,CAAC,CAAA;AAC1C,CAAA;AACO,SAASE,kBAAkBA,CAChC,GAAGF,IAAkD,EACrD;AACA,EAAA,OAAOT,mBAAmB,CAACY,KAAK,CAAC,GAAGH,IAAI,CAAC,CAAA;AAC3C;;;;"} |
| { | ||
| "compilerOptions": { | ||
| "strictNullChecks": true, | ||
| "strictPropertyInitialization": true | ||
| } | ||
| } |
+2
-243
@@ -1,244 +0,3 @@ | ||
| import gensync from "gensync"; | ||
| import { maybeAsync, isAsync, onFirstPause, waitFor, isThenable } from "../gensync-utils/async.js"; | ||
| import { isIterableIterator } from "./util.js"; | ||
| const synchronize = gen => { | ||
| return gensync(gen).sync; | ||
| }; | ||
| function* genTrue() { | ||
| return true; | ||
| } | ||
| export function makeWeakCache(handler) { | ||
| return makeCachedFunction(WeakMap, handler); | ||
| } | ||
| export function makeWeakCacheSync(handler) { | ||
| return synchronize(makeWeakCache(handler)); | ||
| } | ||
| export function makeStrongCache(handler) { | ||
| return makeCachedFunction(Map, handler); | ||
| } | ||
| export function makeStrongCacheSync(handler) { | ||
| return synchronize(makeStrongCache(handler)); | ||
| } | ||
| function makeCachedFunction(CallCache, handler) { | ||
| const callCacheSync = new CallCache(); | ||
| const callCacheAsync = new CallCache(); | ||
| const futureCache = new CallCache(); | ||
| return function* cachedFunction(arg, data) { | ||
| const asyncContext = yield* isAsync(); | ||
| const callCache = asyncContext ? callCacheAsync : callCacheSync; | ||
| const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data); | ||
| if (cached.valid) return cached.value; | ||
| const cache = new CacheConfigurator(data); | ||
| const handlerResult = handler(arg, cache); | ||
| let finishLock; | ||
| let value; | ||
| if (isIterableIterator(handlerResult)) { | ||
| value = yield* onFirstPause(handlerResult, () => { | ||
| finishLock = setupAsyncLocks(cache, futureCache, arg); | ||
| }); | ||
| } else { | ||
| value = handlerResult; | ||
| } | ||
| updateFunctionCache(callCache, cache, arg, value); | ||
| if (finishLock) { | ||
| futureCache.delete(arg); | ||
| finishLock.release(value); | ||
| } | ||
| return value; | ||
| }; | ||
| } | ||
| function* getCachedValue(cache, arg, data) { | ||
| const cachedValue = cache.get(arg); | ||
| if (cachedValue) { | ||
| for (const { | ||
| value, | ||
| valid | ||
| } of cachedValue) { | ||
| if (yield* valid(data)) return { | ||
| valid: true, | ||
| value | ||
| }; | ||
| } | ||
| } | ||
| return { | ||
| valid: false, | ||
| value: null | ||
| }; | ||
| } | ||
| function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) { | ||
| const cached = yield* getCachedValue(callCache, arg, data); | ||
| if (cached.valid) { | ||
| return cached; | ||
| } | ||
| if (asyncContext) { | ||
| const cached = yield* getCachedValue(futureCache, arg, data); | ||
| if (cached.valid) { | ||
| const value = yield* waitFor(cached.value.promise); | ||
| return { | ||
| valid: true, | ||
| value | ||
| }; | ||
| } | ||
| } | ||
| return { | ||
| valid: false, | ||
| value: null | ||
| }; | ||
| } | ||
| function setupAsyncLocks(config, futureCache, arg) { | ||
| const finishLock = new Lock(); | ||
| updateFunctionCache(futureCache, config, arg, finishLock); | ||
| return finishLock; | ||
| } | ||
| function updateFunctionCache(cache, config, arg, value) { | ||
| if (!config.configured()) config.forever(); | ||
| let cachedValue = cache.get(arg); | ||
| config.deactivate(); | ||
| switch (config.mode()) { | ||
| case "forever": | ||
| cachedValue = [{ | ||
| value, | ||
| valid: genTrue | ||
| }]; | ||
| cache.set(arg, cachedValue); | ||
| break; | ||
| case "invalidate": | ||
| cachedValue = [{ | ||
| value, | ||
| valid: config.validator() | ||
| }]; | ||
| cache.set(arg, cachedValue); | ||
| break; | ||
| case "valid": | ||
| if (cachedValue) { | ||
| cachedValue.push({ | ||
| value, | ||
| valid: config.validator() | ||
| }); | ||
| } else { | ||
| cachedValue = [{ | ||
| value, | ||
| valid: config.validator() | ||
| }]; | ||
| cache.set(arg, cachedValue); | ||
| } | ||
| } | ||
| } | ||
| class CacheConfigurator { | ||
| _active = true; | ||
| _never = false; | ||
| _forever = false; | ||
| _invalidate = false; | ||
| _configured = false; | ||
| _pairs = []; | ||
| _data; | ||
| constructor(data) { | ||
| this._data = data; | ||
| } | ||
| simple() { | ||
| return makeSimpleConfigurator(this); | ||
| } | ||
| mode() { | ||
| if (this._never) return "never"; | ||
| if (this._forever) return "forever"; | ||
| if (this._invalidate) return "invalidate"; | ||
| return "valid"; | ||
| } | ||
| forever() { | ||
| if (!this._active) { | ||
| throw new Error("Cannot change caching after evaluation has completed."); | ||
| } | ||
| if (this._never) { | ||
| throw new Error("Caching has already been configured with .never()"); | ||
| } | ||
| this._forever = true; | ||
| this._configured = true; | ||
| } | ||
| never() { | ||
| if (!this._active) { | ||
| throw new Error("Cannot change caching after evaluation has completed."); | ||
| } | ||
| if (this._forever) { | ||
| throw new Error("Caching has already been configured with .forever()"); | ||
| } | ||
| this._never = true; | ||
| this._configured = true; | ||
| } | ||
| using(handler) { | ||
| if (!this._active) { | ||
| throw new Error("Cannot change caching after evaluation has completed."); | ||
| } | ||
| if (this._never || this._forever) { | ||
| throw new Error("Caching has already been configured with .never or .forever()"); | ||
| } | ||
| this._configured = true; | ||
| const key = handler(this._data); | ||
| const fn = maybeAsync(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`); | ||
| if (isThenable(key)) { | ||
| return key.then(key => { | ||
| this._pairs.push([key, fn]); | ||
| return key; | ||
| }); | ||
| } | ||
| this._pairs.push([key, fn]); | ||
| return key; | ||
| } | ||
| invalidate(handler) { | ||
| this._invalidate = true; | ||
| return this.using(handler); | ||
| } | ||
| validator() { | ||
| const pairs = this._pairs; | ||
| return function* (data) { | ||
| for (const [key, fn] of pairs) { | ||
| if (key !== (yield* fn(data))) return false; | ||
| } | ||
| return true; | ||
| }; | ||
| } | ||
| deactivate() { | ||
| this._active = false; | ||
| } | ||
| configured() { | ||
| return this._configured; | ||
| } | ||
| } | ||
| function makeSimpleConfigurator(cache) { | ||
| function cacheFn(val) { | ||
| if (typeof val === "boolean") { | ||
| if (val) cache.forever();else cache.never(); | ||
| return; | ||
| } | ||
| return cache.using(() => assertSimpleType(val())); | ||
| } | ||
| cacheFn.forever = () => cache.forever(); | ||
| cacheFn.never = () => cache.never(); | ||
| cacheFn.using = cb => cache.using(() => assertSimpleType(cb())); | ||
| cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb())); | ||
| return cacheFn; | ||
| } | ||
| export function assertSimpleType(value) { | ||
| if (isThenable(value)) { | ||
| throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`); | ||
| } | ||
| if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") { | ||
| throw new Error("Cache keys must be either string, boolean, number, null, or undefined."); | ||
| } | ||
| return value; | ||
| } | ||
| class Lock { | ||
| released = false; | ||
| promise; | ||
| _resolve; | ||
| constructor() { | ||
| this.promise = new Promise(resolve => { | ||
| this._resolve = resolve; | ||
| }); | ||
| } | ||
| release(value) { | ||
| this.released = true; | ||
| this._resolve(value); | ||
| } | ||
| } | ||
| import 'gensync'; | ||
| export { d as assertSimpleType, m as makeStrongCache, c as makeStrongCacheSync, a as makeWeakCache, b as makeWeakCacheSync } from '../caching-2iA7hK9v.js'; | ||
| //# sourceMappingURL=caching.js.map |
@@ -1,5 +0,5 @@ | ||
| export function findConfigUpwards(rootDir) { | ||
| function findConfigUpwards(rootDir) { | ||
| return null; | ||
| } | ||
| export function* findPackageData(filepath) { | ||
| function* findPackageData(filepath) { | ||
| return { | ||
@@ -12,3 +12,3 @@ filepath, | ||
| } | ||
| export function* findRelativeConfig(pkgData, envName, caller) { | ||
| function* findRelativeConfig(pkgData, envName, caller) { | ||
| return { | ||
@@ -19,25 +19,26 @@ config: null, | ||
| } | ||
| export function* findRootConfig(dirname, envName, caller) { | ||
| function* findRootConfig(dirname, envName, caller) { | ||
| return null; | ||
| } | ||
| export function* loadConfig(name, dirname, envName, caller) { | ||
| function* loadConfig(name, dirname, envName, caller) { | ||
| throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`); | ||
| } | ||
| export function* resolveShowConfigPath(dirname) { | ||
| function* resolveShowConfigPath(dirname) { | ||
| return null; | ||
| } | ||
| export const ROOT_CONFIG_FILENAMES = []; | ||
| export function resolvePlugin(name, dirname) { | ||
| const ROOT_CONFIG_FILENAMES = []; | ||
| function resolvePlugin(name, dirname) { | ||
| return null; | ||
| } | ||
| export function resolvePreset(name, dirname) { | ||
| function resolvePreset(name, dirname) { | ||
| return null; | ||
| } | ||
| export function loadPlugin(name, dirname) { | ||
| function loadPlugin(name, dirname) { | ||
| throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`); | ||
| } | ||
| export function loadPreset(name, dirname) { | ||
| function loadPreset(name, dirname) { | ||
| throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`); | ||
| } | ||
| export { ROOT_CONFIG_FILENAMES, findConfigUpwards, findPackageData, findRelativeConfig, findRootConfig, loadConfig, loadPlugin, loadPreset, resolvePlugin, resolvePreset, resolveShowConfigPath }; | ||
| //# sourceMappingURL=index-browser.js.map |
@@ -1,6 +0,609 @@ | ||
| ({}); | ||
| export { findPackageData } from "./package.js"; | ||
| export { findConfigUpwards, findRelativeConfig, findRootConfig, loadConfig, resolveShowConfigPath, ROOT_CONFIG_FILENAMES } from "./configuration.js"; | ||
| export { loadPlugin, loadPreset, resolvePlugin, resolvePreset } from "./plugins.js"; | ||
| import path from 'node:path'; | ||
| import { m as makeStrongCache, i as isAsync, w as waitFor, a as makeWeakCache, b as makeWeakCacheSync } from '../../caching-2iA7hK9v.js'; | ||
| import { r as readFile, t as transformFileSync, s as stat } from '../../transform-file-Cc6w1JPg.js'; | ||
| import fs, { existsSync } from 'node:fs'; | ||
| import { C as ConfigError, m as makeConfigAPI, p as pathToPattern } from '../../index-BVo3ANpX.js'; | ||
| import { createDebug } from 'obug'; | ||
| import json5 from 'json5'; | ||
| import gensync from 'gensync'; | ||
| import { pathToFileURL, fileURLToPath } from 'node:url'; | ||
| import { createRequire } from 'node:module'; | ||
| import { endHiddenCallStack } from '../../errors/rewrite-stack-trace.js'; | ||
| import { resolve } from 'import-meta-resolve'; | ||
| import '@babel/helpers'; | ||
| import '@babel/traverse'; | ||
| import '@babel/code-frame'; | ||
| import '@babel/types'; | ||
| import 'semver'; | ||
| import '@babel/generator'; | ||
| import '@babel/template'; | ||
| import '#config/files'; | ||
| import '@babel/parser'; | ||
| import 'convert-source-map'; | ||
| import '@jridgewell/remapping'; | ||
| import '#transform-file'; | ||
| import '../resolve-targets.js'; | ||
| import '@babel/helper-compilation-targets'; | ||
| import '#config/resolve-targets'; | ||
| function makeStaticFileCache(fn) { | ||
| return makeStrongCache(function* (filepath, cache) { | ||
| const cached = cache.invalidate(() => fileMtime(filepath)); | ||
| if (cached === null) { | ||
| return null; | ||
| } | ||
| return fn(filepath, yield* readFile(filepath, "utf8")); | ||
| }); | ||
| } | ||
| function fileMtime(filepath) { | ||
| if (!fs.existsSync(filepath)) return null; | ||
| try { | ||
| return +fs.statSync(filepath).mtime; | ||
| } catch (e) { | ||
| if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; | ||
| } | ||
| return null; | ||
| } | ||
| const PACKAGE_FILENAME = "package.json"; | ||
| const readConfigPackage = makeStaticFileCache((filepath, content) => { | ||
| let options; | ||
| try { | ||
| options = JSON.parse(content); | ||
| } catch (err) { | ||
| throw new ConfigError(`Error while parsing JSON - ${err.message}`, filepath); | ||
| } | ||
| if (!options) throw new Error(`${filepath}: No config detected`); | ||
| if (typeof options !== "object") { | ||
| throw new ConfigError(`Config returned typeof ${typeof options}`, filepath); | ||
| } | ||
| if (Array.isArray(options)) { | ||
| throw new ConfigError(`Expected config object but found array`, filepath); | ||
| } | ||
| return { | ||
| filepath, | ||
| dirname: path.dirname(filepath), | ||
| options | ||
| }; | ||
| }); | ||
| function* findPackageData(filepath) { | ||
| let pkg = null; | ||
| const directories = []; | ||
| let isPackage = true; | ||
| let dirname = path.dirname(filepath); | ||
| while (!pkg && path.basename(dirname) !== "node_modules") { | ||
| directories.push(dirname); | ||
| pkg = yield* readConfigPackage(path.join(dirname, PACKAGE_FILENAME)); | ||
| const nextLoc = path.dirname(dirname); | ||
| if (dirname === nextLoc) { | ||
| isPackage = false; | ||
| break; | ||
| } | ||
| dirname = nextLoc; | ||
| } | ||
| return { | ||
| filepath, | ||
| directories, | ||
| pkg, | ||
| isPackage | ||
| }; | ||
| } | ||
| const debug$2 = createDebug("babel:config:loading:files:module-types"); | ||
| const require$2 = createRequire(import.meta.url); | ||
| const LOADING_CJS_FILES = new Set(); | ||
| function loadCjsDefault(filepath) { | ||
| if (LOADING_CJS_FILES.has(filepath)) { | ||
| debug$2("Auto-ignoring usage of config %o.", filepath); | ||
| return {}; | ||
| } | ||
| let module; | ||
| try { | ||
| LOADING_CJS_FILES.add(filepath); | ||
| module = endHiddenCallStack(require$2)(filepath); | ||
| } finally { | ||
| LOADING_CJS_FILES.delete(filepath); | ||
| } | ||
| return module != null && (module.__esModule || module[Symbol.toStringTag] === "Module") ? module.default : module; | ||
| } | ||
| const loadMjsFromPath = endHiddenCallStack(async function loadMjsFromPath(filepath) { | ||
| const url = pathToFileURL(filepath).toString() + "?import"; | ||
| return await import(url); | ||
| }); | ||
| const tsNotSupportedError = ext => `\ | ||
| You are using a ${ext} config file, but Babel only supports transpiling .cts configs. Either: | ||
| - Use a .cts config file | ||
| - Update to Node.js 23.6.0, which has native TypeScript support | ||
| - Install tsx to transpile ${ext} files on the fly\ | ||
| `; | ||
| const SUPPORTED_EXTENSIONS = { | ||
| ".js": "unknown", | ||
| ".mjs": "esm", | ||
| ".cjs": "cjs", | ||
| ".ts": "unknown", | ||
| ".mts": "esm", | ||
| ".cts": "cjs" | ||
| }; | ||
| const asyncModules = new Set(); | ||
| function* loadCodeDefault(filepath, loader, esmError, tlaError) { | ||
| let async; | ||
| const ext = path.extname(filepath); | ||
| const isTS = ext === ".ts" || ext === ".cts" || ext === ".mts"; | ||
| const type = SUPPORTED_EXTENSIONS[Object.hasOwn(SUPPORTED_EXTENSIONS, ext) ? ext : ".js"]; | ||
| const pattern = `${loader} ${type}`; | ||
| switch (pattern) { | ||
| case "require cjs": | ||
| case "auto cjs": | ||
| if (isTS) { | ||
| return ensureTsSupport(filepath, ext, () => loadCjsDefault(filepath)); | ||
| } else { | ||
| return loadCjsDefault(filepath); | ||
| } | ||
| case "auto unknown": | ||
| case "require unknown": | ||
| case "require esm": | ||
| try { | ||
| if (isTS) { | ||
| return ensureTsSupport(filepath, ext, () => loadCjsDefault(filepath)); | ||
| } else { | ||
| return loadCjsDefault(filepath); | ||
| } | ||
| } catch (e) { | ||
| if (e.code === "ERR_REQUIRE_ASYNC_MODULE" || e.code === "ERR_REQUIRE_CYCLE_MODULE" && asyncModules.has(filepath)) { | ||
| asyncModules.add(filepath); | ||
| if (!(async ??= yield* isAsync())) { | ||
| throw new ConfigError(tlaError, filepath); | ||
| } | ||
| } else if (e.code === "ERR_REQUIRE_ESM") ; else { | ||
| throw e; | ||
| } | ||
| } | ||
| case "auto esm": | ||
| if (async ??= yield* isAsync()) { | ||
| const promise = isTS ? ensureTsSupport(filepath, ext, () => loadMjsFromPath(filepath)) : loadMjsFromPath(filepath); | ||
| return (yield* waitFor(promise)).default; | ||
| } | ||
| if (isTS) { | ||
| throw new ConfigError(tsNotSupportedError(ext), filepath); | ||
| } else { | ||
| throw new ConfigError(esmError, filepath); | ||
| } | ||
| default: | ||
| throw new Error("Internal Babel error: unreachable code."); | ||
| } | ||
| } | ||
| function ensureTsSupport(filepath, ext, callback) { | ||
| if (process.features.typescript || require$2.extensions[".ts"] || require$2.extensions[".cts"] || require$2.extensions[".mts"]) { | ||
| return callback(); | ||
| } | ||
| if (ext !== ".cts") { | ||
| throw new ConfigError(tsNotSupportedError(ext), filepath); | ||
| } | ||
| const opts = { | ||
| babelrc: false, | ||
| configFile: false, | ||
| sourceType: "unambiguous", | ||
| sourceMaps: "inline", | ||
| sourceFileName: path.basename(filepath), | ||
| presets: [[getTSPreset(filepath), { | ||
| onlyRemoveTypeImports: true, | ||
| optimizeConstEnums: true | ||
| }]] | ||
| }; | ||
| let handler = function (m, filename) { | ||
| if (handler && filename.endsWith(".cts")) { | ||
| return m._compile(transformFileSync(filename, { | ||
| ...opts, | ||
| filename | ||
| }).code, filename); | ||
| } | ||
| return require$2.extensions[".js"](m, filename); | ||
| }; | ||
| require$2.extensions[ext] = handler; | ||
| try { | ||
| return callback(); | ||
| } finally { | ||
| if (require$2.extensions[ext] === handler) delete require$2.extensions[ext]; | ||
| handler = undefined; | ||
| } | ||
| } | ||
| function getTSPreset(filepath) { | ||
| try { | ||
| return require$2("@babel/preset-typescript"); | ||
| } catch (error) { | ||
| if (error.code !== "MODULE_NOT_FOUND") throw error; | ||
| const message = "You appear to be using a .cts file as Babel configuration, but the `@babel/preset-typescript` package was not found: please install it!"; | ||
| throw new ConfigError(message, filepath); | ||
| } | ||
| } | ||
| const require$1 = createRequire(import.meta.url); | ||
| const debug$1 = createDebug("babel:config:loading:files:configuration"); | ||
| const ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json", "babel.config.cts", "babel.config.ts", "babel.config.mts"]; | ||
| const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json", ".babelrc.cts"]; | ||
| const BABELIGNORE_FILENAME = ".babelignore"; | ||
| const runConfig = makeWeakCache(function* runConfig(options, cache) { | ||
| yield* []; | ||
| return { | ||
| options: endHiddenCallStack(options)(makeConfigAPI(cache)), | ||
| cacheNeedsConfiguration: !cache.configured() | ||
| }; | ||
| }); | ||
| function* readConfigCode(filepath, data) { | ||
| if (!fs.existsSync(filepath)) return null; | ||
| let options = yield* loadCodeDefault(filepath, (yield* isAsync()) ? "auto" : "require", "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously " + "or when using the Node.js `--experimental-require-module` flag.", "You appear to be using a configuration file that contains top-level " + "await, which is only supported when running Babel asynchronously."); | ||
| let cacheNeedsConfiguration = false; | ||
| if (typeof options === "function") { | ||
| ({ | ||
| options, | ||
| cacheNeedsConfiguration | ||
| } = yield* runConfig(options, data)); | ||
| } | ||
| if (!options || typeof options !== "object" || Array.isArray(options)) { | ||
| throw new ConfigError(`Configuration should be an exported JavaScript object.`, filepath); | ||
| } | ||
| if (typeof options.then === "function") { | ||
| options.catch?.(() => {}); | ||
| throw new ConfigError(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`, filepath); | ||
| } | ||
| if (cacheNeedsConfiguration) throwConfigError(filepath); | ||
| return buildConfigFileObject(options, filepath); | ||
| } | ||
| const cfboaf = new WeakMap(); | ||
| function buildConfigFileObject(options, filepath) { | ||
| let configFilesByFilepath = cfboaf.get(options); | ||
| if (!configFilesByFilepath) { | ||
| cfboaf.set(options, configFilesByFilepath = new Map()); | ||
| } | ||
| let configFile = configFilesByFilepath.get(filepath); | ||
| if (!configFile) { | ||
| configFile = { | ||
| filepath, | ||
| dirname: path.dirname(filepath), | ||
| options | ||
| }; | ||
| configFilesByFilepath.set(filepath, configFile); | ||
| } | ||
| return configFile; | ||
| } | ||
| const packageToBabelConfig = makeWeakCacheSync(file => { | ||
| const babel = file.options.babel; | ||
| if (babel === undefined) return null; | ||
| if (typeof babel !== "object" || Array.isArray(babel) || babel === null) { | ||
| throw new ConfigError(`.babel property must be an object`, file.filepath); | ||
| } | ||
| return { | ||
| filepath: file.filepath, | ||
| dirname: file.dirname, | ||
| options: babel | ||
| }; | ||
| }); | ||
| const readConfigJSON5 = makeStaticFileCache((filepath, content) => { | ||
| let options; | ||
| try { | ||
| options = json5.parse(content); | ||
| } catch (err) { | ||
| throw new ConfigError(`Error while parsing config - ${err.message}`, filepath); | ||
| } | ||
| if (!options) throw new ConfigError(`No config detected`, filepath); | ||
| if (typeof options !== "object") { | ||
| throw new ConfigError(`Config returned typeof ${typeof options}`, filepath); | ||
| } | ||
| if (Array.isArray(options)) { | ||
| throw new ConfigError(`Expected config object but found array`, filepath); | ||
| } | ||
| delete options.$schema; | ||
| return { | ||
| filepath, | ||
| dirname: path.dirname(filepath), | ||
| options | ||
| }; | ||
| }); | ||
| const readIgnoreConfig = makeStaticFileCache((filepath, content) => { | ||
| const ignoreDir = path.dirname(filepath); | ||
| const ignorePatterns = content.split("\n").map(line => line.replace(/^#.*$/, "").trim()).filter(Boolean); | ||
| for (const pattern of ignorePatterns) { | ||
| if (pattern.startsWith("!")) { | ||
| throw new ConfigError(`Negation of file paths is not supported.`, filepath); | ||
| } | ||
| } | ||
| return { | ||
| filepath, | ||
| dirname: path.dirname(filepath), | ||
| ignore: ignorePatterns.map(pattern => pathToPattern(pattern, ignoreDir)) | ||
| }; | ||
| }); | ||
| function findConfigUpwards(rootDir) { | ||
| let dirname = rootDir; | ||
| for (;;) { | ||
| for (const filename of ROOT_CONFIG_FILENAMES) { | ||
| if (fs.existsSync(path.join(dirname, filename))) { | ||
| return dirname; | ||
| } | ||
| } | ||
| const nextDir = path.dirname(dirname); | ||
| if (dirname === nextDir) break; | ||
| dirname = nextDir; | ||
| } | ||
| return null; | ||
| } | ||
| function* findRelativeConfig(packageData, envName, caller) { | ||
| let config = null; | ||
| let ignore = null; | ||
| const dirname = path.dirname(packageData.filepath); | ||
| for (const loc of packageData.directories) { | ||
| if (!config) { | ||
| config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, packageData.pkg?.dirname === loc ? packageToBabelConfig(packageData.pkg) : null); | ||
| } | ||
| if (!ignore) { | ||
| const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME); | ||
| ignore = yield* readIgnoreConfig(ignoreLoc); | ||
| if (ignore) { | ||
| debug$1("Found ignore %o from %o.", ignore.filepath, dirname); | ||
| } | ||
| } | ||
| } | ||
| return { | ||
| config, | ||
| ignore | ||
| }; | ||
| } | ||
| function findRootConfig(dirname, envName, caller) { | ||
| return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller); | ||
| } | ||
| function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) { | ||
| const configs = yield* gensync.all(names.map(filename => readConfig(path.join(dirname, filename), envName, caller))); | ||
| const config = configs.reduce((previousConfig, config) => { | ||
| if (config && previousConfig) { | ||
| throw new ConfigError(`Multiple configuration files found. Please remove one:\n` + ` - ${path.basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`); | ||
| } | ||
| return config || previousConfig; | ||
| }, previousConfig); | ||
| if (config) { | ||
| debug$1("Found configuration %o from %o.", config.filepath, dirname); | ||
| } | ||
| return config; | ||
| } | ||
| function* loadConfig(name, dirname, envName, caller) { | ||
| const filepath = require$1.resolve(name, { | ||
| paths: [dirname] | ||
| }); | ||
| const conf = yield* readConfig(filepath, envName, caller); | ||
| if (!conf) { | ||
| throw new ConfigError(`Config file contains no configuration data`, filepath); | ||
| } | ||
| debug$1("Loaded config %o from %o.", name, dirname); | ||
| return conf; | ||
| } | ||
| function readConfig(filepath, envName, caller) { | ||
| const ext = path.extname(filepath); | ||
| switch (ext) { | ||
| case ".js": | ||
| case ".cjs": | ||
| case ".mjs": | ||
| case ".ts": | ||
| case ".cts": | ||
| case ".mts": | ||
| return readConfigCode(filepath, { | ||
| envName, | ||
| caller | ||
| }); | ||
| default: | ||
| return readConfigJSON5(filepath); | ||
| } | ||
| } | ||
| function* resolveShowConfigPath(dirname) { | ||
| const targetPath = process.env.BABEL_SHOW_CONFIG_FOR; | ||
| if (targetPath != null) { | ||
| const absolutePath = path.resolve(dirname, targetPath); | ||
| const stats = yield* stat(absolutePath); | ||
| if (!stats.isFile()) { | ||
| throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`); | ||
| } | ||
| return absolutePath; | ||
| } | ||
| return null; | ||
| } | ||
| function throwConfigError(filepath) { | ||
| throw new ConfigError(`\ | ||
| Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured | ||
| for various types of caching, using the first param of their handler functions: | ||
| module.exports = function(api) { | ||
| // The API exposes the following: | ||
| // Cache the returned value forever and don't call this function again. | ||
| api.cache(true); | ||
| // Don't cache at all. Not recommended because it will be very slow. | ||
| api.cache(false); | ||
| // Cached based on the value of some function. If this function returns a value different from | ||
| // a previously-encountered value, the plugins will re-evaluate. | ||
| var env = api.cache(() => process.env.NODE_ENV); | ||
| // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for | ||
| // any possible NODE_ENV value that might come up during plugin execution. | ||
| var isProd = api.cache(() => process.env.NODE_ENV === "production"); | ||
| // .cache(fn) will perform a linear search though instances to find the matching plugin based | ||
| // based on previous instantiated plugins. If you want to recreate the plugin and discard the | ||
| // previous instance whenever something changes, you may use: | ||
| var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production"); | ||
| // Note, we also expose the following more-verbose versions of the above examples: | ||
| api.cache.forever(); // api.cache(true) | ||
| api.cache.never(); // api.cache(false) | ||
| api.cache.using(fn); // api.cache(fn) | ||
| // Return the value that will be cached. | ||
| return { }; | ||
| };`, filepath); | ||
| } | ||
| const require = createRequire(import.meta.url); | ||
| const debug = createDebug("babel:config:loading:files:plugins"); | ||
| const EXACT_RE = /^module:/; | ||
| const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/; | ||
| const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/; | ||
| const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/; | ||
| const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/; | ||
| const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/; | ||
| const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/; | ||
| const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/; | ||
| const resolvePlugin = resolveStandardizedName.bind(null, "plugin"); | ||
| const resolvePreset = resolveStandardizedName.bind(null, "preset"); | ||
| function* loadPlugin(name, dirname) { | ||
| const { | ||
| filepath, | ||
| loader | ||
| } = resolvePlugin(name, dirname, yield* isAsync()); | ||
| const value = yield* requireModule("plugin", loader, filepath); | ||
| debug("Loaded plugin %o from %o.", name, dirname); | ||
| return { | ||
| filepath, | ||
| value | ||
| }; | ||
| } | ||
| function* loadPreset(name, dirname) { | ||
| const { | ||
| filepath, | ||
| loader | ||
| } = resolvePreset(name, dirname, yield* isAsync()); | ||
| const value = yield* requireModule("preset", loader, filepath); | ||
| debug("Loaded preset %o from %o.", name, dirname); | ||
| return { | ||
| filepath, | ||
| value | ||
| }; | ||
| } | ||
| function standardizeName(type, name) { | ||
| if (path.isAbsolute(name)) return name; | ||
| const isPreset = type === "preset"; | ||
| return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, ""); | ||
| } | ||
| function* resolveAlternativesHelper(type, name) { | ||
| const standardizedName = standardizeName(type, name); | ||
| const { | ||
| error, | ||
| value | ||
| } = yield standardizedName; | ||
| if (!error) return value; | ||
| if (error.code !== "MODULE_NOT_FOUND") throw error; | ||
| if (standardizedName !== name && !(yield name).error) { | ||
| error.message += `\n- If you want to resolve "${name}", use "module:${name}"`; | ||
| } | ||
| if (!(yield standardizeName(type, "@babel/" + name)).error) { | ||
| error.message += `\n- Did you mean "@babel/${name}"?`; | ||
| } | ||
| const oppositeType = type === "preset" ? "plugin" : "preset"; | ||
| if (!(yield standardizeName(oppositeType, name)).error) { | ||
| error.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`; | ||
| } | ||
| if (type === "plugin") { | ||
| const transformName = standardizedName.replace("-proposal-", "-transform-"); | ||
| if (transformName !== standardizedName && !(yield transformName).error) { | ||
| error.message += `\n- Did you mean "${transformName}"?`; | ||
| } | ||
| } | ||
| error.message += `\n | ||
| Make sure that all the Babel plugins and presets you are using | ||
| are defined as dependencies or devDependencies in your package.json | ||
| file. It's possible that the missing plugin is loaded by a preset | ||
| you are using that forgot to add the plugin to its dependencies: you | ||
| can workaround this problem by explicitly adding the missing package | ||
| to your top-level package.json. | ||
| `; | ||
| throw error; | ||
| } | ||
| function tryRequireResolve(id, dirname) { | ||
| try { | ||
| if (dirname) { | ||
| return { | ||
| error: null, | ||
| value: require.resolve(id, { | ||
| paths: [dirname] | ||
| }) | ||
| }; | ||
| } else { | ||
| return { | ||
| error: null, | ||
| value: require.resolve(id) | ||
| }; | ||
| } | ||
| } catch (error) { | ||
| return { | ||
| error, | ||
| value: null | ||
| }; | ||
| } | ||
| } | ||
| function tryImportMetaResolve(id, options) { | ||
| try { | ||
| return { | ||
| error: null, | ||
| value: resolve(id, options) | ||
| }; | ||
| } catch (error) { | ||
| return { | ||
| error, | ||
| value: null | ||
| }; | ||
| } | ||
| } | ||
| function resolveStandardizedNameForRequire(type, name, dirname) { | ||
| const it = resolveAlternativesHelper(type, name); | ||
| let res = it.next(); | ||
| while (!res.done) { | ||
| res = it.next(tryRequireResolve(res.value, dirname)); | ||
| } | ||
| return { | ||
| loader: "require", | ||
| filepath: res.value | ||
| }; | ||
| } | ||
| function resolveStandardizedNameForImport(type, name, dirname) { | ||
| const parentUrl = pathToFileURL(path.join(dirname, "./babel-virtual-resolve-base.js")).href; | ||
| const it = resolveAlternativesHelper(type, name); | ||
| let res = it.next(); | ||
| while (!res.done) { | ||
| res = it.next(tryImportMetaResolve(res.value, parentUrl)); | ||
| } | ||
| return { | ||
| loader: "auto", | ||
| filepath: fileURLToPath(res.value) | ||
| }; | ||
| } | ||
| function resolveStandardizedName(type, name, dirname, allowAsync) { | ||
| if (!allowAsync) { | ||
| return resolveStandardizedNameForRequire(type, name, dirname); | ||
| } | ||
| try { | ||
| const resolved = resolveStandardizedNameForImport(type, name, dirname); | ||
| if (!existsSync(resolved.filepath)) { | ||
| throw Object.assign(new Error(`Could not resolve "${name}" in file ${dirname}.`), { | ||
| type: "MODULE_NOT_FOUND" | ||
| }); | ||
| } | ||
| return resolved; | ||
| } catch (e) { | ||
| try { | ||
| return resolveStandardizedNameForRequire(type, name, dirname); | ||
| } catch (e2) { | ||
| if (e.type === "MODULE_NOT_FOUND") throw e; | ||
| if (e2.type === "MODULE_NOT_FOUND") throw e2; | ||
| throw e; | ||
| } | ||
| } | ||
| } | ||
| function* requireModule(type, loader, name) { | ||
| try { | ||
| return yield* loadCodeDefault(name, loader, `You appear to be using a native ECMAScript module ${type}, ` + "which is only supported when running Babel asynchronously " + "or when using the Node.js `--experimental-require-module` flag.", `You appear to be using a ${type} that contains top-level await, ` + "which is only supported when running Babel asynchronously."); | ||
| } catch (err) { | ||
| err.message = `[BABEL]: ${err.message} (While processing: ${name})`; | ||
| throw err; | ||
| } | ||
| } | ||
| export { ROOT_CONFIG_FILENAMES, findConfigUpwards, findPackageData, findRelativeConfig, findRootConfig, loadConfig, loadPlugin, loadPreset, resolvePlugin, resolvePreset, resolveShowConfigPath }; | ||
| //# sourceMappingURL=index.js.map |
@@ -1,6 +0,7 @@ | ||
| import getTargets from "@babel/helper-compilation-targets"; | ||
| export function resolveBrowserslistConfigFile(browserslistConfigFile, configFilePath) { | ||
| import getTargets from '@babel/helper-compilation-targets'; | ||
| function resolveBrowserslistConfigFile(browserslistConfigFile, configFilePath) { | ||
| return undefined; | ||
| } | ||
| export function resolveTargets(options, root) { | ||
| function resolveTargets(options, root) { | ||
| const optTargets = options.targets; | ||
@@ -21,2 +22,3 @@ let targets; | ||
| export { resolveBrowserslistConfigFile, resolveTargets }; | ||
| //# sourceMappingURL=resolve-targets-browser.js.map |
@@ -1,8 +0,8 @@ | ||
| ({}); | ||
| import path from "node:path"; | ||
| import getTargets from "@babel/helper-compilation-targets"; | ||
| export function resolveBrowserslistConfigFile(browserslistConfigFile, configFileDir) { | ||
| import path from 'node:path'; | ||
| import getTargets from '@babel/helper-compilation-targets'; | ||
| function resolveBrowserslistConfigFile(browserslistConfigFile, configFileDir) { | ||
| return path.resolve(configFileDir, browserslistConfigFile); | ||
| } | ||
| export function resolveTargets(options, root) { | ||
| function resolveTargets(options, root) { | ||
| const optTargets = options.targets; | ||
@@ -35,2 +35,3 @@ let targets; | ||
| export { resolveBrowserslistConfigFile, resolveTargets }; | ||
| //# sourceMappingURL=resolve-targets.js.map |
@@ -21,3 +21,3 @@ const ErrorToString = Function.call.bind(Error.prototype.toString); | ||
| } | ||
| export function injectVirtualStackFrame(error, filename) { | ||
| function injectVirtualStackFrame(error, filename) { | ||
| if (!SUPPORTED) return; | ||
@@ -29,3 +29,3 @@ let frames = virtualFrames.get(error); | ||
| } | ||
| export function expectedError(error) { | ||
| function expectedError(error) { | ||
| if (!SUPPORTED) return; | ||
@@ -35,3 +35,3 @@ expectedErrors.add(error); | ||
| } | ||
| export function beginHiddenCallStack(fn) { | ||
| function beginHiddenCallStack(fn) { | ||
| if (!SUPPORTED) return fn; | ||
@@ -45,3 +45,3 @@ return Object.defineProperty(function (...args) { | ||
| } | ||
| export function endHiddenCallStack(fn) { | ||
| function endHiddenCallStack(fn) { | ||
| if (!SUPPORTED) return fn; | ||
@@ -91,2 +91,3 @@ return Object.defineProperty(function (...args) { | ||
| export { beginHiddenCallStack, endHiddenCallStack, expectedError, injectVirtualStackFrame }; | ||
| //# sourceMappingURL=rewrite-stack-trace.js.map |
+31
-31
@@ -76,3 +76,3 @@ import * as _babel_traverse from '@babel/traverse'; | ||
| }; | ||
| type SimpleType = string | boolean | number | null | void | Promise<SimpleType>; | ||
| type SimpleType = string | boolean | number | null | undefined | Promise<SimpleType>; | ||
@@ -299,3 +299,3 @@ declare const __marker: unique symbol; | ||
| presets: ConfigItem<PresetAPI>[]; | ||
| plugins: ConfigItem<PluginAPI$1>[]; | ||
| plugins: ConfigItem<PluginAPI>[]; | ||
| }; | ||
@@ -319,3 +319,3 @@ type ResolvedOptions = Omit<NormalizedOptions, "presets" | "plugins" | "passPerPreset"> & { | ||
| dirname: string; | ||
| caller: CallerMetadata; | ||
| caller: CallerMetadata | undefined; | ||
| envName: string; | ||
@@ -326,4 +326,4 @@ }) => unknown); | ||
| }; | ||
| type PluginTarget = string | MaybeDefaultProperty<(api: PluginAPI$1, options?: object, dirname?: string) => PluginObject>; | ||
| type PluginItem = ConfigItem<PluginAPI$1> | PluginTarget | [PluginTarget, object] | [PluginTarget, object, string]; | ||
| type PluginTarget = string | MaybeDefaultProperty<(api: PluginAPI, options?: object, dirname?: string) => PluginObject>; | ||
| type PluginItem = ConfigItem<PluginAPI> | PluginTarget | [PluginTarget, object] | [PluginTarget, object, string]; | ||
| type PresetTarget = string | MaybeDefaultProperty<(api: PresetAPI, options?: object, dirname?: string) => PresetObject>; | ||
@@ -372,19 +372,19 @@ type PresetItem = ConfigItem<PresetAPI> | PresetTarget | [PresetTarget, object] | [PresetTarget, object, string]; | ||
| declare const loadPartialConfigRunner: gensync.Gensync<[opts?: InputOptions], PartialConfig, unknown>; | ||
| declare function loadPartialConfigAsync(...args: Parameters<typeof loadPartialConfigRunner.async>): Promise<PartialConfig>; | ||
| declare function loadPartialConfigSync(...args: Parameters<typeof loadPartialConfigRunner.sync>): PartialConfig; | ||
| declare const loadPartialConfigRunner: gensync.Gensync<[opts?: InputOptions | undefined], PartialConfig | null, unknown>; | ||
| declare function loadPartialConfigAsync(...args: Parameters<typeof loadPartialConfigRunner.async>): Promise<PartialConfig | null>; | ||
| declare function loadPartialConfigSync(...args: Parameters<typeof loadPartialConfigRunner.sync>): PartialConfig | null; | ||
| declare function loadPartialConfig(opts: Parameters<typeof loadPartialConfig$1>[0], callback?: (err: Error, val: PartialConfig | null) => void): void; | ||
| declare function loadOptionsImpl(opts: InputOptions): Handler<ResolvedOptions | null>; | ||
| declare const loadOptionsRunner: gensync.Gensync<[opts: InputOptions], ResolvedOptions, unknown>; | ||
| declare function loadOptionsAsync(...args: Parameters<typeof loadOptionsRunner.async>): Promise<ResolvedOptions>; | ||
| declare function loadOptionsSync(...args: Parameters<typeof loadOptionsRunner.sync>): ResolvedOptions; | ||
| declare function loadOptionsImpl(opts: InputOptions | null | undefined): Handler<ResolvedOptions | null>; | ||
| declare const loadOptionsRunner: gensync.Gensync<[opts: InputOptions | null | undefined], ResolvedOptions | null, unknown>; | ||
| declare function loadOptionsAsync(...args: Parameters<typeof loadOptionsRunner.async>): Promise<ResolvedOptions | null>; | ||
| declare function loadOptionsSync(...args: Parameters<typeof loadOptionsRunner.sync>): ResolvedOptions | null; | ||
| declare function loadOptions(opts: Parameters<typeof loadOptionsImpl>[0], callback?: (err: Error, val: ResolvedOptions | null) => void): void; | ||
| declare const createConfigItemRunner: gensync.Gensync<[value: string | ConfigItem<PresetAPI> | ((api: PresetAPI, options?: object, dirname?: string) => PresetObject) | { | ||
| default: (api: PresetAPI, options?: object, dirname?: string) => PresetObject; | ||
| } | [PresetTarget, object] | [PresetTarget, object, string] | ConfigItem<PluginAPI$1> | ((api: PluginAPI$1, options?: object, dirname?: string) => PluginObject) | { | ||
| default: (api: PluginAPI$1, options?: object, dirname?: string) => PluginObject; | ||
| } | [PluginTarget, object] | [PluginTarget, object, string], { | ||
| } | [PresetTarget, object] | [PresetTarget, object, string] | ConfigItem<PluginAPI> | ((api: PluginAPI, options?: object, dirname?: string) => PluginObject) | { | ||
| default: (api: PluginAPI, options?: object, dirname?: string) => PluginObject; | ||
| } | [PluginTarget, object] | [PluginTarget, object, string], ({ | ||
| dirname?: string; | ||
| type?: "preset" | "plugin"; | ||
| }?], ConfigItem<unknown>, unknown>; | ||
| } | undefined)?], ConfigItem<unknown>, unknown>; | ||
| declare function createConfigItemAsync(...args: Parameters<typeof createConfigItemRunner.async>): Promise<ConfigItem<unknown>>; | ||
@@ -409,3 +409,3 @@ declare function createConfigItemSync(...args: Parameters<typeof createConfigItemRunner.sync>): ConfigItem<unknown>; | ||
| code: string; | ||
| inputMap: SourceMapConverter; | ||
| inputMap: SourceMapConverter | null; | ||
| hub: HubInterface & { | ||
@@ -449,3 +449,3 @@ file: File; | ||
| /** The absolute path of the file being compiled. */ | ||
| filename: string | void; | ||
| filename: string | undefined; | ||
| /** | ||
@@ -455,3 +455,3 @@ * Is Babel executed in async mode or not. | ||
| isAsync: boolean; | ||
| constructor(file: File, key: string | null, options: Options | undefined, isAsync: boolean); | ||
| constructor(file: File, key: string | null | undefined, options: Options | undefined, isAsync: boolean); | ||
| set(key: unknown, val: unknown): void; | ||
@@ -486,12 +486,12 @@ get(key: unknown): any; | ||
| }; | ||
| declare const transformRunner: gensync.Gensync<[code: string, opts?: InputOptions], FileResult, unknown>; | ||
| declare const transformRunner: gensync.Gensync<[code: string, opts?: InputOptions | null | undefined], FileResult | null, unknown>; | ||
| declare const transform: Transform; | ||
| declare function transformSync(...args: Parameters<typeof transformRunner.sync>): FileResult; | ||
| declare function transformAsync(...args: Parameters<typeof transformRunner.async>): Promise<FileResult>; | ||
| declare function transformSync(...args: Parameters<typeof transformRunner.sync>): FileResult | null; | ||
| declare function transformAsync(...args: Parameters<typeof transformRunner.async>): Promise<FileResult | null>; | ||
| declare const transformFileRunner: gensync.Gensync<[filename: string, opts?: InputOptions], FileResult, unknown>; | ||
| declare const transformFileRunner: gensync.Gensync<[filename: string, opts?: InputOptions | undefined], FileResult | null, unknown>; | ||
| declare function transformFile(filename: string, callback: FileResultCallback): void; | ||
| declare function transformFile(filename: string, opts: InputOptions | undefined | null, callback: FileResultCallback): void; | ||
| declare function transformFileSync(...args: Parameters<typeof transformFileRunner.sync>): FileResult; | ||
| declare function transformFileAsync(...args: Parameters<typeof transformFileRunner.async>): Promise<FileResult>; | ||
| declare function transformFileSync(...args: Parameters<typeof transformFileRunner.sync>): FileResult | null; | ||
| declare function transformFileAsync(...args: Parameters<typeof transformFileRunner.async>): Promise<FileResult | null>; | ||
@@ -503,6 +503,6 @@ type AstRoot = t.File | t.Program; | ||
| }; | ||
| declare const transformFromAstRunner: gensync.Gensync<[ast: AstRoot, code: string, opts: InputOptions], FileResult, unknown>; | ||
| declare const transformFromAstRunner: gensync.Gensync<[ast: AstRoot, code: string, opts: InputOptions | null | undefined], FileResult | null, unknown>; | ||
| declare const transformFromAst: TransformFromAst; | ||
| declare function transformFromAstSync(...args: Parameters<typeof transformFromAstRunner.sync>): FileResult; | ||
| declare function transformFromAstAsync(...args: Parameters<typeof transformFromAstRunner.async>): Promise<FileResult>; | ||
| declare function transformFromAstSync(...args: Parameters<typeof transformFromAstRunner.sync>): FileResult | null; | ||
| declare function transformFromAstAsync(...args: Parameters<typeof transformFromAstRunner.async>): Promise<FileResult | null>; | ||
@@ -517,6 +517,6 @@ type FileParseCallback = { | ||
| }; | ||
| declare const parseRunner: gensync.Gensync<[code: string, opts: InputOptions], ParseResult, unknown>; | ||
| declare const parseRunner: gensync.Gensync<[code: string, opts: InputOptions | null | undefined], ParseResult | null, unknown>; | ||
| declare const parse: Parse; | ||
| declare function parseSync(...args: Parameters<typeof parseRunner.sync>): ParseResult; | ||
| declare function parseAsync(...args: Parameters<typeof parseRunner.async>): Promise<ParseResult>; | ||
| declare function parseSync(...args: Parameters<typeof parseRunner.sync>): ParseResult | null; | ||
| declare function parseAsync(...args: Parameters<typeof parseRunner.async>): Promise<ParseResult | null>; | ||
@@ -523,0 +523,0 @@ declare const version: string; |
+23
-21
@@ -1,22 +0,24 @@ | ||
| export const version = "8.0.0-beta.4"; | ||
| export { default as File } from "./transformation/file/file.js"; | ||
| export { default as buildExternalHelpers } from "./tools/build-external-helpers.js"; | ||
| import * as resolvers from "./config/files/index.js"; | ||
| export const resolvePlugin = (name, dirname) => resolvers.resolvePlugin(name, dirname, false).filepath; | ||
| export const resolvePreset = (name, dirname) => resolvers.resolvePreset(name, dirname, false).filepath; | ||
| export { getEnv } from "./config/helpers/environment.js"; | ||
| export * as types from "@babel/types"; | ||
| export { tokTypes } from "@babel/parser"; | ||
| export { default as traverse } from "@babel/traverse"; | ||
| export { default as template } from "@babel/template"; | ||
| export { createConfigItem, createConfigItemAsync, createConfigItemSync } from "./config/index.js"; | ||
| export { loadOptions, loadOptionsAsync, loadPartialConfig, loadPartialConfigAsync, loadPartialConfigSync } from "./config/index.js"; | ||
| import { loadOptionsSync } from "./config/index.js"; | ||
| export { loadOptionsSync }; | ||
| export { transform, transformAsync, transformSync } from "./transform.js"; | ||
| export { transformFile, transformFileAsync, transformFileSync } from "./transform-file.js"; | ||
| export { transformFromAst, transformFromAstAsync, transformFromAstSync } from "./transform-ast.js"; | ||
| export { parse, parseAsync, parseSync } from "./parse.js"; | ||
| export const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]); | ||
| export { D as DEFAULT_EXTENSIONS, F as File, d as buildExternalHelpers, e as createConfigItem, f as createConfigItemAsync, h as createConfigItemSync, g as getEnv, i as loadOptions, j as loadOptionsAsync, c as loadOptionsSync, k as loadPartialConfig, n as loadPartialConfigAsync, o as loadPartialConfigSync, y as parse, z as parseAsync, A as parseSync, a as resolvePlugin, b as resolvePreset, t as transform, q as transformAsync, u as transformFromAst, w as transformFromAstAsync, x as transformFromAstSync, s as transformSync, v as version } from './index-BVo3ANpX.js'; | ||
| import '#config/files'; | ||
| import * as _t from '@babel/types'; | ||
| export { _t as types }; | ||
| export { tokTypes } from '@babel/parser'; | ||
| export { default as traverse } from '@babel/traverse'; | ||
| export { default as template } from '@babel/template'; | ||
| export { transformFile, transformFileAsync, transformFileSync } from '#transform-file'; | ||
| import '@babel/helpers'; | ||
| import '@babel/code-frame'; | ||
| import 'semver'; | ||
| import '@babel/generator'; | ||
| import 'gensync'; | ||
| import './caching-2iA7hK9v.js'; | ||
| import 'node:path'; | ||
| import 'node:fs'; | ||
| import 'obug'; | ||
| import 'convert-source-map'; | ||
| import '@jridgewell/remapping'; | ||
| import './errors/rewrite-stack-trace.js'; | ||
| import './config/resolve-targets.js'; | ||
| import '@babel/helper-compilation-targets'; | ||
| import '#config/resolve-targets'; | ||
| //# sourceMappingURL=index.js.map |
@@ -1,2 +0,2 @@ | ||
| export const transformFile = function transformFile(filename, opts, callback) { | ||
| const transformFile = function transformFile(filename, opts, callback) { | ||
| if (typeof opts === "function") { | ||
@@ -7,9 +7,10 @@ callback = opts; | ||
| }; | ||
| export function transformFileSync() { | ||
| function transformFileSync() { | ||
| throw new Error("Transforming files is not supported in browsers"); | ||
| } | ||
| export function transformFileAsync() { | ||
| function transformFileAsync() { | ||
| return Promise.reject(new Error("Transforming files is not supported in browsers")); | ||
| } | ||
| export { transformFile, transformFileAsync, transformFileSync }; | ||
| //# sourceMappingURL=transform-file-browser.js.map |
+23
-25
@@ -1,26 +0,24 @@ | ||
| import gensync from "gensync"; | ||
| import loadConfig from "./config/index.js"; | ||
| import { run } from "./transformation/index.js"; | ||
| import * as fs from "./gensync-utils/fs.js"; | ||
| ({}); | ||
| const transformFileRunner = gensync(function* (filename, opts) { | ||
| const options = { | ||
| ...opts, | ||
| filename | ||
| }; | ||
| const config = yield* loadConfig(options); | ||
| if (config === null) return null; | ||
| const code = yield* fs.readFile(filename, "utf8"); | ||
| return yield* run(config, code); | ||
| }); | ||
| export function transformFile(...args) { | ||
| transformFileRunner.errback(...args); | ||
| } | ||
| export function transformFileSync(...args) { | ||
| return transformFileRunner.sync(...args); | ||
| } | ||
| export function transformFileAsync(...args) { | ||
| return transformFileRunner.async(...args); | ||
| } | ||
| import 'gensync'; | ||
| import './index-BVo3ANpX.js'; | ||
| export { a as transformFile, b as transformFileAsync, t as transformFileSync } from './transform-file-Cc6w1JPg.js'; | ||
| import '@babel/helpers'; | ||
| import '@babel/traverse'; | ||
| import '@babel/code-frame'; | ||
| import '@babel/types'; | ||
| import 'semver'; | ||
| import '@babel/generator'; | ||
| import '@babel/template'; | ||
| import '#config/files'; | ||
| import '@babel/parser'; | ||
| import './caching-2iA7hK9v.js'; | ||
| import 'node:path'; | ||
| import 'node:fs'; | ||
| import 'obug'; | ||
| import 'convert-source-map'; | ||
| import '@jridgewell/remapping'; | ||
| import './errors/rewrite-stack-trace.js'; | ||
| import '#transform-file'; | ||
| import './config/resolve-targets.js'; | ||
| import '@babel/helper-compilation-targets'; | ||
| import '#config/resolve-targets'; | ||
| //# sourceMappingURL=transform-file.js.map |
+46
-23
| { | ||
| "name": "@babel/core", | ||
| "version": "8.0.0-beta.4", | ||
| "version": "8.0.0-rc.1", | ||
| "description": "Babel compiler core.", | ||
@@ -40,19 +40,11 @@ "main": "./lib/index.js", | ||
| }, | ||
| "browser": { | ||
| "./lib/config/files/index.js": "./lib/config/files/index-browser.js", | ||
| "./lib/config/resolve-targets.js": "./lib/config/resolve-targets-browser.js", | ||
| "./lib/transform-file.js": "./lib/transform-file-browser.js", | ||
| "./src/config/files/index.ts": "./src/config/files/index-browser.ts", | ||
| "./src/config/resolve-targets.ts": "./src/config/resolve-targets-browser.ts", | ||
| "./src/transform-file.ts": "./src/transform-file-browser.ts" | ||
| }, | ||
| "dependencies": { | ||
| "@babel/code-frame": "^8.0.0-beta.4", | ||
| "@babel/generator": "^8.0.0-beta.4", | ||
| "@babel/helper-compilation-targets": "^8.0.0-beta.4", | ||
| "@babel/helpers": "^8.0.0-beta.4", | ||
| "@babel/parser": "^8.0.0-beta.4", | ||
| "@babel/template": "^8.0.0-beta.4", | ||
| "@babel/traverse": "^8.0.0-beta.4", | ||
| "@babel/types": "^8.0.0-beta.4", | ||
| "@babel/code-frame": "^8.0.0-rc.1", | ||
| "@babel/generator": "^8.0.0-rc.1", | ||
| "@babel/helper-compilation-targets": "^8.0.0-rc.1", | ||
| "@babel/helpers": "^8.0.0-rc.1", | ||
| "@babel/parser": "^8.0.0-rc.1", | ||
| "@babel/template": "^8.0.0-rc.1", | ||
| "@babel/traverse": "^8.0.0-rc.1", | ||
| "@babel/types": "^8.0.0-rc.1", | ||
| "@jridgewell/remapping": "^2.3.5", | ||
@@ -68,8 +60,8 @@ "@types/gensync": "^1.0.0", | ||
| "devDependencies": { | ||
| "@babel/helper-transform-fixture-test-runner": "^8.0.0-beta.4", | ||
| "@babel/plugin-syntax-flow": "^8.0.0-beta.4", | ||
| "@babel/plugin-transform-flow-strip-types": "^8.0.0-beta.4", | ||
| "@babel/plugin-transform-modules-commonjs": "^8.0.0-beta.4", | ||
| "@babel/preset-env": "^8.0.0-beta.4", | ||
| "@babel/preset-typescript": "^8.0.0-beta.4", | ||
| "@babel/helper-transform-fixture-test-runner": "^8.0.0-rc.1", | ||
| "@babel/plugin-syntax-flow": "^8.0.0-rc.1", | ||
| "@babel/plugin-transform-flow-strip-types": "^8.0.0-rc.1", | ||
| "@babel/plugin-transform-modules-commonjs": "^8.0.0-rc.1", | ||
| "@babel/preset-env": "^8.0.0-rc.1", | ||
| "@babel/preset-typescript": "^8.0.0-rc.1", | ||
| "@jridgewell/trace-mapping": "^0.3.28", | ||
@@ -97,3 +89,34 @@ "@types/convert-source-map": "^2.0.0", | ||
| }, | ||
| "imports": { | ||
| "#config/files": { | ||
| "babel-src": { | ||
| "browser": "./src/config/files/index-browser.ts", | ||
| "default": "./src/config/files/index.ts" | ||
| }, | ||
| "types": "./lib/config/files/index.d.ts", | ||
| "browser": "./lib/config/files/index-browser.js", | ||
| "default": "./lib/config/files/index.js" | ||
| }, | ||
| "#config/resolve-targets": { | ||
| "babel-src": { | ||
| "browser": "./src/config/resolve-targets-browser.ts", | ||
| "default": "./src/config/resolve-targets.ts" | ||
| }, | ||
| "types": "./lib/config/resolve-targets.d.ts", | ||
| "browser": "./lib/config/resolve-targets-browser.js", | ||
| "default": "./lib/config/resolve-targets.js" | ||
| }, | ||
| "#transform-file": { | ||
| "babel-src": { | ||
| "browser": "./src/transform-file-browser.ts", | ||
| "default": "./src/transform-file.ts" | ||
| }, | ||
| "types": "./lib/transform-file.d.ts", | ||
| "browser": "./lib/transform-file-browser.js", | ||
| "default": "./lib/transform-file.js" | ||
| }, | ||
| "#hack-for-rollup-inlining-order-1": "./lib/errors/rewrite-stack-trace.js", | ||
| "#hack-for-rollup-inlining-order-2": "./lib/config/caching.js" | ||
| }, | ||
| "type": "module" | ||
| } |
| export {}; | ||
| //# sourceMappingURL=cache-contexts.js.map |
| {"version":3,"names":[],"sources":["../../src/config/cache-contexts.ts"],"sourcesContent":["import type { ConfigContext } from \"./config-chain.ts\";\nimport type {\n CallerMetadata,\n TargetsListOrObject,\n} from \"./validation/options.ts\";\n\nexport type { ConfigContext as FullConfig };\n\nexport type FullPreset = {\n targets: TargetsListOrObject;\n} & ConfigContext;\nexport type FullPlugin = {\n assumptions: Record<string, boolean>;\n} & FullPreset;\n\n// Context not including filename since it is used in places that cannot\n// process 'ignore'/'only' and other filename-based logic.\nexport type SimpleConfig = {\n envName: string;\n caller: CallerMetadata | undefined;\n};\nexport type SimplePreset = {\n targets: TargetsListOrObject;\n} & SimpleConfig;\nexport type SimplePlugin = {\n assumptions: Record<string, boolean>;\n} & SimplePreset;\n"],"mappings":"","ignoreList":[]} |
| import path from "node:path"; | ||
| import { createDebug } from "obug"; | ||
| import { validate } from "./validation/options.js"; | ||
| import pathPatternToRegex from "./pattern-to-regex.js"; | ||
| import { ConfigPrinter, ChainFormatter } from "./printer.js"; | ||
| import { endHiddenCallStack } from "../errors/rewrite-stack-trace.js"; | ||
| import ConfigError from "../errors/config-error.js"; | ||
| const debug = createDebug("babel:config:config-chain"); | ||
| import { findPackageData, findRelativeConfig, findRootConfig, loadConfig } from "./files/index.js"; | ||
| import { makeWeakCacheSync, makeStrongCacheSync } from "./caching.js"; | ||
| import { createCachedDescriptors, createUncachedDescriptors } from "./config-descriptors.js"; | ||
| export function* buildPresetChain(arg, context) { | ||
| const chain = yield* buildPresetChainWalker(arg, context); | ||
| if (!chain) return null; | ||
| return { | ||
| plugins: dedupDescriptors(chain.plugins), | ||
| presets: dedupDescriptors(chain.presets), | ||
| options: chain.options.map(o => createConfigChainOptions(o)), | ||
| files: new Set() | ||
| }; | ||
| } | ||
| export const buildPresetChainWalker = makeChainWalker({ | ||
| root: preset => loadPresetDescriptors(preset), | ||
| env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName), | ||
| overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index), | ||
| overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName), | ||
| createLogger: () => () => {} | ||
| }); | ||
| const loadPresetDescriptors = makeWeakCacheSync(preset => buildRootDescriptors(preset, preset.alias, createUncachedDescriptors)); | ||
| const loadPresetEnvDescriptors = makeWeakCacheSync(preset => makeStrongCacheSync(envName => buildEnvDescriptors(preset, preset.alias, createUncachedDescriptors, envName))); | ||
| const loadPresetOverridesDescriptors = makeWeakCacheSync(preset => makeStrongCacheSync(index => buildOverrideDescriptors(preset, preset.alias, createUncachedDescriptors, index))); | ||
| const loadPresetOverridesEnvDescriptors = makeWeakCacheSync(preset => makeStrongCacheSync(index => makeStrongCacheSync(envName => buildOverrideEnvDescriptors(preset, preset.alias, createUncachedDescriptors, index, envName)))); | ||
| export function* buildRootChain(opts, context) { | ||
| let configReport, babelRcReport; | ||
| const programmaticLogger = new ConfigPrinter(); | ||
| const programmaticChain = yield* loadProgrammaticChain({ | ||
| options: opts, | ||
| dirname: context.cwd | ||
| }, context, undefined, programmaticLogger); | ||
| if (!programmaticChain) return null; | ||
| const programmaticReport = yield* programmaticLogger.output(); | ||
| let configFile; | ||
| if (typeof opts.configFile === "string") { | ||
| configFile = yield* loadConfig(opts.configFile, context.cwd, context.envName, context.caller); | ||
| } else if (opts.configFile !== false) { | ||
| configFile = yield* findRootConfig(context.root, context.envName, context.caller); | ||
| } | ||
| let { | ||
| babelrc, | ||
| babelrcRoots | ||
| } = opts; | ||
| let babelrcRootsDirectory = context.cwd; | ||
| const configFileChain = emptyChain(); | ||
| const configFileLogger = new ConfigPrinter(); | ||
| if (configFile) { | ||
| const validatedFile = validateConfigFile(configFile); | ||
| const result = yield* loadFileChain(validatedFile, context, undefined, configFileLogger); | ||
| if (!result) return null; | ||
| configReport = yield* configFileLogger.output(); | ||
| if (babelrc === undefined) { | ||
| babelrc = validatedFile.options.babelrc; | ||
| } | ||
| if (babelrcRoots === undefined) { | ||
| babelrcRootsDirectory = validatedFile.dirname; | ||
| babelrcRoots = validatedFile.options.babelrcRoots; | ||
| } | ||
| mergeChain(configFileChain, result); | ||
| } | ||
| let ignoreFile, babelrcFile; | ||
| let isIgnored = false; | ||
| const fileChain = emptyChain(); | ||
| if ((babelrc === true || babelrc === undefined) && typeof context.filename === "string") { | ||
| const pkgData = yield* findPackageData(context.filename); | ||
| if (pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) { | ||
| ({ | ||
| ignore: ignoreFile, | ||
| config: babelrcFile | ||
| } = yield* findRelativeConfig(pkgData, context.envName, context.caller)); | ||
| if (ignoreFile) { | ||
| fileChain.files.add(ignoreFile.filepath); | ||
| } | ||
| if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) { | ||
| isIgnored = true; | ||
| } | ||
| if (babelrcFile && !isIgnored) { | ||
| const validatedFile = validateBabelrcFile(babelrcFile); | ||
| const babelrcLogger = new ConfigPrinter(); | ||
| const result = yield* loadFileChain(validatedFile, context, undefined, babelrcLogger); | ||
| if (!result) { | ||
| isIgnored = true; | ||
| } else { | ||
| babelRcReport = yield* babelrcLogger.output(); | ||
| mergeChain(fileChain, result); | ||
| } | ||
| } | ||
| if (babelrcFile && isIgnored) { | ||
| fileChain.files.add(babelrcFile.filepath); | ||
| } | ||
| } | ||
| } | ||
| if (context.showConfig) { | ||
| console.log(`Babel configs on "${context.filename}" (ascending priority):\n` + [configReport, babelRcReport, programmaticReport].filter(x => !!x).join("\n\n") + "\n-----End Babel configs-----"); | ||
| } | ||
| const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain); | ||
| return { | ||
| plugins: isIgnored ? [] : dedupDescriptors(chain.plugins), | ||
| presets: isIgnored ? [] : dedupDescriptors(chain.presets), | ||
| options: isIgnored ? [] : chain.options.map(o => createConfigChainOptions(o)), | ||
| fileHandling: isIgnored ? "ignored" : "transpile", | ||
| ignore: ignoreFile || undefined, | ||
| babelrc: babelrcFile || undefined, | ||
| config: configFile || undefined, | ||
| files: chain.files | ||
| }; | ||
| } | ||
| function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) { | ||
| if (typeof babelrcRoots === "boolean") return babelrcRoots; | ||
| const absoluteRoot = context.root; | ||
| if (babelrcRoots === undefined) { | ||
| return pkgData.directories.includes(absoluteRoot); | ||
| } | ||
| let babelrcPatterns = babelrcRoots; | ||
| if (!Array.isArray(babelrcPatterns)) { | ||
| babelrcPatterns = [babelrcPatterns]; | ||
| } | ||
| babelrcPatterns = babelrcPatterns.map(pat => { | ||
| return typeof pat === "string" ? path.resolve(babelrcRootsDirectory, pat) : pat; | ||
| }); | ||
| if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) { | ||
| return pkgData.directories.includes(absoluteRoot); | ||
| } | ||
| return babelrcPatterns.some(pat => { | ||
| if (typeof pat === "string") { | ||
| pat = pathPatternToRegex(pat, babelrcRootsDirectory); | ||
| } | ||
| return pkgData.directories.some(directory => { | ||
| return matchPattern(pat, babelrcRootsDirectory, directory, context); | ||
| }); | ||
| }); | ||
| } | ||
| const validateConfigFile = makeWeakCacheSync(file => ({ | ||
| filepath: file.filepath, | ||
| dirname: file.dirname, | ||
| options: validate("configfile", file.options, file.filepath) | ||
| })); | ||
| const validateBabelrcFile = makeWeakCacheSync(file => ({ | ||
| filepath: file.filepath, | ||
| dirname: file.dirname, | ||
| options: validate("babelrcfile", file.options, file.filepath) | ||
| })); | ||
| const validateExtendFile = makeWeakCacheSync(file => ({ | ||
| filepath: file.filepath, | ||
| dirname: file.dirname, | ||
| options: validate("extendsfile", file.options, file.filepath) | ||
| })); | ||
| const loadProgrammaticChain = makeChainWalker({ | ||
| root: input => buildRootDescriptors(input, "base", createCachedDescriptors), | ||
| env: (input, envName) => buildEnvDescriptors(input, "base", createCachedDescriptors, envName), | ||
| overrides: (input, index) => buildOverrideDescriptors(input, "base", createCachedDescriptors, index), | ||
| overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", createCachedDescriptors, index, envName), | ||
| createLogger: (input, context, baseLogger) => buildProgrammaticLogger(input, context, baseLogger) | ||
| }); | ||
| const loadFileChainWalker = makeChainWalker({ | ||
| root: file => loadFileDescriptors(file), | ||
| env: (file, envName) => loadFileEnvDescriptors(file)(envName), | ||
| overrides: (file, index) => loadFileOverridesDescriptors(file)(index), | ||
| overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName), | ||
| createLogger: (file, context, baseLogger) => buildFileLogger(file.filepath, context, baseLogger) | ||
| }); | ||
| function* loadFileChain(input, context, files, baseLogger) { | ||
| const chain = yield* loadFileChainWalker(input, context, files, baseLogger); | ||
| chain?.files.add(input.filepath); | ||
| return chain; | ||
| } | ||
| const loadFileDescriptors = makeWeakCacheSync(file => buildRootDescriptors(file, file.filepath, createUncachedDescriptors)); | ||
| const loadFileEnvDescriptors = makeWeakCacheSync(file => makeStrongCacheSync(envName => buildEnvDescriptors(file, file.filepath, createUncachedDescriptors, envName))); | ||
| const loadFileOverridesDescriptors = makeWeakCacheSync(file => makeStrongCacheSync(index => buildOverrideDescriptors(file, file.filepath, createUncachedDescriptors, index))); | ||
| const loadFileOverridesEnvDescriptors = makeWeakCacheSync(file => makeStrongCacheSync(index => makeStrongCacheSync(envName => buildOverrideEnvDescriptors(file, file.filepath, createUncachedDescriptors, index, envName)))); | ||
| function buildFileLogger(filepath, context, baseLogger) { | ||
| if (!baseLogger) { | ||
| return () => {}; | ||
| } | ||
| return baseLogger.configure(context.showConfig, ChainFormatter.Config, { | ||
| filepath | ||
| }); | ||
| } | ||
| function buildRootDescriptors({ | ||
| dirname, | ||
| options | ||
| }, alias, descriptors) { | ||
| return descriptors(dirname, options, alias); | ||
| } | ||
| function buildProgrammaticLogger(_, context, baseLogger) { | ||
| if (!baseLogger) { | ||
| return () => {}; | ||
| } | ||
| return baseLogger.configure(context.showConfig, ChainFormatter.Programmatic, { | ||
| callerName: context.caller?.name | ||
| }); | ||
| } | ||
| function buildEnvDescriptors({ | ||
| dirname, | ||
| options | ||
| }, alias, descriptors, envName) { | ||
| const opts = options.env?.[envName]; | ||
| return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null; | ||
| } | ||
| function buildOverrideDescriptors({ | ||
| dirname, | ||
| options | ||
| }, alias, descriptors, index) { | ||
| const opts = options.overrides?.[index]; | ||
| if (!opts) throw new Error("Assertion failure - missing override"); | ||
| return descriptors(dirname, opts, `${alias}.overrides[${index}]`); | ||
| } | ||
| function buildOverrideEnvDescriptors({ | ||
| dirname, | ||
| options | ||
| }, alias, descriptors, index, envName) { | ||
| const override = options.overrides?.[index]; | ||
| if (!override) throw new Error("Assertion failure - missing override"); | ||
| const opts = override.env?.[envName]; | ||
| return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null; | ||
| } | ||
| function makeChainWalker({ | ||
| root, | ||
| env, | ||
| overrides, | ||
| overridesEnv, | ||
| createLogger | ||
| }) { | ||
| return function* chainWalker(input, context, files = new Set(), baseLogger) { | ||
| const { | ||
| dirname | ||
| } = input; | ||
| const flattenedConfigs = []; | ||
| const rootOpts = root(input); | ||
| if (configIsApplicable(rootOpts, dirname, context, input.filepath)) { | ||
| flattenedConfigs.push({ | ||
| config: rootOpts, | ||
| envName: undefined, | ||
| index: undefined | ||
| }); | ||
| const envOpts = env(input, context.envName); | ||
| if (envOpts && configIsApplicable(envOpts, dirname, context, input.filepath)) { | ||
| flattenedConfigs.push({ | ||
| config: envOpts, | ||
| envName: context.envName, | ||
| index: undefined | ||
| }); | ||
| } | ||
| (rootOpts.options.overrides || []).forEach((_, index) => { | ||
| const overrideOps = overrides(input, index); | ||
| if (configIsApplicable(overrideOps, dirname, context, input.filepath)) { | ||
| flattenedConfigs.push({ | ||
| config: overrideOps, | ||
| index, | ||
| envName: undefined | ||
| }); | ||
| const overrideEnvOpts = overridesEnv(input, index, context.envName); | ||
| if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context, input.filepath)) { | ||
| flattenedConfigs.push({ | ||
| config: overrideEnvOpts, | ||
| index, | ||
| envName: context.envName | ||
| }); | ||
| } | ||
| } | ||
| }); | ||
| } | ||
| if (flattenedConfigs.some(({ | ||
| config: { | ||
| options: { | ||
| ignore, | ||
| only | ||
| } | ||
| } | ||
| }) => shouldIgnore(context, ignore, only, dirname))) { | ||
| return null; | ||
| } | ||
| const chain = emptyChain(); | ||
| const logger = createLogger(input, context, baseLogger); | ||
| for (const { | ||
| config, | ||
| index, | ||
| envName | ||
| } of flattenedConfigs) { | ||
| if (!(yield* mergeExtendsChain(chain, config.options, dirname, context, files, baseLogger))) { | ||
| return null; | ||
| } | ||
| logger(config, index, envName); | ||
| yield* mergeChainOpts(chain, config); | ||
| } | ||
| return chain; | ||
| }; | ||
| } | ||
| function* mergeExtendsChain(chain, opts, dirname, context, files, baseLogger) { | ||
| if (opts.extends === undefined) return true; | ||
| const file = yield* loadConfig(opts.extends, dirname, context.envName, context.caller); | ||
| if (files.has(file)) { | ||
| throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files, file => ` - ${file.filepath}`).join("\n")); | ||
| } | ||
| files.add(file); | ||
| const fileChain = yield* loadFileChain(validateExtendFile(file), context, files, baseLogger); | ||
| files.delete(file); | ||
| if (!fileChain) return false; | ||
| mergeChain(chain, fileChain); | ||
| return true; | ||
| } | ||
| function mergeChain(target, source) { | ||
| target.options.push(...source.options); | ||
| target.plugins.push(...source.plugins); | ||
| target.presets.push(...source.presets); | ||
| for (const file of source.files) { | ||
| target.files.add(file); | ||
| } | ||
| return target; | ||
| } | ||
| function* mergeChainOpts(target, { | ||
| options, | ||
| plugins, | ||
| presets | ||
| }) { | ||
| target.options.push(options); | ||
| target.plugins.push(...(yield* plugins())); | ||
| target.presets.push(...(yield* presets())); | ||
| return target; | ||
| } | ||
| function emptyChain() { | ||
| return { | ||
| options: [], | ||
| presets: [], | ||
| plugins: [], | ||
| files: new Set() | ||
| }; | ||
| } | ||
| function createConfigChainOptions(opts) { | ||
| const options = { | ||
| ...opts | ||
| }; | ||
| delete options.extends; | ||
| delete options.env; | ||
| delete options.overrides; | ||
| delete options.plugins; | ||
| delete options.presets; | ||
| delete options.passPerPreset; | ||
| delete options.ignore; | ||
| delete options.only; | ||
| delete options.test; | ||
| delete options.include; | ||
| delete options.exclude; | ||
| if (Object.hasOwn(options, "sourceMap")) { | ||
| options.sourceMaps = options.sourceMap; | ||
| delete options.sourceMap; | ||
| } | ||
| return options; | ||
| } | ||
| function dedupDescriptors(items) { | ||
| const map = new Map(); | ||
| const descriptors = []; | ||
| for (const item of items) { | ||
| if (typeof item.value === "function") { | ||
| const fnKey = item.value; | ||
| let nameMap = map.get(fnKey); | ||
| if (!nameMap) { | ||
| nameMap = new Map(); | ||
| map.set(fnKey, nameMap); | ||
| } | ||
| let desc = nameMap.get(item.name); | ||
| if (!desc) { | ||
| desc = { | ||
| value: item | ||
| }; | ||
| descriptors.push(desc); | ||
| if (!item.ownPass) nameMap.set(item.name, desc); | ||
| } else { | ||
| desc.value = item; | ||
| } | ||
| } else { | ||
| descriptors.push({ | ||
| value: item | ||
| }); | ||
| } | ||
| } | ||
| return descriptors.reduce((acc, desc) => { | ||
| acc.push(desc.value); | ||
| return acc; | ||
| }, []); | ||
| } | ||
| function configIsApplicable({ | ||
| options | ||
| }, dirname, context, configName) { | ||
| return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname, configName)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname, configName)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname, configName)); | ||
| } | ||
| function configFieldIsApplicable(context, test, dirname, configName) { | ||
| const patterns = Array.isArray(test) ? test : [test]; | ||
| return matchesPatterns(context, patterns, dirname, configName); | ||
| } | ||
| function ignoreListReplacer(_key, value) { | ||
| if (value instanceof RegExp) { | ||
| return String(value); | ||
| } | ||
| return value; | ||
| } | ||
| function shouldIgnore(context, ignore, only, dirname) { | ||
| if (ignore && matchesPatterns(context, ignore, dirname)) { | ||
| const message = `No config is applied to "${context.filename ?? "(unknown)"}" because it matches one of \`ignore: ${JSON.stringify(ignore, ignoreListReplacer)}\` from "${dirname}"`; | ||
| debug(message); | ||
| if (context.showConfig) { | ||
| console.log(message); | ||
| } | ||
| return true; | ||
| } | ||
| if (only && !matchesPatterns(context, only, dirname)) { | ||
| const message = `No config is applied to "${context.filename ?? "(unknown)"}" because it fails to match one of \`only: ${JSON.stringify(only, ignoreListReplacer)}\` from "${dirname}"`; | ||
| debug(message); | ||
| if (context.showConfig) { | ||
| console.log(message); | ||
| } | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
| function matchesPatterns(context, patterns, dirname, configName) { | ||
| return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context, configName)); | ||
| } | ||
| function matchPattern(pattern, dirname, pathToTest, context, configName) { | ||
| if (typeof pattern === "function") { | ||
| return !!endHiddenCallStack(pattern)(pathToTest, { | ||
| dirname, | ||
| envName: context.envName, | ||
| caller: context.caller | ||
| }); | ||
| } | ||
| if (typeof pathToTest !== "string") { | ||
| throw new ConfigError(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`, configName); | ||
| } | ||
| if (typeof pattern === "string") { | ||
| pattern = pathPatternToRegex(pattern, dirname); | ||
| } | ||
| return pattern.test(pathToTest); | ||
| } | ||
| //# sourceMappingURL=config-chain.js.map |
| {"version":3,"names":["path","createDebug","validate","pathPatternToRegex","ConfigPrinter","ChainFormatter","endHiddenCallStack","ConfigError","debug","findPackageData","findRelativeConfig","findRootConfig","loadConfig","makeWeakCacheSync","makeStrongCacheSync","createCachedDescriptors","createUncachedDescriptors","buildPresetChain","arg","context","chain","buildPresetChainWalker","plugins","dedupDescriptors","presets","options","map","o","createConfigChainOptions","files","Set","makeChainWalker","root","preset","loadPresetDescriptors","env","envName","loadPresetEnvDescriptors","overrides","index","loadPresetOverridesDescriptors","overridesEnv","loadPresetOverridesEnvDescriptors","createLogger","buildRootDescriptors","alias","buildEnvDescriptors","buildOverrideDescriptors","buildOverrideEnvDescriptors","buildRootChain","opts","configReport","babelRcReport","programmaticLogger","programmaticChain","loadProgrammaticChain","dirname","cwd","undefined","programmaticReport","output","configFile","caller","babelrc","babelrcRoots","babelrcRootsDirectory","configFileChain","emptyChain","configFileLogger","validatedFile","validateConfigFile","result","loadFileChain","mergeChain","ignoreFile","babelrcFile","isIgnored","fileChain","filename","pkgData","babelrcLoadEnabled","ignore","config","add","filepath","shouldIgnore","validateBabelrcFile","babelrcLogger","showConfig","console","log","filter","x","join","fileHandling","absoluteRoot","directories","includes","babelrcPatterns","Array","isArray","pat","resolve","length","some","directory","matchPattern","file","validateExtendFile","input","baseLogger","buildProgrammaticLogger","loadFileChainWalker","loadFileDescriptors","loadFileEnvDescriptors","loadFileOverridesDescriptors","loadFileOverridesEnvDescriptors","buildFileLogger","configure","Config","descriptors","_","Programmatic","callerName","name","Error","override","chainWalker","flattenedConfigs","rootOpts","configIsApplicable","push","envOpts","forEach","overrideOps","overrideEnvOpts","only","logger","mergeExtendsChain","mergeChainOpts","extends","has","from","delete","target","source","passPerPreset","test","include","exclude","Object","hasOwn","sourceMaps","sourceMap","items","Map","item","value","fnKey","nameMap","get","set","desc","ownPass","reduce","acc","configName","configFieldIsApplicable","patterns","matchesPatterns","ignoreListReplacer","_key","RegExp","String","message","JSON","stringify","pattern","pathToTest"],"sources":["../../src/config/config-chain.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-use-before-define */\n\nimport path from \"node:path\";\nimport { createDebug } from \"obug\";\nimport type { Handler } from \"gensync\";\nimport { validate } from \"./validation/options.ts\";\nimport type {\n ConfigApplicableTest,\n BabelrcSearch,\n CallerMetadata,\n MatchItem,\n InputOptions,\n ConfigChainOptions,\n} from \"./validation/options.ts\";\nimport pathPatternToRegex from \"./pattern-to-regex.ts\";\nimport { ConfigPrinter, ChainFormatter } from \"./printer.ts\";\nimport type { ReadonlyDeepArray } from \"./helpers/deep-array.ts\";\n\nimport { endHiddenCallStack } from \"../errors/rewrite-stack-trace.ts\";\nimport ConfigError from \"../errors/config-error.ts\";\nimport type { PluginAPI, PresetAPI } from \"./helpers/config-api.ts\";\n\nconst debug = createDebug(\"babel:config:config-chain\");\n\nimport {\n findPackageData,\n findRelativeConfig,\n findRootConfig,\n loadConfig,\n} from \"./files/index.ts\";\nimport type { ConfigFile, IgnoreFile, FilePackageData } from \"./files/index.ts\";\n\nimport { makeWeakCacheSync, makeStrongCacheSync } from \"./caching.ts\";\n\nimport {\n createCachedDescriptors,\n createUncachedDescriptors,\n} from \"./config-descriptors.ts\";\nimport type {\n UnloadedDescriptor,\n OptionsAndDescriptors,\n ValidatedFile,\n} from \"./config-descriptors.ts\";\n\nexport type ConfigChain = {\n plugins: UnloadedDescriptor<PluginAPI>[];\n presets: UnloadedDescriptor<PresetAPI>[];\n options: ConfigChainOptions[];\n files: Set<string>;\n};\n\nexport type PresetInstance = {\n options: InputOptions;\n alias: string;\n dirname: string;\n externalDependencies: ReadonlyDeepArray<string>;\n};\n\nexport type ConfigContext = {\n filename: string | undefined;\n cwd: string;\n root: string;\n envName: string;\n caller: CallerMetadata | undefined;\n showConfig: boolean;\n};\n\n/**\n * Build a config chain for a given preset.\n */\nexport function* buildPresetChain(\n arg: PresetInstance,\n context: any,\n): Handler<ConfigChain | null> {\n const chain = yield* buildPresetChainWalker(arg, context);\n if (!chain) return null;\n\n return {\n plugins: dedupDescriptors(chain.plugins),\n presets: dedupDescriptors(chain.presets),\n options: chain.options.map(o => createConfigChainOptions(o)),\n files: new Set(),\n };\n}\n\nexport const buildPresetChainWalker = makeChainWalker<PresetInstance>({\n root: preset => loadPresetDescriptors(preset),\n env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName),\n overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index),\n overridesEnv: (preset, index, envName) =>\n loadPresetOverridesEnvDescriptors(preset)(index)(envName),\n createLogger: () => () => {}, // Currently we don't support logging how preset is expanded\n});\nconst loadPresetDescriptors = makeWeakCacheSync((preset: PresetInstance) =>\n buildRootDescriptors(preset, preset.alias, createUncachedDescriptors),\n);\nconst loadPresetEnvDescriptors = makeWeakCacheSync((preset: PresetInstance) =>\n makeStrongCacheSync((envName: string) =>\n buildEnvDescriptors(\n preset,\n preset.alias,\n createUncachedDescriptors,\n envName,\n ),\n ),\n);\nconst loadPresetOverridesDescriptors = makeWeakCacheSync(\n (preset: PresetInstance) =>\n makeStrongCacheSync((index: number) =>\n buildOverrideDescriptors(\n preset,\n preset.alias,\n createUncachedDescriptors,\n index,\n ),\n ),\n);\nconst loadPresetOverridesEnvDescriptors = makeWeakCacheSync(\n (preset: PresetInstance) =>\n makeStrongCacheSync((index: number) =>\n makeStrongCacheSync((envName: string) =>\n buildOverrideEnvDescriptors(\n preset,\n preset.alias,\n createUncachedDescriptors,\n index,\n envName,\n ),\n ),\n ),\n);\n\nexport type FileHandling = \"transpile\" | \"ignored\" | \"unsupported\";\nexport type RootConfigChain = ConfigChain & {\n babelrc: ConfigFile | undefined;\n config: ConfigFile | undefined;\n ignore: IgnoreFile | undefined;\n fileHandling: FileHandling;\n files: Set<string>;\n};\n\n/**\n * Build a config chain for Babel's full root configuration.\n */\nexport function* buildRootChain(\n opts: InputOptions,\n context: ConfigContext,\n): Handler<RootConfigChain | null> {\n let configReport, babelRcReport;\n const programmaticLogger = new ConfigPrinter();\n const programmaticChain = yield* loadProgrammaticChain(\n {\n options: opts,\n dirname: context.cwd,\n },\n context,\n undefined,\n programmaticLogger,\n );\n if (!programmaticChain) return null;\n const programmaticReport = yield* programmaticLogger.output();\n\n let configFile;\n if (typeof opts.configFile === \"string\") {\n configFile = yield* loadConfig(\n opts.configFile,\n context.cwd,\n context.envName,\n context.caller,\n );\n } else if (opts.configFile !== false) {\n configFile = yield* findRootConfig(\n context.root,\n context.envName,\n context.caller,\n );\n }\n\n let { babelrc, babelrcRoots } = opts;\n let babelrcRootsDirectory = context.cwd;\n\n const configFileChain = emptyChain();\n const configFileLogger = new ConfigPrinter();\n if (configFile) {\n const validatedFile = validateConfigFile(configFile);\n const result = yield* loadFileChain(\n validatedFile,\n context,\n undefined,\n configFileLogger,\n );\n if (!result) return null;\n configReport = yield* configFileLogger.output();\n\n // Allow config files to toggle `.babelrc` resolution on and off and\n // specify where the roots are.\n if (babelrc === undefined) {\n babelrc = validatedFile.options.babelrc;\n }\n if (babelrcRoots === undefined) {\n babelrcRootsDirectory = validatedFile.dirname;\n babelrcRoots = validatedFile.options.babelrcRoots;\n }\n\n mergeChain(configFileChain, result);\n }\n\n let ignoreFile, babelrcFile;\n let isIgnored = false;\n const fileChain = emptyChain();\n // resolve all .babelrc files\n if (\n (babelrc === true || babelrc === undefined) &&\n typeof context.filename === \"string\"\n ) {\n const pkgData = yield* findPackageData(context.filename);\n\n if (\n pkgData &&\n babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)\n ) {\n ({ ignore: ignoreFile, config: babelrcFile } = yield* findRelativeConfig(\n pkgData,\n context.envName,\n context.caller,\n ));\n\n if (ignoreFile) {\n fileChain.files.add(ignoreFile.filepath);\n }\n\n if (\n ignoreFile &&\n shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)\n ) {\n isIgnored = true;\n }\n\n if (babelrcFile && !isIgnored) {\n const validatedFile = validateBabelrcFile(babelrcFile);\n const babelrcLogger = new ConfigPrinter();\n const result = yield* loadFileChain(\n validatedFile,\n context,\n undefined,\n babelrcLogger,\n );\n if (!result) {\n isIgnored = true;\n } else {\n babelRcReport = yield* babelrcLogger.output();\n mergeChain(fileChain, result);\n }\n }\n\n if (babelrcFile && isIgnored) {\n fileChain.files.add(babelrcFile.filepath);\n }\n }\n }\n\n if (context.showConfig) {\n console.log(\n `Babel configs on \"${context.filename}\" (ascending priority):\\n` +\n // print config by the order of ascending priority\n [configReport, babelRcReport, programmaticReport]\n .filter(x => !!x)\n .join(\"\\n\\n\") +\n \"\\n-----End Babel configs-----\",\n );\n }\n // Insert file chain in front so programmatic options have priority\n // over configuration file chain items.\n const chain = mergeChain(\n mergeChain(mergeChain(emptyChain(), configFileChain), fileChain),\n programmaticChain,\n );\n\n return {\n plugins: isIgnored ? [] : dedupDescriptors(chain.plugins),\n presets: isIgnored ? [] : dedupDescriptors(chain.presets),\n options: isIgnored\n ? []\n : chain.options.map(o => createConfigChainOptions(o)),\n fileHandling: isIgnored ? \"ignored\" : \"transpile\",\n ignore: ignoreFile || undefined,\n babelrc: babelrcFile || undefined,\n config: configFile || undefined,\n files: chain.files,\n };\n}\n\nfunction babelrcLoadEnabled(\n context: ConfigContext,\n pkgData: FilePackageData,\n babelrcRoots: BabelrcSearch | undefined,\n babelrcRootsDirectory: string,\n): boolean {\n if (typeof babelrcRoots === \"boolean\") return babelrcRoots;\n\n const absoluteRoot = context.root;\n\n // Fast path to avoid having to match patterns if the babelrc is just\n // loading in the standard root directory.\n if (babelrcRoots === undefined) {\n return pkgData.directories.includes(absoluteRoot);\n }\n\n let babelrcPatterns = babelrcRoots;\n if (!Array.isArray(babelrcPatterns)) {\n babelrcPatterns = [babelrcPatterns];\n }\n babelrcPatterns = babelrcPatterns.map(pat => {\n return typeof pat === \"string\"\n ? path.resolve(babelrcRootsDirectory, pat)\n : pat;\n });\n\n // Fast path to avoid having to match patterns if the babelrc is just\n // loading in the standard root directory.\n if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {\n return pkgData.directories.includes(absoluteRoot);\n }\n\n return babelrcPatterns.some(pat => {\n if (typeof pat === \"string\") {\n pat = pathPatternToRegex(pat, babelrcRootsDirectory);\n }\n\n return pkgData.directories.some(directory => {\n return matchPattern(pat, babelrcRootsDirectory, directory, context);\n });\n });\n}\n\nconst validateConfigFile = makeWeakCacheSync(\n (file: ConfigFile): ValidatedFile => ({\n filepath: file.filepath,\n dirname: file.dirname,\n options: validate(\"configfile\", file.options, file.filepath),\n }),\n);\n\nconst validateBabelrcFile = makeWeakCacheSync(\n (file: ConfigFile): ValidatedFile => ({\n filepath: file.filepath,\n dirname: file.dirname,\n options: validate(\"babelrcfile\", file.options, file.filepath),\n }),\n);\n\nconst validateExtendFile = makeWeakCacheSync(\n (file: ConfigFile): ValidatedFile => ({\n filepath: file.filepath,\n dirname: file.dirname,\n options: validate(\"extendsfile\", file.options, file.filepath),\n }),\n);\n\n/**\n * Build a config chain for just the programmatic options passed into Babel.\n */\nconst loadProgrammaticChain = makeChainWalker({\n root: input => buildRootDescriptors(input, \"base\", createCachedDescriptors),\n env: (input, envName) =>\n buildEnvDescriptors(input, \"base\", createCachedDescriptors, envName),\n overrides: (input, index) =>\n buildOverrideDescriptors(input, \"base\", createCachedDescriptors, index),\n overridesEnv: (input, index, envName) =>\n buildOverrideEnvDescriptors(\n input,\n \"base\",\n createCachedDescriptors,\n index,\n envName,\n ),\n createLogger: (input, context, baseLogger) =>\n buildProgrammaticLogger(input, context, baseLogger),\n});\n\n/**\n * Build a config chain for a given file.\n */\nconst loadFileChainWalker = makeChainWalker<ValidatedFile>({\n root: file => loadFileDescriptors(file),\n env: (file, envName) => loadFileEnvDescriptors(file)(envName),\n overrides: (file, index) => loadFileOverridesDescriptors(file)(index),\n overridesEnv: (file, index, envName) =>\n loadFileOverridesEnvDescriptors(file)(index)(envName),\n createLogger: (file, context, baseLogger) =>\n buildFileLogger(file.filepath, context, baseLogger),\n});\n\nfunction* loadFileChain(\n input: ValidatedFile,\n context: ConfigContext,\n files: Set<ConfigFile>,\n baseLogger: ConfigPrinter,\n) {\n const chain = yield* loadFileChainWalker(input, context, files, baseLogger);\n chain?.files.add(input.filepath);\n\n return chain;\n}\n\nconst loadFileDescriptors = makeWeakCacheSync((file: ValidatedFile) =>\n buildRootDescriptors(file, file.filepath, createUncachedDescriptors),\n);\nconst loadFileEnvDescriptors = makeWeakCacheSync((file: ValidatedFile) =>\n makeStrongCacheSync((envName: string) =>\n buildEnvDescriptors(\n file,\n file.filepath,\n createUncachedDescriptors,\n envName,\n ),\n ),\n);\nconst loadFileOverridesDescriptors = makeWeakCacheSync((file: ValidatedFile) =>\n makeStrongCacheSync((index: number) =>\n buildOverrideDescriptors(\n file,\n file.filepath,\n createUncachedDescriptors,\n index,\n ),\n ),\n);\nconst loadFileOverridesEnvDescriptors = makeWeakCacheSync(\n (file: ValidatedFile) =>\n makeStrongCacheSync((index: number) =>\n makeStrongCacheSync((envName: string) =>\n buildOverrideEnvDescriptors(\n file,\n file.filepath,\n createUncachedDescriptors,\n index,\n envName,\n ),\n ),\n ),\n);\n\nfunction buildFileLogger(\n filepath: string,\n context: ConfigContext,\n baseLogger: ConfigPrinter | void,\n) {\n if (!baseLogger) {\n return () => {};\n }\n return baseLogger.configure(context.showConfig, ChainFormatter.Config, {\n filepath,\n });\n}\n\nfunction buildRootDescriptors(\n { dirname, options }: Partial<ValidatedFile>,\n alias: string,\n descriptors: (\n dirname: string,\n options: InputOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n) {\n return descriptors(dirname, options, alias);\n}\n\nfunction buildProgrammaticLogger(\n _: unknown,\n context: ConfigContext,\n baseLogger: ConfigPrinter | void,\n) {\n if (!baseLogger) {\n return () => {};\n }\n return baseLogger.configure(context.showConfig, ChainFormatter.Programmatic, {\n callerName: context.caller?.name,\n });\n}\n\nfunction buildEnvDescriptors(\n { dirname, options }: Partial<ValidatedFile>,\n alias: string,\n descriptors: (\n dirname: string,\n options: InputOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n envName: string,\n) {\n const opts = options.env?.[envName];\n return opts ? descriptors(dirname, opts, `${alias}.env[\"${envName}\"]`) : null;\n}\n\nfunction buildOverrideDescriptors(\n { dirname, options }: Partial<ValidatedFile>,\n alias: string,\n descriptors: (\n dirname: string,\n options: InputOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n index: number,\n) {\n const opts = options.overrides?.[index];\n if (!opts) throw new Error(\"Assertion failure - missing override\");\n\n return descriptors(dirname, opts, `${alias}.overrides[${index}]`);\n}\n\nfunction buildOverrideEnvDescriptors(\n { dirname, options }: Partial<ValidatedFile>,\n alias: string,\n descriptors: (\n dirname: string,\n options: InputOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n index: number,\n envName: string,\n) {\n const override = options.overrides?.[index];\n if (!override) throw new Error(\"Assertion failure - missing override\");\n\n const opts = override.env?.[envName];\n return opts\n ? descriptors(\n dirname,\n opts,\n `${alias}.overrides[${index}].env[\"${envName}\"]`,\n )\n : null;\n}\n\nfunction makeChainWalker<\n ArgT extends {\n options: InputOptions;\n dirname: string;\n filepath?: string;\n },\n>({\n root,\n env,\n overrides,\n overridesEnv,\n createLogger,\n}: {\n root: (configEntry: ArgT) => OptionsAndDescriptors;\n env: (configEntry: ArgT, env: string) => OptionsAndDescriptors | null;\n overrides: (configEntry: ArgT, index: number) => OptionsAndDescriptors;\n overridesEnv: (\n configEntry: ArgT,\n index: number,\n env: string,\n ) => OptionsAndDescriptors | null;\n createLogger: (\n configEntry: ArgT,\n context: ConfigContext,\n printer: ConfigPrinter | void,\n ) => (\n opts: OptionsAndDescriptors,\n index?: number | null,\n env?: string | null,\n ) => void;\n}): (\n configEntry: ArgT,\n context: ConfigContext,\n files?: Set<ConfigFile>,\n baseLogger?: ConfigPrinter,\n) => Handler<ConfigChain | null> {\n return function* chainWalker(input, context, files = new Set(), baseLogger) {\n const { dirname } = input;\n\n const flattenedConfigs: {\n config: OptionsAndDescriptors;\n index: number | undefined | null;\n envName: string | undefined | null;\n }[] = [];\n\n const rootOpts = root(input);\n if (configIsApplicable(rootOpts, dirname, context, input.filepath)) {\n flattenedConfigs.push({\n config: rootOpts,\n envName: undefined,\n index: undefined,\n });\n\n const envOpts = env(input, context.envName);\n if (\n envOpts &&\n configIsApplicable(envOpts, dirname, context, input.filepath)\n ) {\n flattenedConfigs.push({\n config: envOpts,\n envName: context.envName,\n index: undefined,\n });\n }\n\n (rootOpts.options.overrides || []).forEach((_, index) => {\n const overrideOps = overrides(input, index);\n if (configIsApplicable(overrideOps, dirname, context, input.filepath)) {\n flattenedConfigs.push({\n config: overrideOps,\n index,\n envName: undefined,\n });\n\n const overrideEnvOpts = overridesEnv(input, index, context.envName);\n if (\n overrideEnvOpts &&\n configIsApplicable(\n overrideEnvOpts,\n dirname,\n context,\n input.filepath,\n )\n ) {\n flattenedConfigs.push({\n config: overrideEnvOpts,\n index,\n envName: context.envName,\n });\n }\n }\n });\n }\n\n // Process 'ignore' and 'only' before 'extends' items are processed so\n // that we don't do extra work loading extended configs if a file is\n // ignored.\n if (\n flattenedConfigs.some(\n ({\n config: {\n options: { ignore, only },\n },\n }) => shouldIgnore(context, ignore, only, dirname),\n )\n ) {\n return null;\n }\n\n const chain = emptyChain();\n const logger = createLogger(input, context, baseLogger);\n\n for (const { config, index, envName } of flattenedConfigs) {\n if (\n !(yield* mergeExtendsChain(\n chain,\n config.options,\n dirname,\n context,\n files,\n baseLogger,\n ))\n ) {\n return null;\n }\n\n logger(config, index, envName);\n yield* mergeChainOpts(chain, config);\n }\n return chain;\n };\n}\n\nfunction* mergeExtendsChain(\n chain: ConfigChain,\n opts: InputOptions,\n dirname: string,\n context: ConfigContext,\n files: Set<ConfigFile>,\n baseLogger?: ConfigPrinter,\n): Handler<boolean> {\n if (opts.extends === undefined) return true;\n\n const file = yield* loadConfig(\n opts.extends,\n dirname,\n context.envName,\n context.caller,\n );\n\n if (files.has(file)) {\n throw new Error(\n `Configuration cycle detected loading ${file.filepath}.\\n` +\n `File already loaded following the config chain:\\n` +\n Array.from(files, file => ` - ${file.filepath}`).join(\"\\n\"),\n );\n }\n\n files.add(file);\n const fileChain = yield* loadFileChain(\n validateExtendFile(file),\n context,\n files,\n baseLogger,\n );\n files.delete(file);\n\n if (!fileChain) return false;\n\n mergeChain(chain, fileChain);\n\n return true;\n}\n\nfunction mergeChain(target: ConfigChain, source: ConfigChain): ConfigChain {\n target.options.push(...source.options);\n target.plugins.push(...source.plugins);\n target.presets.push(...source.presets);\n for (const file of source.files) {\n target.files.add(file);\n }\n\n return target;\n}\n\nfunction* mergeChainOpts(\n target: ConfigChain,\n { options, plugins, presets }: OptionsAndDescriptors,\n): Handler<ConfigChain> {\n target.options.push(options);\n target.plugins.push(...(yield* plugins()));\n target.presets.push(...(yield* presets()));\n\n return target;\n}\n\nfunction emptyChain(): ConfigChain {\n return {\n options: [],\n presets: [],\n plugins: [],\n files: new Set(),\n };\n}\n\nfunction createConfigChainOptions(opts: InputOptions): ConfigChainOptions {\n const options = {\n ...opts,\n };\n delete options.extends;\n delete options.env;\n delete options.overrides;\n delete options.plugins;\n delete options.presets;\n delete options.passPerPreset;\n delete options.ignore;\n delete options.only;\n delete options.test;\n delete options.include;\n delete options.exclude;\n\n // \"sourceMap\" is just aliased to sourceMap, so copy it over as\n // we merge the options together.\n if (Object.hasOwn(options, \"sourceMap\")) {\n options.sourceMaps = options.sourceMap;\n delete options.sourceMap;\n }\n return options;\n}\n\nfunction dedupDescriptors<API>(\n items: UnloadedDescriptor<API>[],\n): UnloadedDescriptor<API>[] {\n const map = new Map<\n Function,\n Map<string | void, { value: UnloadedDescriptor<API> }>\n >();\n\n const descriptors = [];\n\n for (const item of items) {\n if (typeof item.value === \"function\") {\n const fnKey = item.value;\n let nameMap = map.get(fnKey);\n if (!nameMap) {\n nameMap = new Map();\n map.set(fnKey, nameMap);\n }\n let desc = nameMap.get(item.name);\n if (!desc) {\n desc = { value: item };\n descriptors.push(desc);\n\n // Treat passPerPreset presets as unique, skipping them\n // in the merge processing steps.\n if (!item.ownPass) nameMap.set(item.name, desc);\n } else {\n desc.value = item;\n }\n } else {\n descriptors.push({ value: item });\n }\n }\n\n return descriptors.reduce((acc, desc) => {\n acc.push(desc.value);\n return acc;\n }, []);\n}\n\nfunction configIsApplicable(\n { options }: OptionsAndDescriptors,\n dirname: string,\n context: ConfigContext,\n configName: string,\n): boolean {\n return (\n (options.test === undefined ||\n configFieldIsApplicable(context, options.test, dirname, configName)) &&\n (options.include === undefined ||\n configFieldIsApplicable(context, options.include, dirname, configName)) &&\n (options.exclude === undefined ||\n !configFieldIsApplicable(context, options.exclude, dirname, configName))\n );\n}\n\nfunction configFieldIsApplicable(\n context: ConfigContext,\n test: ConfigApplicableTest,\n dirname: string,\n configName: string,\n): boolean {\n const patterns = Array.isArray(test) ? test : [test];\n\n return matchesPatterns(context, patterns, dirname, configName);\n}\n\n/**\n * Print the ignoreList-values in a more helpful way than the default.\n */\nfunction ignoreListReplacer(\n _key: string,\n value: MatchItem[] | MatchItem,\n): MatchItem[] | MatchItem | string {\n if (value instanceof RegExp) {\n return String(value);\n }\n\n return value;\n}\n\n/**\n * Tests if a filename should be ignored based on \"ignore\" and \"only\" options.\n */\nfunction shouldIgnore(\n context: ConfigContext,\n ignore: MatchItem[] | undefined | null,\n only: MatchItem[] | undefined | null,\n dirname: string,\n): boolean {\n if (ignore && matchesPatterns(context, ignore, dirname)) {\n const message = `No config is applied to \"${\n context.filename ?? \"(unknown)\"\n }\" because it matches one of \\`ignore: ${JSON.stringify(\n ignore,\n ignoreListReplacer,\n )}\\` from \"${dirname}\"`;\n debug(message);\n if (context.showConfig) {\n console.log(message);\n }\n return true;\n }\n\n if (only && !matchesPatterns(context, only, dirname)) {\n const message = `No config is applied to \"${\n context.filename ?? \"(unknown)\"\n }\" because it fails to match one of \\`only: ${JSON.stringify(\n only,\n ignoreListReplacer,\n )}\\` from \"${dirname}\"`;\n debug(message);\n if (context.showConfig) {\n console.log(message);\n }\n return true;\n }\n\n return false;\n}\n\n/**\n * Returns result of calling function with filename if pattern is a function.\n * Otherwise returns result of matching pattern Regex with filename.\n */\nfunction matchesPatterns(\n context: ConfigContext,\n patterns: MatchItem[],\n dirname: string,\n configName?: string,\n): boolean {\n return patterns.some(pattern =>\n matchPattern(pattern, dirname, context.filename, context, configName),\n );\n}\n\nfunction matchPattern(\n pattern: MatchItem,\n dirname: string,\n pathToTest: string | undefined,\n context: ConfigContext,\n configName?: string,\n): boolean {\n if (typeof pattern === \"function\") {\n return !!endHiddenCallStack(pattern)(pathToTest, {\n dirname,\n envName: context.envName,\n caller: context.caller,\n });\n }\n\n if (typeof pathToTest !== \"string\") {\n throw new ConfigError(\n `Configuration contains string/RegExp pattern, but no filename was passed to Babel`,\n configName,\n );\n }\n\n if (typeof pattern === \"string\") {\n pattern = pathPatternToRegex(pattern, dirname);\n }\n return pattern.test(pathToTest);\n}\n"],"mappings":"AAEA,OAAOA,IAAI,MAAM,WAAW;AAC5B,SAASC,WAAW,QAAQ,MAAM;AAElC,SAASC,QAAQ,QAAQ,yBAAyB;AASlD,OAAOC,kBAAkB,MAAM,uBAAuB;AACtD,SAASC,aAAa,EAAEC,cAAc,QAAQ,cAAc;AAG5D,SAASC,kBAAkB,QAAQ,kCAAkC;AACrE,OAAOC,WAAW,MAAM,2BAA2B;AAGnD,MAAMC,KAAK,GAAGP,WAAW,CAAC,2BAA2B,CAAC;AAEtD,SACEQ,eAAe,EACfC,kBAAkB,EAClBC,cAAc,EACdC,UAAU,QACL,kBAAkB;AAGzB,SAASC,iBAAiB,EAAEC,mBAAmB,QAAQ,cAAc;AAErE,SACEC,uBAAuB,EACvBC,yBAAyB,QACpB,yBAAyB;AAiChC,OAAO,UAAUC,gBAAgBA,CAC/BC,GAAmB,EACnBC,OAAY,EACiB;EAC7B,MAAMC,KAAK,GAAG,OAAOC,sBAAsB,CAACH,GAAG,EAAEC,OAAO,CAA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AACoF,OAAO,CAAC;IACtB;IACA,OAAO,IAAI;EACb;EAEA,OAAO,KAAK;AACd;AAMA,SAASL,eAAeA,CACtBtJ,OAAsB,EACtBqJ,QAAqB,EACrBhH,OAAe,EACf8G,UAAmB,EACV;EACT,OAAOE,QAAQ,CAAChE,IAAI,CAACyE,OAAO,IAC1BvE,YAAY,CAACuE,OAAO,EAAEzH,OAAO,EAAErC,OAAO,CAAC2D,QAAQ,EAAE3D,OAAO,EAAEmJ,UAAU,CACtE,CAAC;AACH;AAEA,SAAS5D,YAAYA,CACnBuE,OAAkB,EAClBzH,OAAe,EACf0H,UAA8B,EAC9B/J,OAAsB,EACtBmJ,UAAmB,EACV;EACT,IAAI,OAAOW,OAAO,KAAK,UAAU,EAAE;IACjC,OAAO,CAAC,CAAC3K,kBAAkB,CAAC2K,OAAO,CAAC,CAACC,UAAU,EAAE;MAC/C1H,OAAO;MACPpB,OAAO,EAAEjB,OAAO,CAACiB,OAAO;MACxB0B,MAAM,EAAE3C,OAAO,CAAC2C;IAClB,CAAC,CAAC;EACJ;EAEA,IAAI,OAAOoH,UAAU,KAAK,QAAQ,EAAE;IAClC,MAAM,IAAI3K,WAAW,CACnB,mFAAmF,EACnF+J,UACF,CAAC;EACH;EAEA,IAAI,OAAOW,OAAO,KAAK,QAAQ,EAAE;IAC/BA,OAAO,GAAG9K,kBAAkB,CAAC8K,OAAO,EAAEzH,OAAO,CAAC;EAChD;EACA,OAAOyH,OAAO,CAAC9B,IAAI,CAAC+B,UAAU,CAAC;AACjC","ignoreList":[]} |
| import gensync from "gensync"; | ||
| import { once } from "../gensync-utils/functional.js"; | ||
| import { loadPlugin, loadPreset } from "./files/index.js"; | ||
| import { getItemDescriptor } from "./item.js"; | ||
| import { makeWeakCacheSync, makeStrongCacheSync, makeStrongCache } from "./caching.js"; | ||
| import { resolveBrowserslistConfigFile } from "./resolve-targets.js"; | ||
| function isEqualDescriptor(a, b) { | ||
| return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && a.file?.request === b.file?.request && a.file?.resolved === b.file?.resolved; | ||
| } | ||
| function* handlerOf(value) { | ||
| return value; | ||
| } | ||
| function optionsWithResolvedBrowserslistConfigFile(options, dirname) { | ||
| if (typeof options.browserslistConfigFile === "string") { | ||
| options.browserslistConfigFile = resolveBrowserslistConfigFile(options.browserslistConfigFile, dirname); | ||
| } | ||
| return options; | ||
| } | ||
| export function createCachedDescriptors(dirname, options, alias) { | ||
| const { | ||
| plugins, | ||
| presets, | ||
| passPerPreset | ||
| } = options; | ||
| return { | ||
| options: optionsWithResolvedBrowserslistConfigFile(options, dirname), | ||
| plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => handlerOf([]), | ||
| presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => handlerOf([]) | ||
| }; | ||
| } | ||
| export function createUncachedDescriptors(dirname, options, alias) { | ||
| return { | ||
| options: optionsWithResolvedBrowserslistConfigFile(options, dirname), | ||
| plugins: once(() => createPluginDescriptors(options.plugins || [], dirname, alias)), | ||
| presets: once(() => createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset)) | ||
| }; | ||
| } | ||
| const PRESET_DESCRIPTOR_CACHE = new WeakMap(); | ||
| const createCachedPresetDescriptors = makeWeakCacheSync((items, cache) => { | ||
| const dirname = cache.using(dir => dir); | ||
| return makeStrongCacheSync(alias => makeStrongCache(function* (passPerPreset) { | ||
| const descriptors = yield* createPresetDescriptors(items, dirname, alias, passPerPreset); | ||
| return descriptors.map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc)); | ||
| })); | ||
| }); | ||
| const PLUGIN_DESCRIPTOR_CACHE = new WeakMap(); | ||
| const createCachedPluginDescriptors = makeWeakCacheSync((items, cache) => { | ||
| const dirname = cache.using(dir => dir); | ||
| return makeStrongCache(function* (alias) { | ||
| const descriptors = yield* createPluginDescriptors(items, dirname, alias); | ||
| return descriptors.map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc)); | ||
| }); | ||
| }); | ||
| const DEFAULT_OPTIONS = {}; | ||
| function loadCachedDescriptor(cache, desc) { | ||
| const { | ||
| value, | ||
| options = DEFAULT_OPTIONS | ||
| } = desc; | ||
| if (options === false) return desc; | ||
| let cacheByOptions = cache.get(value); | ||
| if (!cacheByOptions) { | ||
| cacheByOptions = new WeakMap(); | ||
| cache.set(value, cacheByOptions); | ||
| } | ||
| let possibilities = cacheByOptions.get(options); | ||
| if (!possibilities) { | ||
| possibilities = []; | ||
| cacheByOptions.set(options, possibilities); | ||
| } | ||
| if (!possibilities.includes(desc)) { | ||
| const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc)); | ||
| if (matches.length > 0) { | ||
| return matches[0]; | ||
| } | ||
| possibilities.push(desc); | ||
| } | ||
| return desc; | ||
| } | ||
| function* createPresetDescriptors(items, dirname, alias, passPerPreset) { | ||
| return yield* createDescriptors("preset", items, dirname, alias, passPerPreset); | ||
| } | ||
| function* createPluginDescriptors(items, dirname, alias) { | ||
| return yield* createDescriptors("plugin", items, dirname, alias); | ||
| } | ||
| function* createDescriptors(type, items, dirname, alias, ownPass) { | ||
| const descriptors = yield* gensync.all(items.map((item, index) => createDescriptor(item, dirname, { | ||
| type, | ||
| alias: `${alias}$${index}`, | ||
| ownPass: !!ownPass | ||
| }))); | ||
| assertNoDuplicates(descriptors); | ||
| return descriptors; | ||
| } | ||
| export function* createDescriptor(pair, dirname, { | ||
| type, | ||
| alias, | ||
| ownPass | ||
| }) { | ||
| const desc = getItemDescriptor(pair); | ||
| if (desc) { | ||
| return desc; | ||
| } | ||
| let name; | ||
| let options; | ||
| let value = pair; | ||
| if (Array.isArray(value)) { | ||
| if (value.length === 3) { | ||
| [value, options, name] = value; | ||
| } else { | ||
| [value, options] = value; | ||
| } | ||
| } | ||
| let file = undefined; | ||
| let filepath = null; | ||
| if (typeof value === "string") { | ||
| if (typeof type !== "string") { | ||
| throw new Error("To resolve a string-based item, the type of item must be given"); | ||
| } | ||
| const resolver = type === "plugin" ? loadPlugin : loadPreset; | ||
| const request = value; | ||
| ({ | ||
| filepath, | ||
| value | ||
| } = yield* resolver(value, dirname)); | ||
| file = { | ||
| request, | ||
| resolved: filepath | ||
| }; | ||
| } | ||
| if (!value) { | ||
| throw new Error(`Unexpected falsy value: ${String(value)}`); | ||
| } | ||
| if (typeof value === "object" && value.__esModule) { | ||
| if (value.default) { | ||
| value = value.default; | ||
| } else { | ||
| throw new Error("Must export a default export when using ES6 modules."); | ||
| } | ||
| } | ||
| if (typeof value !== "object" && typeof value !== "function") { | ||
| throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`); | ||
| } | ||
| if (filepath !== null && typeof value === "object" && value) { | ||
| throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`); | ||
| } | ||
| return { | ||
| name, | ||
| alias: filepath || alias, | ||
| value, | ||
| options, | ||
| dirname, | ||
| ownPass, | ||
| file | ||
| }; | ||
| } | ||
| function assertNoDuplicates(items) { | ||
| const map = new Map(); | ||
| for (const item of items) { | ||
| if (typeof item.value !== "function") continue; | ||
| let nameMap = map.get(item.value); | ||
| if (!nameMap) { | ||
| nameMap = new Set(); | ||
| map.set(item.value, nameMap); | ||
| } | ||
| if (nameMap.has(item.name)) { | ||
| const conflicts = items.filter(i => i.value === item.value); | ||
| throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, ` plugins: [`, ` ['some-plugin', {}],`, ` ['some-plugin', {}, 'some unique name'],`, ` ]`, ``, `Duplicates detected are:`, `${JSON.stringify(conflicts, null, 2)}`].join("\n")); | ||
| } | ||
| nameMap.add(item.name); | ||
| } | ||
| } | ||
| //# sourceMappingURL=config-descriptors.js.map |
| {"version":3,"names":["gensync","once","loadPlugin","loadPreset","getItemDescriptor","makeWeakCacheSync","makeStrongCacheSync","makeStrongCache","resolveBrowserslistConfigFile","isEqualDescriptor","a","b","name","value","options","dirname","alias","ownPass","file","request","resolved","handlerOf","optionsWithResolvedBrowserslistConfigFile","browserslistConfigFile","createCachedDescriptors","plugins","presets","passPerPreset","createCachedPluginDescriptors","createCachedPresetDescriptors","createUncachedDescriptors","createPluginDescriptors","createPresetDescriptors","PRESET_DESCRIPTOR_CACHE","WeakMap","items","cache","using","dir","descriptors","map","desc","loadCachedDescriptor","PLUGIN_DESCRIPTOR_CACHE","DEFAULT_OPTIONS","cacheByOptions","get","set","possibilities","includes","matches","filter","possibility","length","push","createDescriptors","type","all","item","index","createDescriptor","assertNoDuplicates","pair","Array","isArray","undefined","filepath","Error","resolver","String","__esModule","default","Map","nameMap","Set","has","conflicts","i","JSON","stringify","join","add"],"sources":["../../src/config/config-descriptors.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\nimport { once } from \"../gensync-utils/functional.ts\";\n\nimport { loadPlugin, loadPreset } from \"./files/index.ts\";\n\nimport { getItemDescriptor } from \"./item.ts\";\n\nimport {\n makeWeakCacheSync,\n makeStrongCacheSync,\n makeStrongCache,\n} from \"./caching.ts\";\nimport type { CacheConfigurator } from \"./caching.ts\";\n\nimport type {\n PluginItem,\n InputOptions,\n PresetItem,\n} from \"./validation/options.ts\";\n\nimport { resolveBrowserslistConfigFile } from \"./resolve-targets.ts\";\nimport type { PluginAPI, PresetAPI } from \"./helpers/config-api.ts\";\n\n// Represents a config object and functions to lazily load the descriptors\n// for the plugins and presets so we don't load the plugins/presets unless\n// the options object actually ends up being applicable.\nexport type OptionsAndDescriptors = {\n options: InputOptions;\n plugins: () => Handler<UnloadedDescriptor<PluginAPI>[]>;\n presets: () => Handler<UnloadedDescriptor<PresetAPI>[]>;\n};\n\n// Represents a plugin or presets at a given location in a config object.\n// At this point these have been resolved to a specific object or function,\n// but have not yet been executed to call functions with options.\nexport interface UnloadedDescriptor<API, Options = object | undefined> {\n name: string | undefined;\n value: object | ((api: API, options: Options, dirname: string) => unknown);\n options: Options;\n dirname: string;\n alias: string;\n ownPass?: boolean;\n file?: {\n request: string;\n resolved: string;\n };\n}\n\nfunction isEqualDescriptor<API>(\n a: UnloadedDescriptor<API>,\n b: UnloadedDescriptor<API>,\n): boolean {\n return (\n a.name === b.name &&\n a.value === b.value &&\n a.options === b.options &&\n a.dirname === b.dirname &&\n a.alias === b.alias &&\n a.ownPass === b.ownPass &&\n a.file?.request === b.file?.request &&\n a.file?.resolved === b.file?.resolved\n );\n}\n\nexport type ValidatedFile = {\n filepath: string;\n dirname: string;\n options: InputOptions;\n};\n\n// eslint-disable-next-line require-yield\nfunction* handlerOf<T>(value: T): Handler<T> {\n return value;\n}\n\nfunction optionsWithResolvedBrowserslistConfigFile(\n options: InputOptions,\n dirname: string,\n): InputOptions {\n if (typeof options.browserslistConfigFile === \"string\") {\n options.browserslistConfigFile = resolveBrowserslistConfigFile(\n options.browserslistConfigFile,\n dirname,\n );\n }\n return options;\n}\n\n/**\n * Create a set of descriptors from a given options object, preserving\n * descriptor identity based on the identity of the plugin/preset arrays\n * themselves, and potentially on the identity of the plugins/presets + options.\n */\nexport function createCachedDescriptors(\n dirname: string,\n options: InputOptions,\n alias: string,\n): OptionsAndDescriptors {\n const { plugins, presets, passPerPreset } = options;\n return {\n options: optionsWithResolvedBrowserslistConfigFile(options, dirname),\n plugins: plugins\n ? () =>\n // @ts-expect-error todo(flow->ts) ts complains about incorrect arguments\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n createCachedPluginDescriptors(plugins, dirname)(alias)\n : () => handlerOf([]),\n presets: presets\n ? () =>\n // @ts-expect-error todo(flow->ts) ts complains about incorrect arguments\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n createCachedPresetDescriptors(presets, dirname)(alias)(\n !!passPerPreset,\n )\n : () => handlerOf([]),\n };\n}\n\n/**\n * Create a set of descriptors from a given options object, with consistent\n * identity for the descriptors, but not caching based on any specific identity.\n */\nexport function createUncachedDescriptors(\n dirname: string,\n options: InputOptions,\n alias: string,\n): OptionsAndDescriptors {\n return {\n options: optionsWithResolvedBrowserslistConfigFile(options, dirname),\n // The returned result here is cached to represent a config object in\n // memory, so we build and memoize the descriptors to ensure the same\n // values are returned consistently.\n plugins: once(() =>\n createPluginDescriptors(options.plugins || [], dirname, alias),\n ),\n presets: once(() =>\n createPresetDescriptors(\n options.presets || [],\n dirname,\n alias,\n !!options.passPerPreset,\n ),\n ),\n };\n}\n\nconst PRESET_DESCRIPTOR_CACHE = new WeakMap();\nconst createCachedPresetDescriptors = makeWeakCacheSync(\n (items: PresetItem[], cache: CacheConfigurator<string>) => {\n const dirname = cache.using(dir => dir);\n return makeStrongCacheSync((alias: string) =>\n makeStrongCache(function* (\n passPerPreset: boolean,\n ): Handler<UnloadedDescriptor<PresetAPI>[]> {\n const descriptors = yield* createPresetDescriptors(\n items,\n dirname,\n alias,\n passPerPreset,\n );\n return descriptors.map(\n // Items are cached using the overall preset array identity when\n // possibly, but individual descriptors are also cached if a match\n // can be found in the previously-used descriptor lists.\n desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc),\n );\n }),\n );\n },\n);\n\nconst PLUGIN_DESCRIPTOR_CACHE = new WeakMap();\nconst createCachedPluginDescriptors = makeWeakCacheSync(\n (items: PluginItem[], cache: CacheConfigurator<string>) => {\n const dirname = cache.using(dir => dir);\n return makeStrongCache(function* (\n alias: string,\n ): Handler<UnloadedDescriptor<PluginAPI>[]> {\n const descriptors = yield* createPluginDescriptors(items, dirname, alias);\n return descriptors.map(\n // Items are cached using the overall plugin array identity when\n // possibly, but individual descriptors are also cached if a match\n // can be found in the previously-used descriptor lists.\n desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc),\n );\n });\n },\n);\n\n/**\n * When no options object is given in a descriptor, this object is used\n * as a WeakMap key in order to have consistent identity.\n */\nconst DEFAULT_OPTIONS = {};\n\n/**\n * Given the cache and a descriptor, returns a matching descriptor from the\n * cache, or else returns the input descriptor and adds it to the cache for\n * next time.\n */\nfunction loadCachedDescriptor<API>(\n cache: WeakMap<object | Function, WeakMap<object, UnloadedDescriptor<API>[]>>,\n desc: UnloadedDescriptor<API>,\n) {\n const { value, options = DEFAULT_OPTIONS } = desc;\n if (options === false) return desc;\n\n let cacheByOptions = cache.get(value);\n if (!cacheByOptions) {\n cacheByOptions = new WeakMap();\n cache.set(value, cacheByOptions);\n }\n\n let possibilities = cacheByOptions.get(options);\n if (!possibilities) {\n possibilities = [];\n cacheByOptions.set(options, possibilities);\n }\n\n if (!possibilities.includes(desc)) {\n const matches = possibilities.filter(possibility =>\n isEqualDescriptor(possibility, desc),\n );\n if (matches.length > 0) {\n return matches[0];\n }\n\n possibilities.push(desc);\n }\n\n return desc;\n}\n\nfunction* createPresetDescriptors(\n items: PresetItem[],\n dirname: string,\n alias: string,\n passPerPreset: boolean,\n): Handler<UnloadedDescriptor<PresetAPI>[]> {\n return yield* createDescriptors(\n \"preset\",\n items,\n dirname,\n alias,\n passPerPreset,\n );\n}\n\nfunction* createPluginDescriptors(\n items: PluginItem[],\n dirname: string,\n alias: string,\n): Handler<UnloadedDescriptor<PluginAPI>[]> {\n return yield* createDescriptors(\"plugin\", items, dirname, alias);\n}\n\nfunction* createDescriptors<const Type extends \"plugin\" | \"preset\">(\n type: Type,\n items: Type extends \"plugin\" ? PluginItem[] : PresetItem[],\n dirname: string,\n alias: string,\n ownPass?: boolean,\n): Handler<\n UnloadedDescriptor<Type extends \"plugin\" ? PluginAPI : PresetAPI>[]\n> {\n const descriptors = yield* gensync.all(\n items.map((item, index) =>\n createDescriptor(item, dirname, {\n type,\n alias: `${alias}$${index}`,\n ownPass: !!ownPass,\n }),\n ),\n );\n\n assertNoDuplicates(descriptors);\n\n return descriptors;\n}\n\n/**\n * Given a plugin/preset item, resolve it into a standard format.\n */\nexport function* createDescriptor<API>(\n pair: PluginItem | PresetItem,\n dirname: string,\n {\n type,\n alias,\n ownPass,\n }: {\n type?: \"plugin\" | \"preset\";\n alias: string;\n ownPass?: boolean;\n },\n): Handler<UnloadedDescriptor<API>> {\n const desc = getItemDescriptor(pair);\n if (desc) {\n return desc;\n }\n\n let name;\n let options;\n let value = pair;\n if (Array.isArray(value)) {\n if (value.length === 3) {\n [value, options, name] = value;\n } else {\n [value, options] = value;\n }\n }\n\n let file = undefined;\n let filepath = null;\n if (typeof value === \"string\") {\n if (typeof type !== \"string\") {\n throw new Error(\n \"To resolve a string-based item, the type of item must be given\",\n );\n }\n const resolver = type === \"plugin\" ? loadPlugin : loadPreset;\n const request = value;\n\n // @ts-expect-error value must be a PluginItem\n ({ filepath, value } = yield* resolver(value, dirname));\n\n file = {\n request,\n resolved: filepath,\n };\n }\n\n if (!value) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n throw new Error(`Unexpected falsy value: ${String(value)}`);\n }\n\n // @ts-expect-error Handle transpiled ES6 modules.\n if (typeof value === \"object\" && value.__esModule) {\n // @ts-expect-error Handle transpiled ES6 modules.\n if (value.default) {\n // @ts-expect-error Handle transpiled ES6 modules.\n value = value.default;\n } else {\n throw new Error(\"Must export a default export when using ES6 modules.\");\n }\n }\n\n if (typeof value !== \"object\" && typeof value !== \"function\") {\n throw new Error(\n `Unsupported format: ${typeof value}. Expected an object or a function.`,\n );\n }\n\n if (filepath !== null && typeof value === \"object\" && value) {\n // We allow object values for plugins/presets nested directly within a\n // config object, because it can be useful to define them in nested\n // configuration contexts.\n throw new Error(\n `Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`,\n );\n }\n\n return {\n name,\n alias: filepath || alias,\n value,\n options,\n dirname,\n ownPass,\n file,\n };\n}\n\nfunction assertNoDuplicates<API>(items: UnloadedDescriptor<API>[]): void {\n const map = new Map();\n\n for (const item of items) {\n if (typeof item.value !== \"function\") continue;\n\n let nameMap = map.get(item.value);\n if (!nameMap) {\n nameMap = new Set();\n map.set(item.value, nameMap);\n }\n\n if (nameMap.has(item.name)) {\n const conflicts = items.filter(i => i.value === item.value);\n throw new Error(\n [\n `Duplicate plugin/preset detected.`,\n `If you'd like to use two separate instances of a plugin,`,\n `they need separate names, e.g.`,\n ``,\n ` plugins: [`,\n ` ['some-plugin', {}],`,\n ` ['some-plugin', {}, 'some unique name'],`,\n ` ]`,\n ``,\n `Duplicates detected are:`,\n `${JSON.stringify(conflicts, null, 2)}`,\n ].join(\"\\n\"),\n );\n }\n\n nameMap.add(item.name);\n }\n}\n"],"mappings":"AAAA,OAAOA,OAAO,MAAwB,SAAS;AAC/C,SAASC,IAAI,QAAQ,gCAAgC;AAErD,SAASC,UAAU,EAAEC,UAAU,QAAQ,kBAAkB;AAEzD,SAASC,iBAAiB,QAAQ,WAAW;AAE7C,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,eAAe,QACV,cAAc;AASrB,SAASC,6BAA6B,QAAQ,sBAAsB;AA4BpE,SAASC,iBAAiBA,CACxBC,CAA0B,EAC1BC,CAA0B,EACjB;EACT,OACED,CAAC,CAACE,IAAI,KAAKD,CAAC,CAACC,IAAI,IACjBF,CAAC,CAACG,KAAK,KAAKF,CAAC,CAACE,KAAK,IACnBH,CAAC,CAACI,OAAO,KAAKH,CAAC,CAACG,OAAO,IACvBJ,CAAC,CAACK,OAAO,KAAKJ,CAAC,CAACI,OAAO,IACvBL,CAAC,CAACM,KAAK,KAAKL,CAAC,CAACK,KAAK,IACnBN,CAAC,CAACO,OAAO,KAAKN,CAAC,CAACM,OAAO,IACvBP,CAAC,CAACQ,IAAI,EAAEC,OAAO,KAAKR,CAAC,CAACO,IAAI,EAAEC,OAAO,IACnCT,CAAC,CAACQ,IAAI,EAAEE,QAAQ,KAAKT,CAAC,CAACO,IAAI,EAAEE,QAAQ;AAEzC;AASA,UAAUC,SAASA,CAAIR,KAAQ,EAAc;EAC3C,OAAOA,KAAK;AACd;AAEA,SAASS,yCAAyCA,CAChDR,OAAqB,EACrBC,OAAe,EACD;EACd,IAAI,OAAOD,OAAO,CAACS,sBAAsB,KAAK,QAAQ,EAAE;IACtDT,OAAO,CAACS,sBAAsB,GAAGf,6BAA6B,CAC5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gE,SAAS,GAAGzC,KAAK,CAACgB,MAAM,CAAC0B,CAAC,IAAIA,CAAC,CAAChE,KAAK,KAAK6C,IAAI,CAAC7C,KAAK,CAAC;MAC3D,MAAM,IAAIsD,KAAK,CACb,CACE,mCAAmC,EACnC,0DAA0D,EAC1D,gCAAgC,EAChC,EAAE,EACF,cAAc,EACd,0BAA0B,EAC1B,8CAA8C,EAC9C,KAAK,EACL,EAAE,EACF,0BAA0B,EAC1B,GAAGW,IAAI,CAACC,SAAS,CAACH,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CACxC,CAACI,IAAI,CAAC,IAAI,CACb,CAAC;IACH;IAEAP,OAAO,CAACQ,GAAG,CAACvB,IAAI,CAAC9C,IAAI,CAAC;EACxB;AACF","ignoreList":[]} |
| import { createDebug } from "obug"; | ||
| import nodeFs from "node:fs"; | ||
| import path from "node:path"; | ||
| import json5 from "json5"; | ||
| import gensync from "gensync"; | ||
| import { makeWeakCache, makeWeakCacheSync } from "../caching.js"; | ||
| import { makeConfigAPI } from "../helpers/config-api.js"; | ||
| import { makeStaticFileCache } from "./utils.js"; | ||
| import loadCodeDefault from "./module-types.js"; | ||
| import pathPatternToRegex from "../pattern-to-regex.js"; | ||
| import ConfigError from "../../errors/config-error.js"; | ||
| import * as fs from "../../gensync-utils/fs.js"; | ||
| import { createRequire } from "node:module"; | ||
| import { endHiddenCallStack } from "../../errors/rewrite-stack-trace.js"; | ||
| import { isAsync } from "../../gensync-utils/async.js"; | ||
| const require = createRequire(import.meta.url); | ||
| const debug = createDebug("babel:config:loading:files:configuration"); | ||
| export const ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json", "babel.config.cts", "babel.config.ts", "babel.config.mts"]; | ||
| const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json", ".babelrc.cts"]; | ||
| const BABELIGNORE_FILENAME = ".babelignore"; | ||
| const runConfig = makeWeakCache(function* runConfig(options, cache) { | ||
| yield* []; | ||
| return { | ||
| options: endHiddenCallStack(options)(makeConfigAPI(cache)), | ||
| cacheNeedsConfiguration: !cache.configured() | ||
| }; | ||
| }); | ||
| function* readConfigCode(filepath, data) { | ||
| if (!nodeFs.existsSync(filepath)) return null; | ||
| let options = yield* loadCodeDefault(filepath, (yield* isAsync()) ? "auto" : "require", "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously " + "or when using the Node.js `--experimental-require-module` flag.", "You appear to be using a configuration file that contains top-level " + "await, which is only supported when running Babel asynchronously."); | ||
| let cacheNeedsConfiguration = false; | ||
| if (typeof options === "function") { | ||
| ({ | ||
| options, | ||
| cacheNeedsConfiguration | ||
| } = yield* runConfig(options, data)); | ||
| } | ||
| if (!options || typeof options !== "object" || Array.isArray(options)) { | ||
| throw new ConfigError(`Configuration should be an exported JavaScript object.`, filepath); | ||
| } | ||
| if (typeof options.then === "function") { | ||
| options.catch?.(() => {}); | ||
| throw new ConfigError(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`, filepath); | ||
| } | ||
| if (cacheNeedsConfiguration) throwConfigError(filepath); | ||
| return buildConfigFileObject(options, filepath); | ||
| } | ||
| const cfboaf = new WeakMap(); | ||
| function buildConfigFileObject(options, filepath) { | ||
| let configFilesByFilepath = cfboaf.get(options); | ||
| if (!configFilesByFilepath) { | ||
| cfboaf.set(options, configFilesByFilepath = new Map()); | ||
| } | ||
| let configFile = configFilesByFilepath.get(filepath); | ||
| if (!configFile) { | ||
| configFile = { | ||
| filepath, | ||
| dirname: path.dirname(filepath), | ||
| options | ||
| }; | ||
| configFilesByFilepath.set(filepath, configFile); | ||
| } | ||
| return configFile; | ||
| } | ||
| const packageToBabelConfig = makeWeakCacheSync(file => { | ||
| const babel = file.options.babel; | ||
| if (babel === undefined) return null; | ||
| if (typeof babel !== "object" || Array.isArray(babel) || babel === null) { | ||
| throw new ConfigError(`.babel property must be an object`, file.filepath); | ||
| } | ||
| return { | ||
| filepath: file.filepath, | ||
| dirname: file.dirname, | ||
| options: babel | ||
| }; | ||
| }); | ||
| const readConfigJSON5 = makeStaticFileCache((filepath, content) => { | ||
| let options; | ||
| try { | ||
| options = json5.parse(content); | ||
| } catch (err) { | ||
| throw new ConfigError(`Error while parsing config - ${err.message}`, filepath); | ||
| } | ||
| if (!options) throw new ConfigError(`No config detected`, filepath); | ||
| if (typeof options !== "object") { | ||
| throw new ConfigError(`Config returned typeof ${typeof options}`, filepath); | ||
| } | ||
| if (Array.isArray(options)) { | ||
| throw new ConfigError(`Expected config object but found array`, filepath); | ||
| } | ||
| delete options.$schema; | ||
| return { | ||
| filepath, | ||
| dirname: path.dirname(filepath), | ||
| options | ||
| }; | ||
| }); | ||
| const readIgnoreConfig = makeStaticFileCache((filepath, content) => { | ||
| const ignoreDir = path.dirname(filepath); | ||
| const ignorePatterns = content.split("\n").map(line => line.replace(/^#.*$/, "").trim()).filter(Boolean); | ||
| for (const pattern of ignorePatterns) { | ||
| if (pattern.startsWith("!")) { | ||
| throw new ConfigError(`Negation of file paths is not supported.`, filepath); | ||
| } | ||
| } | ||
| return { | ||
| filepath, | ||
| dirname: path.dirname(filepath), | ||
| ignore: ignorePatterns.map(pattern => pathPatternToRegex(pattern, ignoreDir)) | ||
| }; | ||
| }); | ||
| export function findConfigUpwards(rootDir) { | ||
| let dirname = rootDir; | ||
| for (;;) { | ||
| for (const filename of ROOT_CONFIG_FILENAMES) { | ||
| if (nodeFs.existsSync(path.join(dirname, filename))) { | ||
| return dirname; | ||
| } | ||
| } | ||
| const nextDir = path.dirname(dirname); | ||
| if (dirname === nextDir) break; | ||
| dirname = nextDir; | ||
| } | ||
| return null; | ||
| } | ||
| export function* findRelativeConfig(packageData, envName, caller) { | ||
| let config = null; | ||
| let ignore = null; | ||
| const dirname = path.dirname(packageData.filepath); | ||
| for (const loc of packageData.directories) { | ||
| if (!config) { | ||
| config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, packageData.pkg?.dirname === loc ? packageToBabelConfig(packageData.pkg) : null); | ||
| } | ||
| if (!ignore) { | ||
| const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME); | ||
| ignore = yield* readIgnoreConfig(ignoreLoc); | ||
| if (ignore) { | ||
| debug("Found ignore %o from %o.", ignore.filepath, dirname); | ||
| } | ||
| } | ||
| } | ||
| return { | ||
| config, | ||
| ignore | ||
| }; | ||
| } | ||
| export function findRootConfig(dirname, envName, caller) { | ||
| return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller); | ||
| } | ||
| function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) { | ||
| const configs = yield* gensync.all(names.map(filename => readConfig(path.join(dirname, filename), envName, caller))); | ||
| const config = configs.reduce((previousConfig, config) => { | ||
| if (config && previousConfig) { | ||
| throw new ConfigError(`Multiple configuration files found. Please remove one:\n` + ` - ${path.basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`); | ||
| } | ||
| return config || previousConfig; | ||
| }, previousConfig); | ||
| if (config) { | ||
| debug("Found configuration %o from %o.", config.filepath, dirname); | ||
| } | ||
| return config; | ||
| } | ||
| export function* loadConfig(name, dirname, envName, caller) { | ||
| const filepath = require.resolve(name, { | ||
| paths: [dirname] | ||
| }); | ||
| const conf = yield* readConfig(filepath, envName, caller); | ||
| if (!conf) { | ||
| throw new ConfigError(`Config file contains no configuration data`, filepath); | ||
| } | ||
| debug("Loaded config %o from %o.", name, dirname); | ||
| return conf; | ||
| } | ||
| function readConfig(filepath, envName, caller) { | ||
| const ext = path.extname(filepath); | ||
| switch (ext) { | ||
| case ".js": | ||
| case ".cjs": | ||
| case ".mjs": | ||
| case ".ts": | ||
| case ".cts": | ||
| case ".mts": | ||
| return readConfigCode(filepath, { | ||
| envName, | ||
| caller | ||
| }); | ||
| default: | ||
| return readConfigJSON5(filepath); | ||
| } | ||
| } | ||
| export function* resolveShowConfigPath(dirname) { | ||
| const targetPath = process.env.BABEL_SHOW_CONFIG_FOR; | ||
| if (targetPath != null) { | ||
| const absolutePath = path.resolve(dirname, targetPath); | ||
| const stats = yield* fs.stat(absolutePath); | ||
| if (!stats.isFile()) { | ||
| throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`); | ||
| } | ||
| return absolutePath; | ||
| } | ||
| return null; | ||
| } | ||
| function throwConfigError(filepath) { | ||
| throw new ConfigError(`\ | ||
| Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured | ||
| for various types of caching, using the first param of their handler functions: | ||
| module.exports = function(api) { | ||
| // The API exposes the following: | ||
| // Cache the returned value forever and don't call this function again. | ||
| api.cache(true); | ||
| // Don't cache at all. Not recommended because it will be very slow. | ||
| api.cache(false); | ||
| // Cached based on the value of some function. If this function returns a value different from | ||
| // a previously-encountered value, the plugins will re-evaluate. | ||
| var env = api.cache(() => process.env.NODE_ENV); | ||
| // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for | ||
| // any possible NODE_ENV value that might come up during plugin execution. | ||
| var isProd = api.cache(() => process.env.NODE_ENV === "production"); | ||
| // .cache(fn) will perform a linear search though instances to find the matching plugin based | ||
| // based on previous instantiated plugins. If you want to recreate the plugin and discard the | ||
| // previous instance whenever something changes, you may use: | ||
| var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production"); | ||
| // Note, we also expose the following more-verbose versions of the above examples: | ||
| api.cache.forever(); // api.cache(true) | ||
| api.cache.never(); // api.cache(false) | ||
| api.cache.using(fn); // api.cache(fn) | ||
| // Return the value that will be cached. | ||
| return { }; | ||
| };`, filepath); | ||
| } | ||
| //# sourceMappingURL=configuration.js.map |
| {"version":3,"names":["createDebug","nodeFs","path","json5","gensync","makeWeakCache","makeWeakCacheSync","makeConfigAPI","makeStaticFileCache","loadCodeDefault","pathPatternToRegex","ConfigError","fs","createRequire","endHiddenCallStack","isAsync","require","import","meta","url","debug","ROOT_CONFIG_FILENAMES","RELATIVE_CONFIG_FILENAMES","BABELIGNORE_FILENAME","runConfig","options","cache","cacheNeedsConfiguration","configured","readConfigCode","filepath","data","existsSync","Array","isArray","then","catch","throwConfigError","buildConfigFileObject","cfboaf","WeakMap","configFilesByFilepath","get","set","Map","configFile","dirname","packageToBabelConfig","file","babel","undefined","readConfigJSON5","content","parse","err","message","$schema","readIgnoreConfig","ignoreDir","ignorePatterns","split","map","line","replace","trim","filter","Boolean","pattern","startsWith","ignore","findConfigUpwards","rootDir","filename","join","nextDir","findRelativeConfig","packageData","envName","caller","config","loc","directories","loadOneConfig","pkg","ignoreLoc","findRootConfig","names","previousConfig","configs","all","readConfig","reduce","basename","loadConfig","name","resolve","paths","conf","ext","extname","resolveShowConfigPath","targetPath","process","env","BABEL_SHOW_CONFIG_FOR","absolutePath","stats","stat","isFile","Error"],"sources":["../../../src/config/files/configuration.ts"],"sourcesContent":["import { createDebug } from \"obug\";\nimport nodeFs from \"node:fs\";\nimport path from \"node:path\";\nimport json5 from \"json5\";\nimport gensync from \"gensync\";\nimport type { Handler } from \"gensync\";\nimport { makeWeakCache, makeWeakCacheSync } from \"../caching.ts\";\nimport type { CacheConfigurator } from \"../caching.ts\";\nimport { makeConfigAPI } from \"../helpers/config-api.ts\";\nimport type { ConfigAPI } from \"../helpers/config-api.ts\";\nimport { makeStaticFileCache } from \"./utils.ts\";\nimport loadCodeDefault from \"./module-types.ts\";\nimport pathPatternToRegex from \"../pattern-to-regex.ts\";\nimport type { FilePackageData, RelativeConfig, ConfigFile } from \"./types.ts\";\nimport type { CallerMetadata, InputOptions } from \"../validation/options.ts\";\nimport ConfigError from \"../../errors/config-error.ts\";\n\nimport * as fs from \"../../gensync-utils/fs.ts\";\n\nimport { createRequire } from \"node:module\";\nimport { endHiddenCallStack } from \"../../errors/rewrite-stack-trace.ts\";\nimport { isAsync } from \"../../gensync-utils/async.ts\";\nconst require = createRequire(import.meta.url);\n\nconst debug = createDebug(\"babel:config:loading:files:configuration\");\n\nexport const ROOT_CONFIG_FILENAMES = [\n \"babel.config.js\",\n \"babel.config.cjs\",\n \"babel.config.mjs\",\n \"babel.config.json\",\n \"babel.config.cts\",\n \"babel.config.ts\",\n \"babel.config.mts\",\n];\nconst RELATIVE_CONFIG_FILENAMES = [\n \".babelrc\",\n \".babelrc.js\",\n \".babelrc.cjs\",\n \".babelrc.mjs\",\n \".babelrc.json\",\n \".babelrc.cts\",\n];\n\nconst BABELIGNORE_FILENAME = \".babelignore\";\n\ntype ConfigCacheData = {\n envName: string;\n caller: CallerMetadata | undefined;\n};\n\nconst runConfig = makeWeakCache(function* runConfig(\n options: Function,\n cache: CacheConfigurator<ConfigCacheData>,\n): Handler<{\n options: InputOptions | null;\n cacheNeedsConfiguration: boolean;\n}> {\n // if we want to make it possible to use async configs\n yield* [];\n\n return {\n options: endHiddenCallStack(options as any as (api: ConfigAPI) => unknown)(\n makeConfigAPI(cache),\n ),\n cacheNeedsConfiguration: !cache.configured(),\n };\n});\n\nfunction* readConfigCode(\n filepath: string,\n data: ConfigCacheData,\n): Handler<ConfigFile | null> {\n if (!nodeFs.existsSync(filepath)) return null;\n\n let options = yield* loadCodeDefault(\n filepath,\n (yield* isAsync()) ? \"auto\" : \"require\",\n \"You appear to be using a native ECMAScript module configuration \" +\n \"file, which is only supported when running Babel asynchronously \" +\n \"or when using the Node.js `--experimental-require-module` flag.\",\n \"You appear to be using a configuration file that contains top-level \" +\n \"await, which is only supported when running Babel asynchronously.\",\n );\n\n let cacheNeedsConfiguration = false;\n if (typeof options === \"function\") {\n ({ options, cacheNeedsConfiguration } = yield* runConfig(options, data));\n }\n\n if (!options || typeof options !== \"object\" || Array.isArray(options)) {\n throw new ConfigError(\n `Configuration should be an exported JavaScript object.`,\n filepath,\n );\n }\n\n // @ts-expect-error todo(flow->ts)\n if (typeof options.then === \"function\") {\n // @ts-expect-error We use ?. in case options is a thenable but not a promise\n options.catch?.(() => {});\n throw new ConfigError(\n `You appear to be using an async configuration, ` +\n `which your current version of Babel does not support. ` +\n `We may add support for this in the future, ` +\n `but if you're on the most recent version of @babel/core and still ` +\n `seeing this error, then you'll need to synchronously return your config.`,\n filepath,\n );\n }\n\n if (cacheNeedsConfiguration) throwConfigError(filepath);\n\n return buildConfigFileObject(options, filepath);\n}\n\n// We cache the generated ConfigFile object rather than creating a new one\n// every time, so that it can be used as a cache key in other functions.\nconst cfboaf /* configFilesByOptionsAndFilepath */ = new WeakMap<\n InputOptions,\n Map<string, ConfigFile>\n>();\nfunction buildConfigFileObject(\n options: InputOptions,\n filepath: string,\n): ConfigFile {\n let configFilesByFilepath = cfboaf.get(options);\n if (!configFilesByFilepath) {\n cfboaf.set(options, (configFilesByFilepath = new Map()));\n }\n\n let configFile = configFilesByFilepath.get(filepath);\n if (!configFile) {\n configFile = {\n filepath,\n dirname: path.dirname(filepath),\n options,\n };\n configFilesByFilepath.set(filepath, configFile);\n }\n\n return configFile;\n}\n\nconst packageToBabelConfig = makeWeakCacheSync(\n (file: ConfigFile): ConfigFile | null => {\n const babel: unknown = file.options.babel;\n\n if (babel === undefined) return null;\n\n if (typeof babel !== \"object\" || Array.isArray(babel) || babel === null) {\n throw new ConfigError(`.babel property must be an object`, file.filepath);\n }\n\n return {\n filepath: file.filepath,\n dirname: file.dirname,\n options: babel,\n };\n },\n);\n\nconst readConfigJSON5 = makeStaticFileCache((filepath, content): ConfigFile => {\n let options;\n try {\n options = json5.parse(content);\n } catch (err) {\n throw new ConfigError(\n `Error while parsing config - ${err.message}`,\n filepath,\n );\n }\n\n if (!options) throw new ConfigError(`No config detected`, filepath);\n\n if (typeof options !== \"object\") {\n throw new ConfigError(`Config returned typeof ${typeof options}`, filepath);\n }\n if (Array.isArray(options)) {\n throw new ConfigError(`Expected config object but found array`, filepath);\n }\n\n delete options.$schema;\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n options,\n };\n});\n\nconst readIgnoreConfig = makeStaticFileCache((filepath, content) => {\n const ignoreDir = path.dirname(filepath);\n const ignorePatterns = content\n .split(\"\\n\")\n .map(line => line.replace(/^#.*$/, \"\").trim())\n .filter(Boolean);\n\n for (const pattern of ignorePatterns) {\n if (pattern.startsWith(\"!\")) {\n throw new ConfigError(\n `Negation of file paths is not supported.`,\n filepath,\n );\n }\n }\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n ignore: ignorePatterns.map(pattern =>\n pathPatternToRegex(pattern, ignoreDir),\n ),\n };\n});\n\nexport function findConfigUpwards(rootDir: string): string | null {\n let dirname = rootDir;\n for (;;) {\n for (const filename of ROOT_CONFIG_FILENAMES) {\n if (nodeFs.existsSync(path.join(dirname, filename))) {\n return dirname;\n }\n }\n\n const nextDir = path.dirname(dirname);\n if (dirname === nextDir) break;\n dirname = nextDir;\n }\n\n return null;\n}\n\nexport function* findRelativeConfig(\n packageData: FilePackageData,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler<RelativeConfig> {\n let config = null;\n let ignore = null;\n\n const dirname = path.dirname(packageData.filepath);\n\n for (const loc of packageData.directories) {\n if (!config) {\n config = yield* loadOneConfig(\n RELATIVE_CONFIG_FILENAMES,\n loc,\n envName,\n caller,\n packageData.pkg?.dirname === loc\n ? packageToBabelConfig(packageData.pkg)\n : null,\n );\n }\n\n if (!ignore) {\n const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);\n ignore = yield* readIgnoreConfig(ignoreLoc);\n\n if (ignore) {\n debug(\"Found ignore %o from %o.\", ignore.filepath, dirname);\n }\n }\n }\n\n return { config, ignore };\n}\n\nexport function findRootConfig(\n dirname: string,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile | null> {\n return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller);\n}\n\nfunction* loadOneConfig(\n names: string[],\n dirname: string,\n envName: string,\n caller: CallerMetadata | undefined,\n previousConfig: ConfigFile | null = null,\n): Handler<ConfigFile | null> {\n const configs = yield* gensync.all(\n names.map(filename =>\n readConfig(path.join(dirname, filename), envName, caller),\n ),\n );\n const config = configs.reduce((previousConfig: ConfigFile | null, config) => {\n if (config && previousConfig) {\n throw new ConfigError(\n `Multiple configuration files found. Please remove one:\\n` +\n ` - ${path.basename(previousConfig.filepath)}\\n` +\n ` - ${config.filepath}\\n` +\n `from ${dirname}`,\n );\n }\n\n return config || previousConfig;\n }, previousConfig);\n\n if (config) {\n debug(\"Found configuration %o from %o.\", config.filepath, dirname);\n }\n return config;\n}\n\nexport function* loadConfig(\n name: string,\n dirname: string,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile> {\n const filepath = require.resolve(name, { paths: [dirname] });\n\n const conf = yield* readConfig(filepath, envName, caller);\n if (!conf) {\n throw new ConfigError(\n `Config file contains no configuration data`,\n filepath,\n );\n }\n\n debug(\"Loaded config %o from %o.\", name, dirname);\n return conf;\n}\n\n/**\n * Read the given config file, returning the result. Returns null if no config was found, but will\n * throw if there are parsing errors while loading a config.\n */\nfunction readConfig(\n filepath: string,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile | null> {\n const ext = path.extname(filepath);\n switch (ext) {\n case \".js\":\n case \".cjs\":\n case \".mjs\":\n case \".ts\":\n case \".cts\":\n case \".mts\":\n return readConfigCode(filepath, { envName, caller });\n default:\n return readConfigJSON5(filepath);\n }\n}\n\nexport function* resolveShowConfigPath(\n dirname: string,\n): Handler<string | null> {\n const targetPath = process.env.BABEL_SHOW_CONFIG_FOR;\n if (targetPath != null) {\n const absolutePath = path.resolve(dirname, targetPath);\n const stats = yield* fs.stat(absolutePath);\n if (!stats.isFile()) {\n throw new Error(\n `${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`,\n );\n }\n return absolutePath;\n }\n return null;\n}\n\nfunction throwConfigError(filepath: string): never {\n throw new ConfigError(\n `\\\nCaching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured\nfor various types of caching, using the first param of their handler functions:\n\nmodule.exports = function(api) {\n // The API exposes the following:\n\n // Cache the returned value forever and don't call this function again.\n api.cache(true);\n\n // Don't cache at all. Not recommended because it will be very slow.\n api.cache(false);\n\n // Cached based on the value of some function. If this function returns a value different from\n // a previously-encountered value, the plugins will re-evaluate.\n var env = api.cache(() => process.env.NODE_ENV);\n\n // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for\n // any possible NODE_ENV value that might come up during plugin execution.\n var isProd = api.cache(() => process.env.NODE_ENV === \"production\");\n\n // .cache(fn) will perform a linear search though instances to find the matching plugin based\n // based on previous instantiated plugins. If you want to recreate the plugin and discard the\n // previous instance whenever something changes, you may use:\n var isProd = api.cache.invalidate(() => process.env.NODE_ENV === \"production\");\n\n // Note, we also expose the following more-verbose versions of the above examples:\n api.cache.forever(); // api.cache(true)\n api.cache.never(); // api.cache(false)\n api.cache.using(fn); // api.cache(fn)\n\n // Return the value that will be cached.\n return { };\n};`,\n filepath,\n );\n}\n"],"mappings":"AAAA,SAASA,WAAW,QAAQ,MAAM;AAClC,OAAOC,MAAM,MAAM,SAAS;AAC5B,OAAOC,IAAI,MAAM,WAAW;AAC5B,OAAOC,KAAK,MAAM,OAAO;AACzB,OAAOC,OAAO,MAAM,SAAS;AAE7B,SAASC,aAAa,EAAEC,iBAAiB,QAAQ,eAAe;AAEhE,SAASC,aAAa,QAAQ,0BAA0B;AAExD,SAASC,mBAAmB,QAAQ,YAAY;AAChD,OAAOC,eAAe,MAAM,mBAAmB;AAC/C,OAAOC,kBAAkB,MAAM,wBAAwB;AAGvD,OAAOC,WAAW,MAAM,8BAA8B;AAEtD,OAAO,KAAKC,EAAE,MAAM,2BAA2B;AAE/C,SAASC,aAAa,QAAQ,aAAa;AAC3C,SAASC,kBAAkB,QAAQ,qCAAqC;AACxE,SAASC,OAAO,QAAQ,8BAA8B;AACtD,MAAMC,OAAO,GAAGH,aAAa,CAACI,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;AAE9C,MAAMC,KAAK,GAAGpB,WAAW,CAAC,0CAA0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,CAAC;IACtD;MACE,OAAO3B,eAAe,CAACrB,QAAQ,CAAC;EACpC;AACF;AAEA,OAAO,UAAUsE,qBAAqBA,CACpCtD,OAAe,EACS;EACxB,MAAMuD,UAAU,GAAGC,OAAO,CAACC,GAAG,CAACC,qBAAqB;EACpD,IAAIH,UAAU,IAAI,IAAI,EAAE;IACtB,MAAMI,YAAY,GAAGvG,IAAI,CAAC6F,OAAO,CAACjD,OAAO,EAAEuD,UAAU,CAAC;IACtD,MAAMK,KAAK,GAAG,OAAO9F,EAAE,CAAC+F,IAAI,CAACF,YAAY,CAAC;IAC1C,IAAI,CAACC,KAAK,CAACE,MAAM,CAAC,CAAC,EAAE;MACnB,MAAM,IAAIC,KAAK,CACb,GAAGJ,YAAY,sFACjB,CAAC;IACH;IACA,OAAOA,YAAY;EACrB;EACA,OAAO,IAAI;AACb;AAEA,SAASpE,gBAAgBA,CAACP,QAAgB,EAAS;EACjD,MAAM,IAAInB,WAAW,CACnB;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,EACCmB,QACF,CAAC;AACH","ignoreList":[]} |
| module.exports = function import_(filepath) { | ||
| return import(filepath); | ||
| }; | ||
| //# sourceMappingURL=import.cjs.map |
| {"version":3,"names":["module","exports","import_","filepath"],"sources":["../../../src/config/files/import.cjs"],"sourcesContent":["// We keep this in a separate file so that in older node versions, where\n// import() isn't supported, we can try/catch around the require() call\n// when loading this file.\n\nmodule.exports = function import_(filepath) {\n return import(filepath);\n};\n"],"mappings":"AAIAA,MAAM,CAACC,OAAO,GAAG,SAASC,OAAOA,CAACC,QAAQ,EAAE;EAC1C,OAAO,OAAOA,QAAQ,CAAC;AACzB,CAAC","ignoreList":[]} |
| import { isAsync, waitFor } from "../../gensync-utils/async.js"; | ||
| import path from "node:path"; | ||
| import { pathToFileURL } from "node:url"; | ||
| import { createRequire } from "node:module"; | ||
| import { createDebug } from "obug"; | ||
| import { endHiddenCallStack } from "../../errors/rewrite-stack-trace.js"; | ||
| import ConfigError from "../../errors/config-error.js"; | ||
| import { transformFileSync } from "../../transform-file.js"; | ||
| const debug = createDebug("babel:config:loading:files:module-types"); | ||
| const require = createRequire(import.meta.url); | ||
| const LOADING_CJS_FILES = new Set(); | ||
| function loadCjsDefault(filepath) { | ||
| if (LOADING_CJS_FILES.has(filepath)) { | ||
| debug("Auto-ignoring usage of config %o.", filepath); | ||
| return {}; | ||
| } | ||
| let module; | ||
| try { | ||
| LOADING_CJS_FILES.add(filepath); | ||
| module = endHiddenCallStack(require)(filepath); | ||
| } finally { | ||
| LOADING_CJS_FILES.delete(filepath); | ||
| } | ||
| return module != null && (module.__esModule || module[Symbol.toStringTag] === "Module") ? module.default : module; | ||
| } | ||
| const loadMjsFromPath = endHiddenCallStack(async function loadMjsFromPath(filepath) { | ||
| const url = pathToFileURL(filepath).toString() + "?import"; | ||
| return await import(url); | ||
| }); | ||
| const tsNotSupportedError = ext => `\ | ||
| You are using a ${ext} config file, but Babel only supports transpiling .cts configs. Either: | ||
| - Use a .cts config file | ||
| - Update to Node.js 23.6.0, which has native TypeScript support | ||
| - Install tsx to transpile ${ext} files on the fly\ | ||
| `; | ||
| const SUPPORTED_EXTENSIONS = { | ||
| ".js": "unknown", | ||
| ".mjs": "esm", | ||
| ".cjs": "cjs", | ||
| ".ts": "unknown", | ||
| ".mts": "esm", | ||
| ".cts": "cjs" | ||
| }; | ||
| const asyncModules = new Set(); | ||
| export default function* loadCodeDefault(filepath, loader, esmError, tlaError) { | ||
| let async; | ||
| const ext = path.extname(filepath); | ||
| const isTS = ext === ".ts" || ext === ".cts" || ext === ".mts"; | ||
| const type = SUPPORTED_EXTENSIONS[Object.hasOwn(SUPPORTED_EXTENSIONS, ext) ? ext : ".js"]; | ||
| const pattern = `${loader} ${type}`; | ||
| switch (pattern) { | ||
| case "require cjs": | ||
| case "auto cjs": | ||
| if (isTS) { | ||
| return ensureTsSupport(filepath, ext, () => loadCjsDefault(filepath)); | ||
| } else { | ||
| return loadCjsDefault(filepath); | ||
| } | ||
| case "auto unknown": | ||
| case "require unknown": | ||
| case "require esm": | ||
| try { | ||
| if (isTS) { | ||
| return ensureTsSupport(filepath, ext, () => loadCjsDefault(filepath)); | ||
| } else { | ||
| return loadCjsDefault(filepath); | ||
| } | ||
| } catch (e) { | ||
| if (e.code === "ERR_REQUIRE_ASYNC_MODULE" || e.code === "ERR_REQUIRE_CYCLE_MODULE" && asyncModules.has(filepath)) { | ||
| asyncModules.add(filepath); | ||
| if (!(async ??= yield* isAsync())) { | ||
| throw new ConfigError(tlaError, filepath); | ||
| } | ||
| } else if (e.code === "ERR_REQUIRE_ESM") {} else { | ||
| throw e; | ||
| } | ||
| } | ||
| case "auto esm": | ||
| if (async ??= yield* isAsync()) { | ||
| const promise = isTS ? ensureTsSupport(filepath, ext, () => loadMjsFromPath(filepath)) : loadMjsFromPath(filepath); | ||
| return (yield* waitFor(promise)).default; | ||
| } | ||
| if (isTS) { | ||
| throw new ConfigError(tsNotSupportedError(ext), filepath); | ||
| } else { | ||
| throw new ConfigError(esmError, filepath); | ||
| } | ||
| default: | ||
| throw new Error("Internal Babel error: unreachable code."); | ||
| } | ||
| } | ||
| function ensureTsSupport(filepath, ext, callback) { | ||
| if (process.features.typescript || require.extensions[".ts"] || require.extensions[".cts"] || require.extensions[".mts"]) { | ||
| return callback(); | ||
| } | ||
| if (ext !== ".cts") { | ||
| throw new ConfigError(tsNotSupportedError(ext), filepath); | ||
| } | ||
| const opts = { | ||
| babelrc: false, | ||
| configFile: false, | ||
| sourceType: "unambiguous", | ||
| sourceMaps: "inline", | ||
| sourceFileName: path.basename(filepath), | ||
| presets: [[getTSPreset(filepath), { | ||
| onlyRemoveTypeImports: true, | ||
| optimizeConstEnums: true | ||
| }]] | ||
| }; | ||
| let handler = function (m, filename) { | ||
| if (handler && filename.endsWith(".cts")) { | ||
| return m._compile(transformFileSync(filename, { | ||
| ...opts, | ||
| filename | ||
| }).code, filename); | ||
| } | ||
| return require.extensions[".js"](m, filename); | ||
| }; | ||
| require.extensions[ext] = handler; | ||
| try { | ||
| return callback(); | ||
| } finally { | ||
| if (require.extensions[ext] === handler) delete require.extensions[ext]; | ||
| handler = undefined; | ||
| } | ||
| } | ||
| function getTSPreset(filepath) { | ||
| try { | ||
| return require("@babel/preset-typescript"); | ||
| } catch (error) { | ||
| if (error.code !== "MODULE_NOT_FOUND") throw error; | ||
| const message = "You appear to be using a .cts file as Babel configuration, but the `@babel/preset-typescript` package was not found: please install it!"; | ||
| throw new ConfigError(message, filepath); | ||
| } | ||
| } | ||
| //# sourceMappingURL=module-types.js.map |
| {"version":3,"names":["isAsync","waitFor","path","pathToFileURL","createRequire","createDebug","endHiddenCallStack","ConfigError","transformFileSync","debug","require","import","meta","url","LOADING_CJS_FILES","Set","loadCjsDefault","filepath","has","module","add","delete","__esModule","Symbol","toStringTag","default","loadMjsFromPath","toString","tsNotSupportedError","ext","SUPPORTED_EXTENSIONS","asyncModules","loadCodeDefault","loader","esmError","tlaError","async","extname","isTS","type","Object","hasOwn","pattern","ensureTsSupport","e","code","promise","Error","callback","process","features","typescript","extensions","opts","babelrc","configFile","sourceType","sourceMaps","sourceFileName","basename","presets","getTSPreset","onlyRemoveTypeImports","optimizeConstEnums","handler","m","filename","endsWith","_compile","undefined","error","message"],"sources":["../../../src/config/files/module-types.ts"],"sourcesContent":["import { isAsync, waitFor } from \"../../gensync-utils/async.ts\";\nimport type { Handler } from \"gensync\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport { createDebug } from \"obug\";\n\nimport { endHiddenCallStack } from \"../../errors/rewrite-stack-trace.ts\";\nimport ConfigError from \"../../errors/config-error.ts\";\n\nimport type { InputOptions } from \"../index.ts\";\nimport { transformFileSync } from \"../../transform-file.ts\";\n\nconst debug = createDebug(\"babel:config:loading:files:module-types\");\n\nconst require = createRequire(import.meta.url);\n\nconst LOADING_CJS_FILES = new Set();\n\nfunction loadCjsDefault(filepath: string) {\n // The `require()` call below can make this code reentrant if a require hook\n // like @babel/register has been loaded into the system. That would cause\n // Babel to attempt to compile the `.babelrc.js` file as it loads below. To\n // cover this case, we auto-ignore re-entrant config processing. ESM loaders\n // do not have this problem, because loaders do not apply to themselves.\n if (LOADING_CJS_FILES.has(filepath)) {\n debug(\"Auto-ignoring usage of config %o.\", filepath);\n return {};\n }\n\n let module;\n try {\n LOADING_CJS_FILES.add(filepath);\n module = endHiddenCallStack(require)(filepath);\n } finally {\n LOADING_CJS_FILES.delete(filepath);\n }\n\n return module != null &&\n (module.__esModule || module[Symbol.toStringTag] === \"Module\")\n ? module.default\n : module;\n}\n\nconst loadMjsFromPath = endHiddenCallStack(async function loadMjsFromPath(\n filepath: string,\n) {\n // Add ?import as a workaround for https://github.com/nodejs/node/issues/55500\n const url = pathToFileURL(filepath).toString() + \"?import\";\n\n return await import(url);\n});\n\nconst tsNotSupportedError = (ext: string) => `\\\nYou are using a ${ext} config file, but Babel only supports transpiling .cts configs. Either:\n- Use a .cts config file\n- Update to Node.js 23.6.0, which has native TypeScript support\n- Install tsx to transpile ${ext} files on the fly\\\n`;\n\nconst SUPPORTED_EXTENSIONS = {\n \".js\": \"unknown\",\n \".mjs\": \"esm\",\n \".cjs\": \"cjs\",\n \".ts\": \"unknown\",\n \".mts\": \"esm\",\n \".cts\": \"cjs\",\n} as const;\n\nconst asyncModules = new Set();\n\nexport default function* loadCodeDefault(\n filepath: string,\n loader: \"require\" | \"auto\",\n esmError: string,\n tlaError: string,\n): Handler<unknown> {\n let async;\n\n const ext = path.extname(filepath);\n const isTS = ext === \".ts\" || ext === \".cts\" || ext === \".mts\";\n\n const type =\n SUPPORTED_EXTENSIONS[\n Object.hasOwn(SUPPORTED_EXTENSIONS, ext)\n ? (ext as keyof typeof SUPPORTED_EXTENSIONS)\n : (\".js\" as const)\n ];\n\n const pattern = `${loader} ${type}` as const;\n switch (pattern) {\n case \"require cjs\":\n case \"auto cjs\":\n if (isTS) {\n return ensureTsSupport(filepath, ext, () => loadCjsDefault(filepath));\n } else {\n return loadCjsDefault(filepath);\n }\n\n case \"auto unknown\":\n case \"require unknown\":\n case \"require esm\":\n try {\n if (isTS) {\n return ensureTsSupport(filepath, ext, () => loadCjsDefault(filepath));\n } else {\n return loadCjsDefault(filepath);\n }\n } catch (e) {\n if (\n e.code === \"ERR_REQUIRE_ASYNC_MODULE\" ||\n // Node.js 13.0.0 throws ERR_REQUIRE_CYCLE_MODULE instead of\n // ERR_REQUIRE_ASYNC_MODULE when requiring a module a second time\n // https://github.com/nodejs/node/issues/55516\n // This `asyncModules` won't catch all of such cases, but it will\n // at least catch those caused by Babel trying to load a module twice.\n (e.code === \"ERR_REQUIRE_CYCLE_MODULE\" && asyncModules.has(filepath))\n ) {\n asyncModules.add(filepath);\n if (!(async ??= yield* isAsync())) {\n throw new ConfigError(tlaError, filepath);\n }\n // fall through: require() failed due to TLA\n } else if (e.code === \"ERR_REQUIRE_ESM\") {\n // fall through: require() failed due to ESM\n } else {\n throw e;\n }\n }\n // fall through: require() failed due to ESM or TLA, try import()\n case \"auto esm\":\n if ((async ??= yield* isAsync())) {\n const promise = isTS\n ? ensureTsSupport(filepath, ext, () => loadMjsFromPath(filepath))\n : loadMjsFromPath(filepath);\n\n return (yield* waitFor(promise)).default;\n }\n if (isTS) {\n throw new ConfigError(tsNotSupportedError(ext), filepath);\n } else {\n throw new ConfigError(esmError, filepath);\n }\n default:\n throw new Error(\"Internal Babel error: unreachable code.\");\n }\n}\n\nfunction ensureTsSupport<T>(\n filepath: string,\n ext: string,\n callback: () => T,\n): T {\n if (\n process.features.typescript ||\n require.extensions[\".ts\"] ||\n require.extensions[\".cts\"] ||\n require.extensions[\".mts\"]\n ) {\n return callback();\n }\n\n if (ext !== \".cts\") {\n throw new ConfigError(tsNotSupportedError(ext), filepath);\n }\n\n const opts: InputOptions = {\n babelrc: false,\n configFile: false,\n sourceType: \"unambiguous\",\n sourceMaps: \"inline\",\n sourceFileName: path.basename(filepath),\n presets: [\n [\n getTSPreset(filepath),\n {\n onlyRemoveTypeImports: true,\n optimizeConstEnums: true,\n },\n ],\n ],\n };\n\n let handler: NodeJS.RequireExtensions[\"\"] = function (m, filename) {\n // If we want to support `.ts`, `.d.ts` must be handled specially.\n if (handler && filename.endsWith(\".cts\")) {\n // @ts-expect-error Undocumented API\n return m._compile(\n transformFileSync(filename, {\n ...opts,\n filename,\n }).code,\n filename,\n );\n }\n return require.extensions[\".js\"](m, filename);\n };\n require.extensions[ext] = handler;\n\n try {\n return callback();\n } finally {\n if (require.extensions[ext] === handler) delete require.extensions[ext];\n handler = undefined;\n }\n}\n\nfunction getTSPreset(filepath: string) {\n try {\n // eslint-disable-next-line import/no-extraneous-dependencies\n return require(\"@babel/preset-typescript\");\n } catch (error) {\n if (error.code !== \"MODULE_NOT_FOUND\") throw error;\n\n const message =\n \"You appear to be using a .cts file as Babel configuration, but the `@babel/preset-typescript` package was not found: please install it!\";\n\n throw new ConfigError(message, filepath);\n }\n}\n"],"mappings":"AAAA,SAASA,OAAO,EAAEC,OAAO,QAAQ,8BAA8B;AAE/D,OAAOC,IAAI,MAAM,WAAW;AAC5B,SAASC,aAAa,QAAQ,UAAU;AACxC,SAASC,aAAa,QAAQ,aAAa;AAC3C,SAASC,WAAW,QAAQ,MAAM;AAElC,SAASC,kBAAkB,QAAQ,qCAAqC;AACxE,OAAOC,WAAW,MAAM,8BAA8B;AAGtD,SAASC,iBAAiB,QAAQ,yBAAyB;AAE3D,MAAMC,KAAK,GAAGJ,WAAW,CAAC,yCAAyC,CAAC;AAEpE,MAAMK,OAAO,GAAGN,aAAa,CAACO,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC;AAE9C,MAAMC,iBAAiB,GAAG,IAAIC,GAAG,CAAC,CAAC;AAEnC,SAASC,cAAcA,CAACC,QAAgB,EAAE;EAMx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,CAAC,EACrB;MACE6C,qBAAqB,EAAE,IAAI;MAC3BC,kBAAkB,EAAE;IACtB,CAAC,CACF;EAEL,CAAC;EAED,IAAIC,OAAqC,GAAG,SAAAA,CAAUC,CAAC,EAAEC,QAAQ,EAAE;IAEjE,IAAIF,OAAO,IAAIE,QAAQ,CAACC,QAAQ,CAAC,MAAM,CAAC,EAAE;MAExC,OAAOF,CAAC,CAACG,QAAQ,CACf5D,iBAAiB,CAAC0D,QAAQ,EAAE;QAC1B,GAAGb,IAAI;QACPa;MACF,CAAC,CAAC,CAACrB,IAAI,EACPqB,QACF,CAAC;IACH;IACA,OAAOxD,OAAO,CAAC0C,UAAU,CAAC,KAAK,CAAC,CAACa,CAAC,EAAEC,QAAQ,CAAC;EAC/C,CAAC;EACDxD,OAAO,CAAC0C,UAAU,CAACvB,GAAG,CAAC,GAAGmC,OAAO;EAEjC,IAAI;IACF,OAAOhB,QAAQ,CAAC,CAAC;EACnB,CAAC,SAAS;IACR,IAAItC,OAAO,CAAC0C,UAAU,CAACvB,GAAG,CAAC,KAAKmC,OAAO,EAAE,OAAOtD,OAAO,CAAC0C,UAAU,CAACvB,GAAG,CAAC;IACvEmC,OAAO,GAAGK,SAAS;EACrB;AACF;AAEA,SAASR,WAAWA,CAAC5C,QAAgB,EAAE;EACrC,IAAI;IAEF,OAAOP,OAAO,CAAC,0BAA0B,CAAC;EAC5C,CAAC,CAAC,OAAO4D,KAAK,EAAE;IACd,IAAIA,KAAK,CAACzB,IAAI,KAAK,kBAAkB,EAAE,MAAMyB,KAAK;IAElD,MAAMC,OAAO,GACX,yIAAyI;IAE3I,MAAM,IAAIhE,WAAW,CAACgE,OAAO,EAAEtD,QAAQ,CAAC;EAC1C;AACF","ignoreList":[]} |
| import path from "node:path"; | ||
| import { makeStaticFileCache } from "./utils.js"; | ||
| import ConfigError from "../../errors/config-error.js"; | ||
| const PACKAGE_FILENAME = "package.json"; | ||
| const readConfigPackage = makeStaticFileCache((filepath, content) => { | ||
| let options; | ||
| try { | ||
| options = JSON.parse(content); | ||
| } catch (err) { | ||
| throw new ConfigError(`Error while parsing JSON - ${err.message}`, filepath); | ||
| } | ||
| if (!options) throw new Error(`${filepath}: No config detected`); | ||
| if (typeof options !== "object") { | ||
| throw new ConfigError(`Config returned typeof ${typeof options}`, filepath); | ||
| } | ||
| if (Array.isArray(options)) { | ||
| throw new ConfigError(`Expected config object but found array`, filepath); | ||
| } | ||
| return { | ||
| filepath, | ||
| dirname: path.dirname(filepath), | ||
| options | ||
| }; | ||
| }); | ||
| export function* findPackageData(filepath) { | ||
| let pkg = null; | ||
| const directories = []; | ||
| let isPackage = true; | ||
| let dirname = path.dirname(filepath); | ||
| while (!pkg && path.basename(dirname) !== "node_modules") { | ||
| directories.push(dirname); | ||
| pkg = yield* readConfigPackage(path.join(dirname, PACKAGE_FILENAME)); | ||
| const nextLoc = path.dirname(dirname); | ||
| if (dirname === nextLoc) { | ||
| isPackage = false; | ||
| break; | ||
| } | ||
| dirname = nextLoc; | ||
| } | ||
| return { | ||
| filepath, | ||
| directories, | ||
| pkg, | ||
| isPackage | ||
| }; | ||
| } | ||
| //# sourceMappingURL=package.js.map |
| {"version":3,"names":["path","makeStaticFileCache","ConfigError","PACKAGE_FILENAME","readConfigPackage","filepath","content","options","JSON","parse","err","message","Error","Array","isArray","dirname","findPackageData","pkg","directories","isPackage","basename","push","join","nextLoc"],"sources":["../../../src/config/files/package.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { Handler } from \"gensync\";\nimport { makeStaticFileCache } from \"./utils.ts\";\n\nimport type { ConfigFile, FilePackageData } from \"./types.ts\";\n\nimport ConfigError from \"../../errors/config-error.ts\";\n\nconst PACKAGE_FILENAME = \"package.json\";\n\nconst readConfigPackage = makeStaticFileCache(\n (filepath, content): ConfigFile => {\n let options;\n try {\n options = JSON.parse(content) as unknown;\n } catch (err) {\n throw new ConfigError(\n `Error while parsing JSON - ${err.message}`,\n filepath,\n );\n }\n\n if (!options) throw new Error(`${filepath}: No config detected`);\n\n if (typeof options !== \"object\") {\n throw new ConfigError(\n `Config returned typeof ${typeof options}`,\n filepath,\n );\n }\n if (Array.isArray(options)) {\n throw new ConfigError(`Expected config object but found array`, filepath);\n }\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n options,\n };\n },\n);\n\n/**\n * Find metadata about the package that this file is inside of. Resolution\n * of Babel's config requires general package information to decide when to\n * search for .babelrc files\n */\nexport function* findPackageData(filepath: string): Handler<FilePackageData> {\n let pkg = null;\n const directories = [];\n let isPackage = true;\n\n let dirname = path.dirname(filepath);\n while (!pkg && path.basename(dirname) !== \"node_modules\") {\n directories.push(dirname);\n\n pkg = yield* readConfigPackage(path.join(dirname, PACKAGE_FILENAME));\n\n const nextLoc = path.dirname(dirname);\n if (dirname === nextLoc) {\n isPackage = false;\n break;\n }\n dirname = nextLoc;\n }\n\n return { filepath, directories, pkg, isPackage };\n}\n"],"mappings":"AAAA,OAAOA,IAAI,MAAM,WAAW;AAE5B,SAASC,mBAAmB,QAAQ,YAAY;AAIhD,OAAOC,WAAW,MAAM,8BAA8B;AAEtD,MAAMC,gBAAgB,GAAG,cAAc;AAEvC,MAAMC,iBAAiB,GAAGH,mBAAmB,CAC3C,CAACI,QAAQ,EAAEC,OAAO,KAAiB;EACjC,IAAIC,OAAO;EACX,IAAI;IACFA,OAAO,GAAGC,IAAI,CAACC,KAAK,CAACH,OAAO,CAAY;EAC1C,CAAC,CAAC,OAAOI,GAAG,EAAE;IACZ,MAAM,IAAIR,WAAW,CACnB,8BAA8BQ,GAAG,CAACC,OAAO,EAAE,EAC3CN,QACF,CAAC;EACH;EAEA,IAAI,CAACE,OAAO,EAAE,MAAM,IAAIK,KAAK,CAAC,GAAGP,QAAQ,sBAAsB,CAAC;EAEhE,IAAI,OAAOE,OAAO,KAAK,QAAQ,EAAE;IAC/B,MAAM,IAAIL,WAAW,CACnB,0BAA0B,OAAOK,OAAO,EAAE,EAC1CF,QACF,CAAC;EACH;EACA,IAAIQ,KAAK,CAACC,OAAO,CAACP,OAAO,CAAC,EAAE;IAC1B,MAAM,IAAIL,WAAW,CAAC,wCAAwC,EAAEG,QAAQ,CAAC;EAC3E;EAEA,OAAO;IACLA,QAAQ;IACRU,OAAO,EAAEf,IAAI,CAACe,OAAO,CAACV,QAAQ,CAAC;IAC/BE;EACF,CAAC;AACH,CACF,CAAC;AAOD,OAAO,UAAUS,eAAeA,CAACX,QAAgB,EAA4B;EAC3E,IAAIY,GAAG,GAAG,IAAI;EACd,MAAMC,WAAW,GAAG,EAAE;EACtB,IAAIC,SAAS,GAAG,IAAI;EAEpB,IAAIJ,OAAO,GAAGf,IAAI,CAACe,OAAO,CAACV,QAAQ,CAAC;EACpC,OAAO,CAACY,GAAG,IAAIjB,IAAI,CAACoB,QAAQ,CAACL,OAAO,CAAC,KAAK,cAAc,EAAE;IACxDG,WAAW,CAACG,IAAI,CAACN,OAAO,CAAC;IAEzBE,GAAG,GAAG,OAAOb,iBAAiB,CAACJ,IAAI,CAACsB,IAAI,CAACP,OAAO,EAAEZ,gBAAgB,CAAC,CAAC;IAEpE,MAAMoB,OAAO,GAAGvB,IAAI,CAACe,OAAO,CAACA,OAAO,CAAC;IACrC,IAAIA,OAAO,KAAKQ,OAAO,EAAE;MACvBJ,SAAS,GAAG,KAAK;MACjB;IACF;IACAJ,OAAO,GAAGQ,OAAO;EACnB;EAEA,OAAO;IAAElB,QAAQ;IAAEa,WAAW;IAAED,GAAG;IAAEE;EAAU,CAAC;AAClD","ignoreList":[]} |
| import { createDebug } from "obug"; | ||
| import path from "node:path"; | ||
| import { isAsync } from "../../gensync-utils/async.js"; | ||
| import loadCodeDefault from "./module-types.js"; | ||
| import { fileURLToPath, pathToFileURL } from "node:url"; | ||
| import { resolve as importMetaResolve } from "import-meta-resolve"; | ||
| import { createRequire } from "node:module"; | ||
| import { existsSync } from "node:fs"; | ||
| const require = createRequire(import.meta.url); | ||
| const debug = createDebug("babel:config:loading:files:plugins"); | ||
| const EXACT_RE = /^module:/; | ||
| const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/; | ||
| const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/; | ||
| const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/; | ||
| const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/; | ||
| const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/; | ||
| const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/; | ||
| const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/; | ||
| export const resolvePlugin = resolveStandardizedName.bind(null, "plugin"); | ||
| export const resolvePreset = resolveStandardizedName.bind(null, "preset"); | ||
| export function* loadPlugin(name, dirname) { | ||
| const { | ||
| filepath, | ||
| loader | ||
| } = resolvePlugin(name, dirname, yield* isAsync()); | ||
| const value = yield* requireModule("plugin", loader, filepath); | ||
| debug("Loaded plugin %o from %o.", name, dirname); | ||
| return { | ||
| filepath, | ||
| value | ||
| }; | ||
| } | ||
| export function* loadPreset(name, dirname) { | ||
| const { | ||
| filepath, | ||
| loader | ||
| } = resolvePreset(name, dirname, yield* isAsync()); | ||
| const value = yield* requireModule("preset", loader, filepath); | ||
| debug("Loaded preset %o from %o.", name, dirname); | ||
| return { | ||
| filepath, | ||
| value | ||
| }; | ||
| } | ||
| function standardizeName(type, name) { | ||
| if (path.isAbsolute(name)) return name; | ||
| const isPreset = type === "preset"; | ||
| return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, ""); | ||
| } | ||
| function* resolveAlternativesHelper(type, name) { | ||
| const standardizedName = standardizeName(type, name); | ||
| const { | ||
| error, | ||
| value | ||
| } = yield standardizedName; | ||
| if (!error) return value; | ||
| if (error.code !== "MODULE_NOT_FOUND") throw error; | ||
| if (standardizedName !== name && !(yield name).error) { | ||
| error.message += `\n- If you want to resolve "${name}", use "module:${name}"`; | ||
| } | ||
| if (!(yield standardizeName(type, "@babel/" + name)).error) { | ||
| error.message += `\n- Did you mean "@babel/${name}"?`; | ||
| } | ||
| const oppositeType = type === "preset" ? "plugin" : "preset"; | ||
| if (!(yield standardizeName(oppositeType, name)).error) { | ||
| error.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`; | ||
| } | ||
| if (type === "plugin") { | ||
| const transformName = standardizedName.replace("-proposal-", "-transform-"); | ||
| if (transformName !== standardizedName && !(yield transformName).error) { | ||
| error.message += `\n- Did you mean "${transformName}"?`; | ||
| } | ||
| } | ||
| error.message += `\n | ||
| Make sure that all the Babel plugins and presets you are using | ||
| are defined as dependencies or devDependencies in your package.json | ||
| file. It's possible that the missing plugin is loaded by a preset | ||
| you are using that forgot to add the plugin to its dependencies: you | ||
| can workaround this problem by explicitly adding the missing package | ||
| to your top-level package.json. | ||
| `; | ||
| throw error; | ||
| } | ||
| function tryRequireResolve(id, dirname) { | ||
| try { | ||
| if (dirname) { | ||
| return { | ||
| error: null, | ||
| value: require.resolve(id, { | ||
| paths: [dirname] | ||
| }) | ||
| }; | ||
| } else { | ||
| return { | ||
| error: null, | ||
| value: require.resolve(id) | ||
| }; | ||
| } | ||
| } catch (error) { | ||
| return { | ||
| error, | ||
| value: null | ||
| }; | ||
| } | ||
| } | ||
| function tryImportMetaResolve(id, options) { | ||
| try { | ||
| return { | ||
| error: null, | ||
| value: importMetaResolve(id, options) | ||
| }; | ||
| } catch (error) { | ||
| return { | ||
| error, | ||
| value: null | ||
| }; | ||
| } | ||
| } | ||
| function resolveStandardizedNameForRequire(type, name, dirname) { | ||
| const it = resolveAlternativesHelper(type, name); | ||
| let res = it.next(); | ||
| while (!res.done) { | ||
| res = it.next(tryRequireResolve(res.value, dirname)); | ||
| } | ||
| return { | ||
| loader: "require", | ||
| filepath: res.value | ||
| }; | ||
| } | ||
| function resolveStandardizedNameForImport(type, name, dirname) { | ||
| const parentUrl = pathToFileURL(path.join(dirname, "./babel-virtual-resolve-base.js")).href; | ||
| const it = resolveAlternativesHelper(type, name); | ||
| let res = it.next(); | ||
| while (!res.done) { | ||
| res = it.next(tryImportMetaResolve(res.value, parentUrl)); | ||
| } | ||
| return { | ||
| loader: "auto", | ||
| filepath: fileURLToPath(res.value) | ||
| }; | ||
| } | ||
| function resolveStandardizedName(type, name, dirname, allowAsync) { | ||
| if (!allowAsync) { | ||
| return resolveStandardizedNameForRequire(type, name, dirname); | ||
| } | ||
| try { | ||
| const resolved = resolveStandardizedNameForImport(type, name, dirname); | ||
| if (!existsSync(resolved.filepath)) { | ||
| throw Object.assign(new Error(`Could not resolve "${name}" in file ${dirname}.`), { | ||
| type: "MODULE_NOT_FOUND" | ||
| }); | ||
| } | ||
| return resolved; | ||
| } catch (e) { | ||
| try { | ||
| return resolveStandardizedNameForRequire(type, name, dirname); | ||
| } catch (e2) { | ||
| if (e.type === "MODULE_NOT_FOUND") throw e; | ||
| if (e2.type === "MODULE_NOT_FOUND") throw e2; | ||
| throw e; | ||
| } | ||
| } | ||
| } | ||
| function* requireModule(type, loader, name) { | ||
| try { | ||
| return yield* loadCodeDefault(name, loader, `You appear to be using a native ECMAScript module ${type}, ` + "which is only supported when running Babel asynchronously " + "or when using the Node.js `--experimental-require-module` flag.", `You appear to be using a ${type} that contains top-level await, ` + "which is only supported when running Babel asynchronously."); | ||
| } catch (err) { | ||
| err.message = `[BABEL]: ${err.message} (While processing: ${name})`; | ||
| throw err; | ||
| } | ||
| } | ||
| //# sourceMappingURL=plugins.js.map |
| {"version":3,"names":["createDebug","path","isAsync","loadCodeDefault","fileURLToPath","pathToFileURL","resolve","importMetaResolve","createRequire","existsSync","require","import","meta","url","debug","EXACT_RE","BABEL_PLUGIN_PREFIX_RE","BABEL_PRESET_PREFIX_RE","BABEL_PLUGIN_ORG_RE","BABEL_PRESET_ORG_RE","OTHER_PLUGIN_ORG_RE","OTHER_PRESET_ORG_RE","OTHER_ORG_DEFAULT_RE","resolvePlugin","resolveStandardizedName","bind","resolvePreset","loadPlugin","name","dirname","filepath","loader","value","requireModule","loadPreset","standardizeName","type","isAbsolute","isPreset","replace","resolveAlternativesHelper","standardizedName","error","code","message","oppositeType","transformName","tryRequireResolve","id","paths","tryImportMetaResolve","options","resolveStandardizedNameForRequire","it","res","next","done","resolveStandardizedNameForImport","parentUrl","join","href","allowAsync","resolved","Object","assign","Error","e","e2","err"],"sources":["../../../src/config/files/plugins.ts"],"sourcesContent":["/**\n * This file handles all logic for converting string-based configuration references into loaded objects.\n */\n\nimport { createDebug } from \"obug\";\nimport path from \"node:path\";\nimport type { Handler } from \"gensync\";\nimport { isAsync } from \"../../gensync-utils/async.ts\";\nimport loadCodeDefault from \"./module-types.ts\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport { resolve as importMetaResolve } from \"import-meta-resolve\";\n\nimport { createRequire } from \"node:module\";\nimport { existsSync } from \"node:fs\";\nconst require = createRequire(import.meta.url);\n\nconst debug = createDebug(\"babel:config:loading:files:plugins\");\n\nconst EXACT_RE = /^module:/;\nconst BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\\/|babel-plugin-)/;\nconst BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\\/|babel-preset-)/;\nconst BABEL_PLUGIN_ORG_RE = /^(@babel\\/)(?!plugin-|[^/]+\\/)/;\nconst BABEL_PRESET_ORG_RE = /^(@babel\\/)(?!preset-|[^/]+\\/)/;\nconst OTHER_PLUGIN_ORG_RE =\n /^(@(?!babel\\/)[^/]+\\/)(?![^/]*babel-plugin(?:-|\\/|$)|[^/]+\\/)/;\nconst OTHER_PRESET_ORG_RE =\n /^(@(?!babel\\/)[^/]+\\/)(?![^/]*babel-preset(?:-|\\/|$)|[^/]+\\/)/;\nconst OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;\n\nexport const resolvePlugin = resolveStandardizedName.bind(null, \"plugin\");\nexport const resolvePreset = resolveStandardizedName.bind(null, \"preset\");\n\nexport function* loadPlugin(\n name: string,\n dirname: string,\n): Handler<{ filepath: string; value: unknown }> {\n const { filepath, loader } = resolvePlugin(name, dirname, yield* isAsync());\n\n const value = yield* requireModule(\"plugin\", loader, filepath);\n debug(\"Loaded plugin %o from %o.\", name, dirname);\n\n return { filepath, value };\n}\n\nexport function* loadPreset(\n name: string,\n dirname: string,\n): Handler<{ filepath: string; value: unknown }> {\n const { filepath, loader } = resolvePreset(name, dirname, yield* isAsync());\n\n const value = yield* requireModule(\"preset\", loader, filepath);\n\n debug(\"Loaded preset %o from %o.\", name, dirname);\n\n return { filepath, value };\n}\n\nfunction standardizeName(type: \"plugin\" | \"preset\", name: string) {\n // Let absolute and relative paths through.\n if (path.isAbsolute(name)) return name;\n\n const isPreset = type === \"preset\";\n\n return (\n name\n // foo -> babel-preset-foo\n .replace(\n isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE,\n `babel-${type}-`,\n )\n // @babel/es2015 -> @babel/preset-es2015\n .replace(\n isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE,\n `$1${type}-`,\n )\n // @foo/mypreset -> @foo/babel-preset-mypreset\n .replace(\n isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE,\n `$1babel-${type}-`,\n )\n // @foo -> @foo/babel-preset\n .replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`)\n // module:mypreset -> mypreset\n .replace(EXACT_RE, \"\")\n );\n}\n\ntype Result<T> = { error: Error; value: null } | { error: null; value: T };\n\nfunction* resolveAlternativesHelper(\n type: \"plugin\" | \"preset\",\n name: string,\n): Iterator<string, string, Result<string>> {\n const standardizedName = standardizeName(type, name);\n const { error, value } = yield standardizedName;\n if (!error) return value;\n\n // @ts-expect-error code may not index error\n if (error.code !== \"MODULE_NOT_FOUND\") throw error;\n\n if (standardizedName !== name && !(yield name).error) {\n error.message += `\\n- If you want to resolve \"${name}\", use \"module:${name}\"`;\n }\n\n if (!(yield standardizeName(type, \"@babel/\" + name)).error) {\n error.message += `\\n- Did you mean \"@babel/${name}\"?`;\n }\n\n const oppositeType = type === \"preset\" ? \"plugin\" : \"preset\";\n if (!(yield standardizeName(oppositeType, name)).error) {\n error.message += `\\n- Did you accidentally pass a ${oppositeType} as a ${type}?`;\n }\n\n if (type === \"plugin\") {\n const transformName = standardizedName.replace(\"-proposal-\", \"-transform-\");\n if (transformName !== standardizedName && !(yield transformName).error) {\n error.message += `\\n- Did you mean \"${transformName}\"?`;\n }\n }\n\n error.message += `\\n\nMake sure that all the Babel plugins and presets you are using\nare defined as dependencies or devDependencies in your package.json\nfile. It's possible that the missing plugin is loaded by a preset\nyou are using that forgot to add the plugin to its dependencies: you\ncan workaround this problem by explicitly adding the missing package\nto your top-level package.json.\n`;\n\n throw error;\n}\n\nfunction tryRequireResolve(\n id: string,\n dirname: string | undefined,\n): Result<string> {\n try {\n if (dirname) {\n return { error: null, value: require.resolve(id, { paths: [dirname] }) };\n } else {\n return { error: null, value: require.resolve(id) };\n }\n } catch (error) {\n return { error, value: null };\n }\n}\n\nfunction tryImportMetaResolve(\n id: Parameters<typeof importMetaResolve>[0],\n options: Parameters<typeof importMetaResolve>[1],\n): Result<string> {\n try {\n return { error: null, value: importMetaResolve(id, options) };\n } catch (error) {\n return { error, value: null };\n }\n}\n\nfunction resolveStandardizedNameForRequire(\n type: \"plugin\" | \"preset\",\n name: string,\n dirname: string,\n) {\n const it = resolveAlternativesHelper(type, name);\n let res = it.next();\n while (!res.done) {\n res = it.next(tryRequireResolve(res.value, dirname));\n }\n return { loader: \"require\" as const, filepath: res.value };\n}\nfunction resolveStandardizedNameForImport(\n type: \"plugin\" | \"preset\",\n name: string,\n dirname: string,\n) {\n const parentUrl = pathToFileURL(\n path.join(dirname, \"./babel-virtual-resolve-base.js\"),\n ).href;\n\n const it = resolveAlternativesHelper(type, name);\n let res = it.next();\n while (!res.done) {\n res = it.next(tryImportMetaResolve(res.value, parentUrl));\n }\n return { loader: \"auto\" as const, filepath: fileURLToPath(res.value) };\n}\n\nfunction resolveStandardizedName(\n type: \"plugin\" | \"preset\",\n name: string,\n dirname: string,\n allowAsync: boolean,\n) {\n if (!allowAsync) {\n return resolveStandardizedNameForRequire(type, name, dirname);\n }\n\n try {\n const resolved = resolveStandardizedNameForImport(type, name, dirname);\n // import-meta-resolve 4.0 does not throw if the module is not found.\n if (!existsSync(resolved.filepath)) {\n throw Object.assign(\n new Error(`Could not resolve \"${name}\" in file ${dirname}.`),\n { type: \"MODULE_NOT_FOUND\" },\n );\n }\n return resolved;\n } catch (e) {\n try {\n return resolveStandardizedNameForRequire(type, name, dirname);\n } catch (e2) {\n if (e.type === \"MODULE_NOT_FOUND\") throw e;\n if (e2.type === \"MODULE_NOT_FOUND\") throw e2;\n throw e;\n }\n }\n}\n\nfunction* requireModule(\n type: string,\n loader: \"require\" | \"auto\",\n name: string,\n): Handler<unknown> {\n try {\n return yield* loadCodeDefault(\n name,\n loader,\n `You appear to be using a native ECMAScript module ${type}, ` +\n \"which is only supported when running Babel asynchronously \" +\n \"or when using the Node.js `--experimental-require-module` flag.\",\n `You appear to be using a ${type} that contains top-level await, ` +\n \"which is only supported when running Babel asynchronously.\",\n );\n } catch (err) {\n err.message = `[BABEL]: ${err.message} (While processing: ${name})`;\n throw err;\n }\n}\n"],"mappings":"AAIA,SAASA,WAAW,QAAQ,MAAM;AAClC,OAAOC,IAAI,MAAM,WAAW;AAE5B,SAASC,OAAO,QAAQ,8BAA8B;AACtD,OAAOC,eAAe,MA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ACJ,CAAC;EACH,CAAC,CAAC,OAAOgC,GAAG,EAAE;IACZA,GAAG,CAACxB,OAAO,GAAG,YAAYwB,GAAG,CAACxB,OAAO,uBAAuBhB,IAAI,GAAG;IACnE,MAAMwC,GAAG;EACX;AACF","ignoreList":[]} |
| export {}; | ||
| //# sourceMappingURL=types.js.map |
| {"version":3,"names":[],"sources":["../../../src/config/files/types.ts"],"sourcesContent":["import type { InputOptions } from \"../index.ts\";\n\nexport type ConfigFile = {\n filepath: string;\n dirname: string;\n options: InputOptions & { babel?: unknown };\n};\n\nexport type IgnoreFile = {\n filepath: string;\n dirname: string;\n ignore: RegExp[];\n};\n\nexport type RelativeConfig = {\n // The actual config, either from package.json#babel, .babelrc, or\n // .babelrc.js, if there was one.\n config: ConfigFile | null;\n // The .babelignore, if there was one.\n ignore: IgnoreFile | null;\n};\n\nexport type FilePackageData = {\n // The file in the package.\n filepath: string;\n // Any ancestor directories of the file that are within the package.\n directories: string[];\n // The contents of the package.json. May not be found if the package just\n // terminated at a node_modules folder without finding one.\n pkg: ConfigFile | null;\n // True if a package.json or node_modules folder was found while traversing\n // the directory structure.\n isPackage: boolean;\n};\n"],"mappings":"","ignoreList":[]} |
| import { makeStrongCache } from "../caching.js"; | ||
| import * as fs from "../../gensync-utils/fs.js"; | ||
| import nodeFs from "node:fs"; | ||
| export function makeStaticFileCache(fn) { | ||
| return makeStrongCache(function* (filepath, cache) { | ||
| const cached = cache.invalidate(() => fileMtime(filepath)); | ||
| if (cached === null) { | ||
| return null; | ||
| } | ||
| return fn(filepath, yield* fs.readFile(filepath, "utf8")); | ||
| }); | ||
| } | ||
| function fileMtime(filepath) { | ||
| if (!nodeFs.existsSync(filepath)) return null; | ||
| try { | ||
| return +nodeFs.statSync(filepath).mtime; | ||
| } catch (e) { | ||
| if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; | ||
| } | ||
| return null; | ||
| } | ||
| //# sourceMappingURL=utils.js.map |
| {"version":3,"names":["makeStrongCache","fs","nodeFs","makeStaticFileCache","fn","filepath","cache","cached","invalidate","fileMtime","readFile","existsSync","statSync","mtime","e","code"],"sources":["../../../src/config/files/utils.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport { makeStrongCache } from \"../caching.ts\";\nimport type { CacheConfigurator } from \"../caching.ts\";\nimport * as fs from \"../../gensync-utils/fs.ts\";\nimport nodeFs from \"node:fs\";\n\nexport function makeStaticFileCache<T>(\n fn: (filepath: string, contents: string) => T,\n) {\n return makeStrongCache(function* (\n filepath: string,\n cache: CacheConfigurator<void>,\n ): Handler<null | T> {\n const cached = cache.invalidate(() => fileMtime(filepath));\n\n if (cached === null) {\n return null;\n }\n\n return fn(filepath, yield* fs.readFile(filepath, \"utf8\"));\n });\n}\n\nfunction fileMtime(filepath: string): number | null {\n if (!nodeFs.existsSync(filepath)) return null;\n\n try {\n return +nodeFs.statSync(filepath).mtime;\n } catch (e) {\n if (e.code !== \"ENOENT\" && e.code !== \"ENOTDIR\") throw e;\n }\n\n return null;\n}\n"],"mappings":"AAEA,SAASA,eAAe,QAAQ,eAAe;AAE/C,OAAO,KAAKC,EAAE,MAAM,2BAA2B;AAC/C,OAAOC,MAAM,MAAM,SAAS;AAE5B,OAAO,SAASC,mBAAmBA,CACjCC,EAA6C,EAC7C;EACA,OAAOJ,eAAe,CAAC,WACrBK,QAAgB,EAChBC,KAA8B,EACX;IACnB,MAAMC,MAAM,GAAGD,KAAK,CAACE,UAAU,CAAC,MAAMC,SAAS,CAACJ,QAAQ,CAAC,CAAC;IAE1D,IAAIE,MAAM,KAAK,IAAI,EAAE;MACnB,OAAO,IAAI;IACb;IAEA,OAAOH,EAAE,CAACC,QAAQ,EAAE,OAAOJ,EAAE,CAACS,QAAQ,CAACL,QAAQ,EAAE,MAAM,CAAC,CAAC;EAC3D,CAAC,CAAC;AACJ;AAEA,SAASI,SAASA,CAACJ,QAAgB,EAAiB;EAClD,IAAI,CAACH,MAAM,CAACS,UAAU,CAACN,QAAQ,CAAC,EAAE,OAAO,IAAI;EAE7C,IAAI;IACF,OAAO,CAACH,MAAM,CAACU,QAAQ,CAACP,QAAQ,CAAC,CAACQ,KAAK;EACzC,CAAC,CAAC,OAAOC,CAAC,EAAE;IACV,IAAIA,CAAC,CAACC,IAAI,KAAK,QAAQ,IAAID,CAAC,CAACC,IAAI,KAAK,SAAS,EAAE,MAAMD,CAAC;EAC1D;EAEA,OAAO,IAAI;AACb","ignoreList":[]} |
| import gensync from "gensync"; | ||
| import { forwardAsync, maybeAsync, isThenable } from "../gensync-utils/async.js"; | ||
| import { mergeOptions } from "./util.js"; | ||
| import * as context from "../index.js"; | ||
| import Plugin from "./plugin.js"; | ||
| import { getItemDescriptor } from "./item.js"; | ||
| import { buildPresetChain } from "./config-chain.js"; | ||
| import { finalize as freezeDeepArray } from "./helpers/deep-array.js"; | ||
| import traverse from "@babel/traverse"; | ||
| import { makeWeakCache, makeWeakCacheSync } from "./caching.js"; | ||
| import { validate, checkNoUnwrappedItemOptionPairs } from "./validation/options.js"; | ||
| import { validatePluginObject } from "./validation/plugins.js"; | ||
| import { makePluginAPI, makePresetAPI } from "./helpers/config-api.js"; | ||
| import loadPrivatePartialConfig from "./partial.js"; | ||
| import ConfigError from "../errors/config-error.js"; | ||
| export default gensync(function* loadFullConfig(inputOpts) { | ||
| const result = yield* loadPrivatePartialConfig(inputOpts); | ||
| if (!result) { | ||
| return null; | ||
| } | ||
| const { | ||
| options, | ||
| context, | ||
| fileHandling | ||
| } = result; | ||
| if (fileHandling === "ignored") { | ||
| return null; | ||
| } | ||
| const optionDefaults = {}; | ||
| const { | ||
| plugins, | ||
| presets | ||
| } = options; | ||
| if (!plugins || !presets) { | ||
| throw new Error("Assertion failure - plugins and presets exist"); | ||
| } | ||
| const presetContext = { | ||
| ...context, | ||
| targets: options.targets | ||
| }; | ||
| const toDescriptor = item => { | ||
| const desc = getItemDescriptor(item); | ||
| if (!desc) { | ||
| throw new Error("Assertion failure - must be config item"); | ||
| } | ||
| return desc; | ||
| }; | ||
| const presetsDescriptors = presets.map(toDescriptor); | ||
| const initialPluginsDescriptors = plugins.map(toDescriptor); | ||
| const pluginDescriptorsByPass = [[]]; | ||
| const passes = []; | ||
| const externalDependencies = []; | ||
| const ignored = yield* enhanceError(context, function* recursePresetDescriptors(rawPresets, pluginDescriptorsPass) { | ||
| const presets = []; | ||
| for (let i = 0; i < rawPresets.length; i++) { | ||
| const descriptor = rawPresets[i]; | ||
| if (descriptor.options !== false) { | ||
| try { | ||
| var preset = yield* loadPresetDescriptor(descriptor, presetContext); | ||
| } catch (e) { | ||
| if (e.code === "BABEL_UNKNOWN_OPTION") { | ||
| checkNoUnwrappedItemOptionPairs(rawPresets, i, "preset", e); | ||
| } | ||
| throw e; | ||
| } | ||
| externalDependencies.push(preset.externalDependencies); | ||
| if (descriptor.ownPass) { | ||
| presets.push({ | ||
| preset: preset.chain, | ||
| pass: [] | ||
| }); | ||
| } else { | ||
| presets.unshift({ | ||
| preset: preset.chain, | ||
| pass: pluginDescriptorsPass | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| if (presets.length > 0) { | ||
| pluginDescriptorsByPass.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass)); | ||
| for (const { | ||
| preset, | ||
| pass | ||
| } of presets) { | ||
| if (!preset) return true; | ||
| pass.push(...preset.plugins); | ||
| const ignored = yield* recursePresetDescriptors(preset.presets, pass); | ||
| if (ignored) return true; | ||
| preset.options.forEach(opts => { | ||
| mergeOptions(optionDefaults, opts); | ||
| }); | ||
| } | ||
| } | ||
| })(presetsDescriptors, pluginDescriptorsByPass[0]); | ||
| if (ignored) return null; | ||
| const opts = optionDefaults; | ||
| mergeOptions(opts, options); | ||
| const pluginContext = { | ||
| ...presetContext, | ||
| assumptions: opts.assumptions ?? {} | ||
| }; | ||
| yield* enhanceError(context, function* loadPluginDescriptors() { | ||
| pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); | ||
| for (const descs of pluginDescriptorsByPass) { | ||
| const pass = []; | ||
| passes.push(pass); | ||
| for (let i = 0; i < descs.length; i++) { | ||
| const descriptor = descs[i]; | ||
| if (descriptor.options !== false) { | ||
| try { | ||
| var plugin = yield* loadPluginDescriptor(descriptor, pluginContext); | ||
| } catch (e) { | ||
| if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { | ||
| checkNoUnwrappedItemOptionPairs(descs, i, "plugin", e); | ||
| } | ||
| throw e; | ||
| } | ||
| pass.push(plugin); | ||
| externalDependencies.push(plugin.externalDependencies); | ||
| } | ||
| } | ||
| } | ||
| })(); | ||
| opts.plugins = passes[0]; | ||
| opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({ | ||
| plugins | ||
| })); | ||
| opts.passPerPreset = opts.presets.length > 0; | ||
| return { | ||
| options: opts, | ||
| passes: passes, | ||
| externalDependencies: freezeDeepArray(externalDependencies) | ||
| }; | ||
| }); | ||
| function enhanceError(context, fn) { | ||
| return function* (arg1, arg2) { | ||
| try { | ||
| return yield* fn(arg1, arg2); | ||
| } catch (e) { | ||
| if (!e.message.startsWith("[BABEL]")) { | ||
| e.message = `[BABEL] ${context.filename ?? "unknown file"}: ${e.message}`; | ||
| } | ||
| throw e; | ||
| } | ||
| }; | ||
| } | ||
| const makeDescriptorLoader = apiFactory => makeWeakCache(function* ({ | ||
| value, | ||
| options, | ||
| dirname, | ||
| alias | ||
| }, cache) { | ||
| if (options === false) throw new Error("Assertion failure"); | ||
| options = options || {}; | ||
| const externalDependencies = []; | ||
| let item = value; | ||
| if (typeof value === "function") { | ||
| const factory = maybeAsync(value, `You appear to be using an async plugin/preset, but Babel has been called synchronously`); | ||
| const api = { | ||
| ...context, | ||
| ...apiFactory(cache, externalDependencies) | ||
| }; | ||
| try { | ||
| item = yield* factory(api, options, dirname); | ||
| } catch (e) { | ||
| if (alias) { | ||
| e.message += ` (While processing: ${JSON.stringify(alias)})`; | ||
| } | ||
| throw e; | ||
| } | ||
| } | ||
| if (!item || typeof item !== "object") { | ||
| throw new Error("Plugin/Preset did not return an object."); | ||
| } | ||
| if (isThenable(item)) { | ||
| yield* []; | ||
| throw new Error(`You appear to be using a promise as a plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version. ` + `As an alternative, you can prefix the promise with "await". ` + `(While processing: ${JSON.stringify(alias)})`); | ||
| } | ||
| if (externalDependencies.length > 0 && (!cache.configured() || cache.mode() === "forever")) { | ||
| let error = `A plugin/preset has external untracked dependencies ` + `(${externalDependencies[0]}), but the cache `; | ||
| if (!cache.configured()) { | ||
| error += `has not been configured to be invalidated when the external dependencies change. `; | ||
| } else { | ||
| error += ` has been configured to never be invalidated. `; | ||
| } | ||
| error += `Plugins/presets should configure their cache to be invalidated when the external ` + `dependencies change, for example using \`api.cache.invalidate(() => ` + `statSync(filepath).mtimeMs)\` or \`api.cache.never()\`\n` + `(While processing: ${JSON.stringify(alias)})`; | ||
| throw new Error(error); | ||
| } | ||
| return { | ||
| value: item, | ||
| options, | ||
| dirname, | ||
| alias, | ||
| externalDependencies: freezeDeepArray(externalDependencies) | ||
| }; | ||
| }); | ||
| const pluginDescriptorLoader = makeDescriptorLoader(makePluginAPI); | ||
| const presetDescriptorLoader = makeDescriptorLoader(makePresetAPI); | ||
| const instantiatePlugin = makeWeakCache(function* ({ | ||
| value, | ||
| options, | ||
| dirname, | ||
| alias, | ||
| externalDependencies | ||
| }, cache) { | ||
| const pluginObj = validatePluginObject(value); | ||
| const plugin = { | ||
| ...pluginObj | ||
| }; | ||
| if (plugin.visitor) { | ||
| plugin.visitor = traverse.explode({ | ||
| ...plugin.visitor | ||
| }); | ||
| } | ||
| if (plugin.inherits) { | ||
| const inheritsDescriptor = { | ||
| name: undefined, | ||
| alias: `${alias}$inherits`, | ||
| value: plugin.inherits, | ||
| options, | ||
| dirname | ||
| }; | ||
| const inherits = yield* forwardAsync(loadPluginDescriptor, run => { | ||
| return cache.invalidate(data => run(inheritsDescriptor, data)); | ||
| }); | ||
| plugin.pre = chainMaybeAsync(inherits.pre, plugin.pre); | ||
| plugin.post = chainMaybeAsync(inherits.post, plugin.post); | ||
| plugin.manipulateOptions = chainMaybeAsync(inherits.manipulateOptions, plugin.manipulateOptions); | ||
| plugin.visitor = traverse.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]); | ||
| if (inherits.externalDependencies.length > 0) { | ||
| if (externalDependencies.length === 0) { | ||
| externalDependencies = inherits.externalDependencies; | ||
| } else { | ||
| externalDependencies = freezeDeepArray([externalDependencies, inherits.externalDependencies]); | ||
| } | ||
| } | ||
| } | ||
| return new Plugin(plugin, options, alias, externalDependencies); | ||
| }); | ||
| function* loadPluginDescriptor(descriptor, context) { | ||
| if (descriptor.value instanceof Plugin) { | ||
| if (descriptor.options) { | ||
| throw new Error("Passed options to an existing Plugin instance will not work."); | ||
| } | ||
| return descriptor.value; | ||
| } | ||
| return yield* instantiatePlugin(yield* pluginDescriptorLoader(descriptor, context), context); | ||
| } | ||
| const needsFilename = val => val && typeof val !== "function"; | ||
| const validateIfOptionNeedsFilename = (options, descriptor) => { | ||
| if (needsFilename(options.test) || needsFilename(options.include) || needsFilename(options.exclude)) { | ||
| const formattedPresetName = descriptor.name ? `"${descriptor.name}"` : "/* your preset */"; | ||
| throw new ConfigError([`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, `\`\`\``, `babel.transformSync(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`, `\`\`\``, `See https://babeljs.io/docs/en/options#filename for more information.`].join("\n")); | ||
| } | ||
| }; | ||
| const validatePreset = (preset, context, descriptor) => { | ||
| if (!context.filename) { | ||
| const { | ||
| options | ||
| } = preset; | ||
| validateIfOptionNeedsFilename(options, descriptor); | ||
| options.overrides?.forEach(overrideOptions => validateIfOptionNeedsFilename(overrideOptions, descriptor)); | ||
| } | ||
| }; | ||
| const instantiatePreset = makeWeakCacheSync(({ | ||
| value, | ||
| dirname, | ||
| alias, | ||
| externalDependencies | ||
| }) => { | ||
| return { | ||
| options: validate("preset", value), | ||
| alias, | ||
| dirname, | ||
| externalDependencies | ||
| }; | ||
| }); | ||
| function* loadPresetDescriptor(descriptor, context) { | ||
| const preset = instantiatePreset(yield* presetDescriptorLoader(descriptor, context)); | ||
| validatePreset(preset, context, descriptor); | ||
| return { | ||
| chain: yield* buildPresetChain(preset, context), | ||
| externalDependencies: preset.externalDependencies | ||
| }; | ||
| } | ||
| function chainMaybeAsync(a, b) { | ||
| if (!a) return b; | ||
| if (!b) return a; | ||
| return function (...args) { | ||
| const res = a.apply(this, args); | ||
| if (res && typeof res.then === "function") { | ||
| return res.then(() => b.apply(this, args)); | ||
| } | ||
| return b.apply(this, args); | ||
| }; | ||
| } | ||
| //# sourceMappingURL=full.js.map |
| {"version":3,"names":["gensync","forwardAsync","maybeAsync","isThenable","mergeOptions","context","Plugin","getItemDescriptor","buildPresetChain","finalize","freezeDeepArray","traverse","makeWeakCache","makeWeakCacheSync","validate","checkNoUnwrappedItemOptionPairs","validatePluginObject","makePluginAPI","makePresetAPI","loadPrivatePartialConfig","ConfigError","loadFullConfig","inputOpts","result","options","fileHandling","optionDefaults","plugins","presets","Error","presetContext","targets","toDescriptor","item","desc","presetsDescriptors","map","initialPluginsDescriptors","pluginDescriptorsByPass","passes","externalDependencies","ignored","enhanceError","recursePresetDescriptors","rawPresets","pluginDescriptorsPass","i","length","descriptor","preset","loadPresetDescriptor","e","code","push","ownPass","chain","pass","unshift","splice","o","filter","p","forEach","opts","pluginContext","assumptions","loadPluginDescriptors","descs","plugin","loadPluginDescriptor","slice","passPerPreset","fn","arg1","arg2","message","startsWith","filename","makeDescriptorLoader","apiFactory","value","dirname","alias","cache","factory","api","JSON","stringify","configured","mode","error","pluginDescriptorLoader","presetDescriptorLoader","instantiatePlugin","pluginObj","visitor","explode","inherits","inheritsDescriptor","name","undefined","run","invalidate","data","pre","chainMaybeAsync","post","manipulateOptions","visitors","merge","needsFilename","val","validateIfOptionNeedsFilename","test","include","exclude","formattedPresetName","join","validatePreset","overrides","overrideOptions","instantiatePreset","a","b","args","res","apply","then"],"sources":["../../src/config/full.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\nimport {\n forwardAsync,\n maybeAsync,\n isThenable,\n} from \"../gensync-utils/async.ts\";\n\nimport { mergeOptions } from \"./util.ts\";\nimport * as context from \"../index.ts\";\nimport Plugin from \"./plugin.ts\";\nimport { getItemDescriptor } from \"./item.ts\";\nimport { buildPresetChain } from \"./config-chain.ts\";\nimport { finalize as freezeDeepArray } from \"./helpers/deep-array.ts\";\nimport type { DeepArray, ReadonlyDeepArray } from \"./helpers/deep-array.ts\";\nimport type {\n ConfigContext,\n ConfigChain,\n PresetInstance,\n} from \"./config-chain.ts\";\nimport type { UnloadedDescriptor } from \"./config-descriptors.ts\";\nimport traverse from \"@babel/traverse\";\nimport { makeWeakCache, makeWeakCacheSync } from \"./caching.ts\";\nimport type { CacheConfigurator } from \"./caching.ts\";\nimport {\n validate,\n checkNoUnwrappedItemOptionPairs,\n} from \"./validation/options.ts\";\nimport type { InputOptions, PluginItem } from \"./validation/options.ts\";\nimport { validatePluginObject } from \"./validation/plugins.ts\";\nimport { makePluginAPI, makePresetAPI } from \"./helpers/config-api.ts\";\nimport type { PluginAPI, PresetAPI } from \"./helpers/config-api.ts\";\n\nimport loadPrivatePartialConfig from \"./partial.ts\";\nimport type { ResolvedOptions } from \"./validation/options.ts\";\n\nimport type * as Context from \"./cache-contexts.ts\";\nimport ConfigError from \"../errors/config-error.ts\";\n\ntype LoadedDescriptor = {\n value: any;\n options: object;\n dirname: string;\n alias: string;\n externalDependencies: ReadonlyDeepArray<string>;\n};\n\nexport type { InputOptions } from \"./validation/options.ts\";\n\nexport type ResolvedConfig = {\n options: ResolvedOptions;\n passes: PluginPasses;\n externalDependencies: ReadonlyDeepArray<string>;\n};\n\nexport type { Plugin };\nexport type PluginPassList = Plugin[];\nexport type PluginPasses = PluginPassList[];\n\nexport default gensync(function* loadFullConfig(\n inputOpts: InputOptions,\n): Handler<ResolvedConfig | null> {\n const result = yield* loadPrivatePartialConfig(inputOpts);\n if (!result) {\n return null;\n }\n const { options, context, fileHandling } = result;\n\n if (fileHandling === \"ignored\") {\n return null;\n }\n\n const optionDefaults = {};\n\n const { plugins, presets } = options;\n\n if (!plugins || !presets) {\n throw new Error(\"Assertion failure - plugins and presets exist\");\n }\n\n const presetContext: Context.FullPreset = {\n ...context,\n targets: options.targets,\n };\n\n const toDescriptor = (item: PluginItem) => {\n const desc = getItemDescriptor(item);\n if (!desc) {\n throw new Error(\"Assertion failure - must be config item\");\n }\n\n return desc;\n };\n\n const presetsDescriptors = presets.map(toDescriptor);\n const initialPluginsDescriptors = plugins.map(toDescriptor);\n const pluginDescriptorsByPass: UnloadedDescriptor<PluginAPI>[][] = [[]];\n const passes: Plugin[][] = [];\n\n const externalDependencies: DeepArray<string> = [];\n\n const ignored = yield* enhanceError(\n context,\n function* recursePresetDescriptors(\n rawPresets: UnloadedDescriptor<PresetAPI>[],\n pluginDescriptorsPass: UnloadedDescriptor<PluginAPI>[],\n ): Handler<true | void> {\n const presets: {\n preset: ConfigChain | null;\n pass: UnloadedDescriptor<PluginAPI>[];\n }[] = [];\n\n for (let i = 0; i < rawPresets.length; i++) {\n const descriptor = rawPresets[i];\n // @ts-expect-error TODO: disallow false\n if (descriptor.options !== false) {\n try {\n // eslint-disable-next-line no-var\n var preset = yield* loadPresetDescriptor(descriptor, presetContext);\n } catch (e) {\n if (e.code === \"BABEL_UNKNOWN_OPTION\") {\n checkNoUnwrappedItemOptionPairs(rawPresets, i, \"preset\", e);\n }\n throw e;\n }\n\n externalDependencies.push(preset.externalDependencies);\n\n // Presets normally run in reverse order, but if they\n // have their own pass they run after the presets\n // in the previous pass.\n if (descriptor.ownPass) {\n presets.push({ preset: preset.chain, pass: [] });\n } else {\n presets.unshift({\n preset: preset.chain,\n pass: pluginDescriptorsPass,\n });\n }\n }\n }\n\n // resolve presets\n if (presets.length > 0) {\n // The passes are created in the same order as the preset list, but are inserted before any\n // existing additional passes.\n pluginDescriptorsByPass.splice(\n 1,\n 0,\n ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass),\n );\n\n for (const { preset, pass } of presets) {\n if (!preset) return true;\n\n pass.push(...preset.plugins);\n\n const ignored = yield* recursePresetDescriptors(preset.presets, pass);\n if (ignored) return true;\n\n preset.options.forEach(opts => {\n mergeOptions(optionDefaults, opts);\n });\n }\n }\n },\n )(presetsDescriptors, pluginDescriptorsByPass[0]);\n\n if (ignored) return null;\n\n const opts = optionDefaults as ResolvedOptions;\n mergeOptions(opts, options);\n\n const pluginContext: Context.FullPlugin = {\n ...presetContext,\n assumptions: opts.assumptions ?? {},\n };\n\n yield* enhanceError(context, function* loadPluginDescriptors() {\n pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors);\n\n for (const descs of pluginDescriptorsByPass) {\n const pass: Plugin[] = [];\n passes.push(pass);\n\n for (let i = 0; i < descs.length; i++) {\n const descriptor = descs[i];\n // @ts-expect-error TODO: disallow false\n if (descriptor.options !== false) {\n try {\n // eslint-disable-next-line no-var\n var plugin = yield* loadPluginDescriptor(descriptor, pluginContext);\n } catch (e) {\n if (e.code === \"BABEL_UNKNOWN_PLUGIN_PROPERTY\") {\n // print special message for `plugins: [\"@babel/foo\", { foo: \"option\" }]`\n checkNoUnwrappedItemOptionPairs(descs, i, \"plugin\", e);\n }\n throw e;\n }\n pass.push(plugin);\n\n externalDependencies.push(plugin.externalDependencies);\n }\n }\n }\n })();\n\n opts.plugins = passes[0];\n opts.presets = passes\n .slice(1)\n .filter(plugins => plugins.length > 0)\n .map(plugins => ({ plugins }));\n opts.passPerPreset = opts.presets.length > 0;\n\n return {\n options: opts,\n passes: passes,\n externalDependencies: freezeDeepArray(externalDependencies),\n };\n});\n\nfunction enhanceError<T extends Function>(context: ConfigContext, fn: T): T {\n return function* (arg1: unknown, arg2: unknown) {\n try {\n return yield* fn(arg1, arg2);\n } catch (e) {\n // There are a few case where thrown errors will try to annotate themselves multiple times, so\n // to keep things simple we just bail out if re-wrapping the message.\n if (!e.message.startsWith(\"[BABEL]\")) {\n e.message = `[BABEL] ${context.filename ?? \"unknown file\"}: ${\n e.message\n }`;\n }\n\n throw e;\n }\n } as any;\n}\n\n/**\n * Load a generic plugin/preset from the given descriptor loaded from the config object.\n */\nconst makeDescriptorLoader = <Context, API>(\n apiFactory: (\n cache: CacheConfigurator<Context>,\n externalDependencies: string[],\n ) => API,\n) =>\n makeWeakCache(function* (\n { value, options, dirname, alias }: UnloadedDescriptor<API>,\n cache: CacheConfigurator<Context>,\n ): Handler<LoadedDescriptor> {\n // Disabled presets should already have been filtered out\n // @ts-expect-error expected\n if (options === false) throw new Error(\"Assertion failure\");\n\n options = options || {};\n\n const externalDependencies: string[] = [];\n\n let item: unknown = value;\n if (typeof value === \"function\") {\n const factory = maybeAsync(\n value as (api: API, options: object, dirname: string) => unknown,\n `You appear to be using an async plugin/preset, but Babel has been called synchronously`,\n );\n\n const api = {\n ...context,\n ...apiFactory(cache, externalDependencies),\n };\n try {\n item = yield* factory(api, options, dirname);\n } catch (e) {\n if (alias) {\n e.message += ` (While processing: ${JSON.stringify(alias)})`;\n }\n throw e;\n }\n }\n\n if (!item || typeof item !== \"object\") {\n throw new Error(\"Plugin/Preset did not return an object.\");\n }\n\n if (isThenable(item)) {\n // if we want to support async plugins\n yield* [];\n\n throw new Error(\n `You appear to be using a promise as a plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, ` +\n `you may need to upgrade your @babel/core version. ` +\n `As an alternative, you can prefix the promise with \"await\". ` +\n `(While processing: ${JSON.stringify(alias)})`,\n );\n }\n\n if (\n externalDependencies.length > 0 &&\n (!cache.configured() || cache.mode() === \"forever\")\n ) {\n let error =\n `A plugin/preset has external untracked dependencies ` +\n `(${externalDependencies[0]}), but the cache `;\n if (!cache.configured()) {\n error += `has not been configured to be invalidated when the external dependencies change. `;\n } else {\n error += ` has been configured to never be invalidated. `;\n }\n error +=\n `Plugins/presets should configure their cache to be invalidated when the external ` +\n `dependencies change, for example using \\`api.cache.invalidate(() => ` +\n `statSync(filepath).mtimeMs)\\` or \\`api.cache.never()\\`\\n` +\n `(While processing: ${JSON.stringify(alias)})`;\n\n throw new Error(error);\n }\n\n return {\n value: item,\n options,\n dirname,\n alias,\n externalDependencies: freezeDeepArray(externalDependencies),\n };\n });\n\nconst pluginDescriptorLoader = makeDescriptorLoader<\n Context.SimplePlugin,\n PluginAPI\n>(makePluginAPI);\nconst presetDescriptorLoader = makeDescriptorLoader<\n Context.SimplePreset,\n PresetAPI\n>(makePresetAPI);\n\nconst instantiatePlugin = makeWeakCache(function* (\n { value, options, dirname, alias, externalDependencies }: LoadedDescriptor,\n cache: CacheConfigurator<Context.SimplePlugin>,\n): Handler<Plugin> {\n const pluginObj = validatePluginObject(value);\n\n const plugin = {\n ...pluginObj,\n };\n if (plugin.visitor) {\n plugin.visitor = traverse.explode({\n ...plugin.visitor,\n });\n }\n\n if (plugin.inherits) {\n const inheritsDescriptor: UnloadedDescriptor<PluginAPI> = {\n name: undefined,\n alias: `${alias}$inherits`,\n value: plugin.inherits,\n options,\n dirname,\n };\n\n const inherits = yield* forwardAsync(loadPluginDescriptor, run => {\n // If the inherited plugin changes, reinstantiate this plugin.\n return cache.invalidate(data => run(inheritsDescriptor, data));\n });\n\n plugin.pre = chainMaybeAsync(inherits.pre, plugin.pre);\n plugin.post = chainMaybeAsync(inherits.post, plugin.post);\n plugin.manipulateOptions = chainMaybeAsync(\n inherits.manipulateOptions,\n plugin.manipulateOptions,\n );\n plugin.visitor = traverse.visitors.merge([\n inherits.visitor || {},\n plugin.visitor || {},\n ]);\n\n if (inherits.externalDependencies.length > 0) {\n if (externalDependencies.length === 0) {\n externalDependencies = inherits.externalDependencies;\n } else {\n externalDependencies = freezeDeepArray([\n externalDependencies,\n inherits.externalDependencies,\n ]);\n }\n }\n }\n\n return new Plugin(plugin, options, alias, externalDependencies);\n});\n\n/**\n * Instantiate a plugin for the given descriptor, returning the plugin/options pair.\n */\nfunction* loadPluginDescriptor(\n descriptor: UnloadedDescriptor<PluginAPI>,\n context: Context.SimplePlugin,\n): Handler<Plugin> {\n if (descriptor.value instanceof Plugin) {\n if (descriptor.options) {\n throw new Error(\n \"Passed options to an existing Plugin instance will not work.\",\n );\n }\n\n return descriptor.value;\n }\n\n return yield* instantiatePlugin(\n yield* pluginDescriptorLoader(descriptor, context),\n context,\n );\n}\n\nconst needsFilename = (val: unknown) => val && typeof val !== \"function\";\n\nconst validateIfOptionNeedsFilename = (\n options: InputOptions,\n descriptor: UnloadedDescriptor<PresetAPI>,\n): void => {\n if (\n needsFilename(options.test) ||\n needsFilename(options.include) ||\n needsFilename(options.exclude)\n ) {\n const formattedPresetName = descriptor.name\n ? `\"${descriptor.name}\"`\n : \"/* your preset */\";\n throw new ConfigError(\n [\n `Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`,\n `\\`\\`\\``,\n `babel.transformSync(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`,\n `\\`\\`\\``,\n `See https://babeljs.io/docs/en/options#filename for more information.`,\n ].join(\"\\n\"),\n );\n }\n};\n\nconst validatePreset = (\n preset: PresetInstance,\n context: ConfigContext,\n descriptor: UnloadedDescriptor<PresetAPI>,\n): void => {\n if (!context.filename) {\n const { options } = preset;\n validateIfOptionNeedsFilename(options, descriptor);\n options.overrides?.forEach(overrideOptions =>\n validateIfOptionNeedsFilename(overrideOptions, descriptor),\n );\n }\n};\n\nconst instantiatePreset = makeWeakCacheSync(\n ({\n value,\n dirname,\n alias,\n externalDependencies,\n }: LoadedDescriptor): PresetInstance => {\n return {\n options: validate(\"preset\", value),\n alias,\n dirname,\n externalDependencies,\n };\n },\n);\n\n/**\n * Generate a config object that will act as the root of a new nested config.\n */\nfunction* loadPresetDescriptor(\n descriptor: UnloadedDescriptor<PresetAPI>,\n context: Context.FullPreset,\n): Handler<{\n chain: ConfigChain | null;\n externalDependencies: ReadonlyDeepArray<string>;\n}> {\n const preset = instantiatePreset(\n yield* presetDescriptorLoader(descriptor, context),\n );\n validatePreset(preset, context, descriptor);\n return {\n chain: yield* buildPresetChain(preset, context),\n externalDependencies: preset.externalDependencies,\n };\n}\n\nfunction chainMaybeAsync<Args extends any[], R extends void | Promise<void>>(\n a: undefined | ((...args: Args) => R),\n b: undefined | ((...args: Args) => R),\n): (...args: Args) => R {\n if (!a) return b;\n if (!b) return a;\n\n return function (this: unknown, ...args: Args) {\n const res = a.apply(this, args);\n if (res && typeof res.then === \"function\") {\n return res.then(() => b.apply(this, args));\n }\n return b.apply(this, args);\n } as (...args: Args) => R;\n}\n"],"mappings":"AAAA,OAAOA,OAAO,MAAwB,SAAS;AAC/C,SACEC,YAAY,EACZC,UAAU,EACVC,UAAU,QACL,2BAA2B;AAElC,SAASC,YAAY,QAAQ,WAAW;AACxC,OAAO,KAAKC,OAAO,MAAM,aAAa;AACtC,OAAOC,MAAM,MAAM,aAAa;AAChC,SAASC,iBAAiB,QAAQ,WAAW;AAC7C,SAASC,gBAAgB,QAAQ,mBAAmB;AACpD,SAASC,QAAQ,IAAIC,eAAe,QAAQ,yBAAyB;AAQrE,OAAOC,QAAQ,MAAM,iBAAiB;AACtC,SAASC,aAAa,EAAEC,iBAAiB,QAAQ,cAAc;AAE/D,SACEC,QAAQ,EACRC,+BAA+B,QAC1B,yBAAyB;AAEhC,SAASC,oBAAoB,QAAQ,yBAAyB;AAC9D,SAASC,aAAa,EAAEC,aAAa,QAAQ,yBAAyB;AAGtE,OAAOC,wBAAwB,MAAM,cAAc;AAInD,OAAOC,WAAW,MAAM,2BAA2B;AAsBnD,eAAepB,OAAO,CAAC,UAAUqB,cAAcA,CAC7CC,SAAuB,EACS;EAChC,MAAMC,MAAM,GAAG,OAAOJ,wBAAwB,CAACG,SAAS,CAAC;EACzD,IAAI,CAACC,MAAM,EAAE;IACX,OAAO,IAAI;EACb;EACA,MAAM;IAAEC,OAAO;IAAEnB,OAAO;IAAEoB;EAAa,CAAC,GAAGF,MAAM;EAEjD,IAAIE,YAA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,CAAC;AAKD,UAAUU,oBAAoBA,CAC5BF,UAAyC,EACzC3C,OAA2B,EAI1B;EACD,MAAM4C,MAAM,GAAGwE,iBAAiB,CAC9B,OAAO7B,sBAAsB,CAAC5C,UAAU,EAAE3C,OAAO,CACnD,CAAC;EACDiH,cAAc,CAACrE,MAAM,EAAE5C,OAAO,EAAE2C,UAAU,CAAC;EAC3C,OAAO;IACLO,KAAK,EAAE,OAAO/C,gBAAgB,CAACyC,MAAM,EAAE5C,OAAO,CAAC;IAC/CmC,oBAAoB,EAAES,MAAM,CAACT;EAC/B,CAAC;AACH;AAEA,SAASiE,eAAeA,CACtBiB,CAAqC,EACrCC,CAAqC,EACf;EACtB,IAAI,CAACD,CAAC,EAAE,OAAOC,CAAC;EAChB,IAAI,CAACA,CAAC,EAAE,OAAOD,CAAC;EAEhB,OAAO,UAAyB,GAAGE,IAAU,EAAE;IAC7C,MAAMC,GAAG,GAAGH,CAAC,CAACI,KAAK,CAAC,IAAI,EAAEF,IAAI,CAAC;IAC/B,IAAIC,GAAG,IAAI,OAAOA,GAAG,CAACE,IAAI,KAAK,UAAU,EAAE;MACzC,OAAOF,GAAG,CAACE,IAAI,CAAC,MAAMJ,CAAC,CAACG,KAAK,CAAC,IAAI,EAAEF,IAAI,CAAC,CAAC;IAC5C;IACA,OAAOD,CAAC,CAACG,KAAK,CAAC,IAAI,EAAEF,IAAI,CAAC;EAC5B,CAAC;AACH","ignoreList":[]} |
| import semver from "semver"; | ||
| import { version as coreVersion } from "../../index.js"; | ||
| import { assertSimpleType } from "../caching.js"; | ||
| export function makeConfigAPI(cache) { | ||
| const env = value => cache.using(data => { | ||
| if (value === undefined) return data.envName; | ||
| if (typeof value === "function") { | ||
| return assertSimpleType(value(data.envName)); | ||
| } | ||
| return (Array.isArray(value) ? value : [value]).some(entry => { | ||
| if (typeof entry !== "string") { | ||
| throw new Error("Unexpected non-string value"); | ||
| } | ||
| return entry === data.envName; | ||
| }); | ||
| }); | ||
| const caller = cb => cache.using(data => assertSimpleType(cb(data.caller))); | ||
| return { | ||
| version: coreVersion, | ||
| cache: cache.simple(), | ||
| env, | ||
| async: () => false, | ||
| caller, | ||
| assertVersion | ||
| }; | ||
| } | ||
| export function makePresetAPI(cache, externalDependencies) { | ||
| const targets = () => JSON.parse(cache.using(data => JSON.stringify(data.targets))); | ||
| const addExternalDependency = ref => { | ||
| externalDependencies.push(ref); | ||
| }; | ||
| return { | ||
| ...makeConfigAPI(cache), | ||
| targets, | ||
| addExternalDependency | ||
| }; | ||
| } | ||
| export function makePluginAPI(cache, externalDependencies) { | ||
| const assumption = name => cache.using(data => data.assumptions[name]); | ||
| return { | ||
| ...makePresetAPI(cache, externalDependencies), | ||
| assumption | ||
| }; | ||
| } | ||
| function assertVersion(range) { | ||
| if (typeof range === "number") { | ||
| if (!Number.isInteger(range)) { | ||
| throw new Error("Expected string or integer value."); | ||
| } | ||
| range = `^${range}.0.0-0`; | ||
| } | ||
| if (typeof range !== "string") { | ||
| throw new Error("Expected string or integer value."); | ||
| } | ||
| if (range === "*" || semver.satisfies(coreVersion, range)) return; | ||
| const message = `Requires Babel "${range}", but was loaded with "${coreVersion}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`; | ||
| if (typeof process !== "undefined" && process.env.BABEL_7_TO_8_DANGEROUSLY_DISABLE_VERSION_CHECK) { | ||
| console.warn(message); | ||
| return; | ||
| } | ||
| const limit = Error.stackTraceLimit; | ||
| if (typeof limit === "number" && limit < 25) { | ||
| Error.stackTraceLimit = 25; | ||
| } | ||
| const err = new Error(message); | ||
| if (typeof limit === "number") { | ||
| Error.stackTraceLimit = limit; | ||
| } | ||
| throw Object.assign(err, { | ||
| code: "BABEL_VERSION_UNSUPPORTED", | ||
| version: coreVersion, | ||
| range | ||
| }); | ||
| } | ||
| //# sourceMappingURL=config-api.js.map |
| {"version":3,"names":["semver","version","coreVersion","assertSimpleType","makeConfigAPI","cache","env","value","using","data","undefined","envName","Array","isArray","some","entry","Error","caller","cb","simple","async","assertVersion","makePresetAPI","externalDependencies","targets","JSON","parse","stringify","addExternalDependency","ref","push","makePluginAPI","assumption","name","assumptions","range","Number","isInteger","satisfies","message","process","BABEL_7_TO_8_DANGEROUSLY_DISABLE_VERSION_CHECK","console","warn","limit","stackTraceLimit","err","Object","assign","code"],"sources":["../../../src/config/helpers/config-api.ts"],"sourcesContent":["import semver from \"semver\";\nimport type { Targets } from \"@babel/helper-compilation-targets\";\n\nimport { version as coreVersion } from \"../../index.ts\";\nimport { assertSimpleType } from \"../caching.ts\";\nimport type {\n CacheConfigurator,\n SimpleCacheConfigurator,\n SimpleType,\n} from \"../caching.ts\";\n\nimport type {\n AssumptionName,\n CallerMetadata,\n InputOptions,\n} from \"../validation/options.ts\";\n\nimport type * as Context from \"../cache-contexts\";\n\ntype EnvName = NonNullable<InputOptions[\"envName\"]>;\ntype EnvFunction = {\n (): string;\n <T extends SimpleType>(extractor: (envName: EnvName) => T): T;\n (envVar: string): boolean;\n (envVars: string[]): boolean;\n};\n\ntype CallerFactory = {\n <T extends SimpleType>(\n extractor: (callerMetadata: CallerMetadata | undefined) => T,\n ): T;\n (\n extractor: (callerMetadata: CallerMetadata | undefined) => unknown,\n ): SimpleType;\n};\ntype TargetsFunction = () => Targets;\ntype AssumptionFunction = (name: AssumptionName) => boolean | undefined;\n\nexport type ConfigAPI = {\n version: string;\n cache: SimpleCacheConfigurator;\n env: EnvFunction;\n async: () => boolean;\n assertVersion: typeof assertVersion;\n caller?: CallerFactory;\n};\n\nexport type PresetAPI = {\n targets: TargetsFunction;\n addExternalDependency: (ref: string) => void;\n} & ConfigAPI;\n\nexport type PluginAPI = {\n assumption: AssumptionFunction;\n} & PresetAPI;\n\nexport function makeConfigAPI<SideChannel extends Context.SimpleConfig>(\n cache: CacheConfigurator<SideChannel>,\n): ConfigAPI {\n // TODO(@nicolo-ribaudo): If we remove the explicit type from `value`\n // and the `as any` type cast, TypeScript crashes in an infinite\n // recursion. After upgrading to TS4.7 and finishing the noImplicitAny\n // PR, we should check if it still crashes and report it to the TS team.\n const env: EnvFunction = ((\n value: string | string[] | (<T>(babelEnv: string) => T),\n ) =>\n cache.using(data => {\n if (value === undefined) return data.envName;\n if (typeof value === \"function\") {\n return assertSimpleType(value(data.envName));\n }\n return (Array.isArray(value) ? value : [value]).some(entry => {\n if (typeof entry !== \"string\") {\n throw new Error(\"Unexpected non-string value\");\n }\n return entry === data.envName;\n });\n })) as any;\n\n const caller = (\n cb: (CallerMetadata: CallerMetadata | undefined) => SimpleType,\n ) => cache.using(data => assertSimpleType(cb(data.caller)));\n\n return {\n version: coreVersion,\n cache: cache.simple(),\n // Expose \".env()\" so people can easily get the same env that we expose using the \"env\" key.\n env,\n async: () => false,\n caller,\n assertVersion,\n };\n}\n\nexport function makePresetAPI<SideChannel extends Context.SimplePreset>(\n cache: CacheConfigurator<SideChannel>,\n externalDependencies: string[],\n): PresetAPI {\n const targets = () =>\n // We are using JSON.parse/JSON.stringify because it's only possible to cache\n // primitive values. We can safely stringify the targets object because it\n // only contains strings as its properties.\n // Please make the Record and Tuple proposal happen!\n JSON.parse(cache.using(data => JSON.stringify(data.targets)));\n\n const addExternalDependency = (ref: string) => {\n externalDependencies.push(ref);\n };\n\n return { ...makeConfigAPI(cache), targets, addExternalDependency };\n}\n\nexport function makePluginAPI<SideChannel extends Context.SimplePlugin>(\n cache: CacheConfigurator<SideChannel>,\n externalDependencies: string[],\n): PluginAPI {\n const assumption = (name: string) =>\n cache.using(data => data.assumptions[name]);\n\n return { ...makePresetAPI(cache, externalDependencies), assumption };\n}\n\nfunction assertVersion(range: string | number): void {\n if (typeof range === \"number\") {\n if (!Number.isInteger(range)) {\n throw new Error(\"Expected string or integer value.\");\n }\n range = `^${range}.0.0-0`;\n }\n if (typeof range !== \"string\") {\n throw new Error(\"Expected string or integer value.\");\n }\n\n // We want \"*\" to also allow any pre-release, but we do not pass\n // the includePrerelease option to semver.satisfies because we\n // do not want ^7.0.0 to match 8.0.0-alpha.1.\n if (range === \"*\" || semver.satisfies(coreVersion, range)) return;\n\n const message =\n `Requires Babel \"${range}\", but was loaded with \"${coreVersion}\". ` +\n `If you are sure you have a compatible version of @babel/core, ` +\n `it is likely that something in your build process is loading the ` +\n `wrong version. Inspect the stack trace of this error to look for ` +\n `the first entry that doesn't mention \"@babel/core\" or \"babel-core\" ` +\n `to see what is calling Babel.`;\n\n if (\n typeof process !== \"undefined\" &&\n process.env.BABEL_7_TO_8_DANGEROUSLY_DISABLE_VERSION_CHECK\n ) {\n console.warn(message);\n return;\n }\n\n const limit = Error.stackTraceLimit;\n\n if (typeof limit === \"number\" && limit < 25) {\n // Bump up the limit if needed so that users are more likely\n // to be able to see what is calling Babel.\n Error.stackTraceLimit = 25;\n }\n\n const err = new Error(message);\n\n if (typeof limit === \"number\") {\n Error.stackTraceLimit = limit;\n }\n\n throw Object.assign(err, {\n code: \"BABEL_VERSION_UNSUPPORTED\",\n version: coreVersion,\n range,\n });\n}\n"],"mappings":"AAAA,OAAOA,MAAM,MAAM,QAAQ;AAG3B,SAASC,OAAO,IAAIC,WAAW,QAAQ,gBAAgB;AACvD,SAASC,gBAAgB,QAAQ,eAAe;AAoDhD,OAAO,SAASC,aAAaA,CAC3BC,KAAqC,EAC1B;EAKX,MAAMC,GAAgB,GACpBC,KAAuD,IAEvDF,KAAK,CAACG,KAAK,CAACC,IAAI,IAAI;IAClB,IAAIF,KAAK,KAAKG,SAAS,EAAE,OAAOD,IAAI,CAACE,OAAO;IAC5C,IAAI,OAAOJ,KAAK,KAAK,UAAU,EAAE;MAC/B,OAAOJ,gBAAgB,CAACI,KAAK,CAACE,IAAI,CAACE,OAAO,CAAC,CAAC;IAC9C;IACA,OAAO,CAACC,KAAK,CAACC,OAAO,CAACN,KAAK,CAAC,GAAGA,KAAK,GAAG,CAACA,KAAK,CAAC,EAAEO,IAAI,CAACC,KA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KAAsB,EAAQ;EACnD,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;IAC7B,IAAI,CAACC,MAAM,CAACC,SAAS,CAACF,KAAK,CAAC,EAAE;MAC5B,MAAM,IAAInB,KAAK,CAAC,mCAAmC,CAAC;IACtD;IACAmB,KAAK,GAAG,IAAIA,KAAK,QAAQ;EAC3B;EACA,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;IAC7B,MAAM,IAAInB,KAAK,CAAC,mCAAmC,CAAC;EACtD;EAKA,IAAImB,KAAK,KAAK,GAAG,IAAInC,MAAM,CAACsC,SAAS,CAACpC,WAAW,EAAEiC,KAAK,CAAC,EAAE;EAE3D,MAAMI,OAAO,GACX,mBAAmBJ,KAAK,2BAA2BjC,WAAW,KAAK,GACnE,gEAAgE,GAChE,mEAAmE,GACnE,mEAAmE,GACnE,qEAAqE,GACrE,+BAA+B;EAEjC,IACE,OAAOsC,OAAO,KAAK,WAAW,IAC9BA,OAAO,CAAClC,GAAG,CAACmC,8CAA8C,EAC1D;IACAC,OAAO,CAACC,IAAI,CAACJ,OAAO,CAAC;IACrB;EACF;EAEA,MAAMK,KAAK,GAAG5B,KAAK,CAAC6B,eAAe;EAEnC,IAAI,OAAOD,KAAK,KAAK,QAAQ,IAAIA,KAAK,GAAG,EAAE,EAAE;IAG3C5B,KAAK,CAAC6B,eAAe,GAAG,EAAE;EAC5B;EAEA,MAAMC,GAAG,GAAG,IAAI9B,KAAK,CAACuB,OAAO,CAAC;EAE9B,IAAI,OAAOK,KAAK,KAAK,QAAQ,EAAE;IAC7B5B,KAAK,CAAC6B,eAAe,GAAGD,KAAK;EAC/B;EAEA,MAAMG,MAAM,CAACC,MAAM,CAACF,GAAG,EAAE;IACvBG,IAAI,EAAE,2BAA2B;IACjChD,OAAO,EAAEC,WAAW;IACpBiC;EACF,CAAC,CAAC;AACJ","ignoreList":[]} |
| export function finalize(deepArr) { | ||
| return Object.freeze(deepArr); | ||
| } | ||
| export function flattenToSet(arr) { | ||
| const result = new Set(); | ||
| const stack = [arr]; | ||
| while (stack.length > 0) { | ||
| for (const el of stack.pop()) { | ||
| if (Array.isArray(el)) stack.push(el);else result.add(el); | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
| //# sourceMappingURL=deep-array.js.map |
| {"version":3,"names":["finalize","deepArr","Object","freeze","flattenToSet","arr","result","Set","stack","length","el","pop","Array","isArray","push","add"],"sources":["../../../src/config/helpers/deep-array.ts"],"sourcesContent":["export type DeepArray<T> = (T | ReadonlyDeepArray<T>)[];\n\n// Just to make sure that DeepArray<T> is not assignable to ReadonlyDeepArray<T>\ndeclare const __marker: unique symbol;\nexport type ReadonlyDeepArray<T> = readonly (T | ReadonlyDeepArray<T>)[] & {\n [__marker]: true;\n};\n\nexport function finalize<T>(deepArr: DeepArray<T>): ReadonlyDeepArray<T> {\n return Object.freeze(deepArr) as ReadonlyDeepArray<T>;\n}\n\nexport function flattenToSet<T extends string>(\n arr: ReadonlyDeepArray<T>,\n): Set<T> {\n const result = new Set<T>();\n const stack = [arr];\n while (stack.length > 0) {\n for (const el of stack.pop()) {\n if (Array.isArray(el)) stack.push(el as ReadonlyDeepArray<T>);\n else result.add(el as T);\n }\n }\n return result;\n}\n"],"mappings":"AAQA,OAAO,SAASA,QAAQA,CAAIC,OAAqB,EAAwB;EACvE,OAAOC,MAAM,CAACC,MAAM,CAACF,OAAO,CAAC;AAC/B;AAEA,OAAO,SAASG,YAAYA,CAC1BC,GAAyB,EACjB;EACR,MAAMC,MAAM,GAAG,IAAIC,GAAG,CAAI,CAAC;EAC3B,MAAMC,KAAK,GAAG,CAACH,GAAG,CAAC;EACnB,OAAOG,KAAK,CAACC,MAAM,GAAG,CAAC,EAAE;IACvB,KAAK,MAAMC,EAAE,IAAIF,KAAK,CAACG,GAAG,CAAC,CAAC,EAAE;MAC5B,IAAIC,KAAK,CAACC,OAAO,CAACH,EAAE,CAAC,EAAEF,KAAK,CAACM,IAAI,CAACJ,EAA0B,CAAC,CAAC,KACzDJ,MAAM,CAACS,GAAG,CAACL,EAAO,CAAC;IAC1B;EACF;EACA,OAAOJ,MAAM;AACf","ignoreList":[]} |
| export function getEnv(defaultValue = "development") { | ||
| return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue; | ||
| } | ||
| //# sourceMappingURL=environment.js.map |
| {"version":3,"names":["getEnv","defaultValue","process","env","BABEL_ENV","NODE_ENV"],"sources":["../../../src/config/helpers/environment.ts"],"sourcesContent":["export function getEnv(defaultValue: string = \"development\"): string {\n return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;\n}\n"],"mappings":"AAAA,OAAO,SAASA,MAAMA,CAACC,YAAoB,GAAG,aAAa,EAAU;EACnE,OAAOC,OAAO,CAACC,GAAG,CAACC,SAAS,IAAIF,OAAO,CAACC,GAAG,CAACE,QAAQ,IAAIJ,YAAY;AACtE","ignoreList":[]} |
| import gensync from "gensync"; | ||
| import loadFullConfig from "./full.js"; | ||
| import { loadPartialConfig as loadPartialConfigImpl } from "./partial.js"; | ||
| export { loadFullConfig as default }; | ||
| import { createConfigItem as createConfigItemImpl } from "./item.js"; | ||
| import { beginHiddenCallStack } from "../errors/rewrite-stack-trace.js"; | ||
| const loadPartialConfigRunner = gensync(loadPartialConfigImpl); | ||
| export function loadPartialConfigAsync(...args) { | ||
| return beginHiddenCallStack(loadPartialConfigRunner.async)(...args); | ||
| } | ||
| export function loadPartialConfigSync(...args) { | ||
| return beginHiddenCallStack(loadPartialConfigRunner.sync)(...args); | ||
| } | ||
| export function loadPartialConfig(opts, callback) { | ||
| if (callback !== undefined) { | ||
| beginHiddenCallStack(loadPartialConfigRunner.errback)(opts, callback); | ||
| } else if (typeof opts === "function") { | ||
| beginHiddenCallStack(loadPartialConfigRunner.errback)(undefined, opts); | ||
| } else { | ||
| throw new Error("Starting from Babel 8.0.0, the 'loadPartialConfig' function expects a callback. If you need to call it synchronously, please use 'loadPartialConfigSync'."); | ||
| } | ||
| } | ||
| function* loadOptionsImpl(opts) { | ||
| const config = yield* loadFullConfig(opts); | ||
| return config?.options ?? null; | ||
| } | ||
| const loadOptionsRunner = gensync(loadOptionsImpl); | ||
| export function loadOptionsAsync(...args) { | ||
| return beginHiddenCallStack(loadOptionsRunner.async)(...args); | ||
| } | ||
| export function loadOptionsSync(...args) { | ||
| return beginHiddenCallStack(loadOptionsRunner.sync)(...args); | ||
| } | ||
| export function loadOptions(opts, callback) { | ||
| if (callback !== undefined) { | ||
| beginHiddenCallStack(loadOptionsRunner.errback)(opts, callback); | ||
| } else if (typeof opts === "function") { | ||
| beginHiddenCallStack(loadOptionsRunner.errback)(undefined, opts); | ||
| } else { | ||
| throw new Error("Starting from Babel 8.0.0, the 'loadOptions' function expects a callback. If you need to call it synchronously, please use 'loadOptionsSync'."); | ||
| } | ||
| } | ||
| const createConfigItemRunner = gensync(createConfigItemImpl); | ||
| export function createConfigItemAsync(...args) { | ||
| return beginHiddenCallStack(createConfigItemRunner.async)(...args); | ||
| } | ||
| export function createConfigItemSync(...args) { | ||
| return beginHiddenCallStack(createConfigItemRunner.sync)(...args); | ||
| } | ||
| export function createConfigItem(target, options, callback) { | ||
| if (callback !== undefined) { | ||
| beginHiddenCallStack(createConfigItemRunner.errback)(target, options, callback); | ||
| } else if (typeof options === "function") { | ||
| beginHiddenCallStack(createConfigItemRunner.errback)(target, undefined, callback); | ||
| } else { | ||
| throw new Error("Starting from Babel 8.0.0, the 'createConfigItem' function expects a callback. If you need to call it synchronously, please use 'createConfigItemSync'."); | ||
| } | ||
| } | ||
| //# sourceMappingURL=index.js.map |
| {"version":3,"names":["gensync","loadFullConfig","loadPartialConfig","loadPartialConfigImpl","default","createConfigItem","createConfigItemImpl","beginHiddenCallStack","loadPartialConfigRunner","loadPartialConfigAsync","args","async","loadPartialConfigSync","sync","opts","callback","undefined","errback","Error","loadOptionsImpl","config","options","loadOptionsRunner","loadOptionsAsync","loadOptionsSync","loadOptions","createConfigItemRunner","createConfigItemAsync","createConfigItemSync","target"],"sources":["../../src/config/index.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nexport type {\n ResolvedConfig,\n InputOptions,\n PluginPasses,\n Plugin,\n} from \"./full.ts\";\n\nimport type {\n InputOptions,\n PluginTarget,\n ResolvedOptions,\n} from \"./validation/options.ts\";\nexport type { ConfigAPI } from \"./helpers/config-api.ts\";\nimport type {\n PluginAPI as basePluginAPI,\n PresetAPI as basePresetAPI,\n} from \"./helpers/config-api.ts\";\nexport type { PluginObject } from \"./validation/plugins.ts\";\ntype PluginAPI = basePluginAPI & typeof import(\"..\");\ntype PresetAPI = basePresetAPI & typeof import(\"..\");\nexport type { PluginAPI, PresetAPI };\nexport type {\n CallerMetadata,\n NormalizedOptions,\n} from \"./validation/options.ts\";\n\nimport loadFullConfig from \"./full.ts\";\nimport {\n type PartialConfig,\n loadPartialConfig as loadPartialConfigImpl,\n} from \"./partial.ts\";\n\nexport { loadFullConfig as default };\nexport type { PartialConfig } from \"./partial.ts\";\n\nimport { createConfigItem as createConfigItemImpl } from \"./item.ts\";\nimport type { ConfigItem } from \"./item.ts\";\nexport type { ConfigItem };\n\nimport { beginHiddenCallStack } from \"../errors/rewrite-stack-trace.ts\";\n\nconst loadPartialConfigRunner = gensync(loadPartialConfigImpl);\nexport function loadPartialConfigAsync(\n ...args: Parameters<typeof loadPartialConfigRunner.async>\n) {\n return beginHiddenCallStack(loadPartialConfigRunner.async)(...args);\n}\nexport function loadPartialConfigSync(\n ...args: Parameters<typeof loadPartialConfigRunner.sync>\n) {\n return beginHiddenCallStack(loadPartialConfigRunner.sync)(...args);\n}\nexport function loadPartialConfig(\n opts: Parameters<typeof loadPartialConfigImpl>[0],\n callback?: (err: Error, val: PartialConfig | null) => void,\n) {\n if (callback !== undefined) {\n beginHiddenCallStack(loadPartialConfigRunner.errback)(opts, callback);\n } else if (typeof opts === \"function\") {\n beginHiddenCallStack(loadPartialConfigRunner.errback)(\n undefined,\n opts as (err: Error, val: PartialConfig | null) => void,\n );\n } else {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'loadPartialConfig' function expects a callback. If you need to call it synchronously, please use 'loadPartialConfigSync'.\",\n );\n }\n}\n\nfunction* loadOptionsImpl(opts: InputOptions): Handler<ResolvedOptions | null> {\n const config = yield* loadFullConfig(opts);\n // NOTE: We want to return \"null\" explicitly, while ?. alone returns undefined\n return config?.options ?? null;\n}\nconst loadOptionsRunner = gensync(loadOptionsImpl);\nexport function loadOptionsAsync(\n ...args: Parameters<typeof loadOptionsRunner.async>\n) {\n return beginHiddenCallStack(loadOptionsRunner.async)(...args);\n}\nexport function loadOptionsSync(\n ...args: Parameters<typeof loadOptionsRunner.sync>\n) {\n return beginHiddenCallStack(loadOptionsRunner.sync)(...args);\n}\nexport function loadOptions(\n opts: Parameters<typeof loadOptionsImpl>[0],\n callback?: (err: Error, val: ResolvedOptions | null) => void,\n) {\n if (callback !== undefined) {\n beginHiddenCallStack(loadOptionsRunner.errback)(opts, callback);\n } else if (typeof opts === \"function\") {\n beginHiddenCallStack(loadOptionsRunner.errback)(\n undefined,\n opts as (err: Error, val: ResolvedOptions | null) => void,\n );\n } else {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'loadOptions' function expects a callback. If you need to call it synchronously, please use 'loadOptionsSync'.\",\n );\n }\n}\n\nconst createConfigItemRunner = gensync(createConfigItemImpl);\nexport function createConfigItemAsync(\n ...args: Parameters<typeof createConfigItemRunner.async>\n) {\n return beginHiddenCallStack(createConfigItemRunner.async)(...args);\n}\nexport function createConfigItemSync(\n ...args: Parameters<typeof createConfigItemRunner.sync>\n) {\n return beginHiddenCallStack(createConfigItemRunner.sync)(...args);\n}\nexport function createConfigItem(\n target: PluginTarget,\n options: Parameters<typeof createConfigItemImpl>[1],\n callback?: (err: Error, val: ConfigItem<PluginAPI> | null) => void,\n) {\n if (callback !== undefined) {\n beginHiddenCallStack(createConfigItemRunner.errback)(\n target,\n options,\n callback,\n );\n } else if (typeof options === \"function\") {\n beginHiddenCallStack(createConfigItemRunner.errback)(\n target,\n undefined,\n callback,\n );\n } else {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'createConfigItem' function expects a callback. If you need to call it synchronously, please use 'createConfigItemSync'.\",\n );\n }\n}\n"],"mappings":"AAAA,OAAOA,OAAO,MAAwB,SAAS;AA4B/C,OAAOC,cAAc,MAAM,WAAW;AACtC,SAEEC,iBAAiB,IAAIC,qBAAqB,QACrC,cAAc;AAErB,SAASF,cAAc,IAAIG,OAAO;AAGlC,SAASC,gBAAgB,IAAIC,oBAAoB,QAAQ,WAAW;AAIpE,SAASC,oBAAoB,QAAQ,kCAAkC;AAEvE,MAAMC,uBAAuB,GAAGR,OAAO,CAACG,qBAAqB,CAAC;AAC9D,OAAO,SAASM,sBAAsBA,CACpC,GAAGC,IAAsD,EACzD;EACA,OAAOH,oBAAoB,CAACC,uBAAuB,CAACG,KAAK,CAAC,CAAC,GAAGD,IAAI,CAAC;AACrE;AACA,OAAO,SAASE,qBAAqBA,CACnC,GAAGF,IAAqD,EACxD;EACA,OAAOH,oBAAoB,CAACC,uBAAuB,CAACK,IAAI,CAAC,CAAC,GAAGH,IAAI,CAAC;AACpE;AACA,OAAO,SAASR,iBAAiBA,CAC/BY,IAAiD,EACjDC,QAA0D,EAC1D;EACA,IAAIA,QAAQ,KAAKC,SAAS,EAAE;IAC1BT,oBAAoB,CAACC,uBAAuB,CAACS,OAAO,CAAC,CAACH,IAAI,EAAEC,QAAQ,CAAC;EACvE,CAAC,MAAM,IAAI,OAAOD,IAAI,KAAK,UAAU,EAAE;IACrCP,oBAAoB,CAACC,uBAAuB,CAACS,OAAO,CAAC,CACnDD,SAAS,EACTF,IACF,CAAC;EACH,CAAC,MAAM;IACL,MAAM,IAAII,KAAK,CACb,2JACF,CAAC;EACH;AACF;AAEA,UAAUC,eAAeA,CAACL,IAAkB,EAAmC;EAC7E,MAAMM,MAAM,GAAG,OAAOnB,cAAc,CAACa,IAAI,CAAC;EAE1C,OAAOM,MAAM,EAAEC,OAAO,IAAI,IAAI;AAChC;AACA,M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ACNR,OAAO,EACPN,QACF,CAAC;EACH,CAAC,MAAM,IAAI,OAAOM,OAAO,KAAK,UAAU,EAAE;IACxCd,oBAAoB,CAACmB,sBAAsB,CAACT,OAAO,CAAC,CAClDY,MAAM,EACNb,SAAS,EACTD,QACF,CAAC;EACH,CAAC,MAAM;IACL,MAAM,IAAIG,KAAK,CACb,yJACF,CAAC;EACH;AACF","ignoreList":[]} |
| import path from "node:path"; | ||
| import { createDescriptor } from "./config-descriptors.js"; | ||
| export function createItemFromDescriptor(desc) { | ||
| return new ConfigItem(desc); | ||
| } | ||
| export function* createConfigItem(value, { | ||
| dirname = ".", | ||
| type | ||
| } = {}) { | ||
| const descriptor = yield* createDescriptor(value, path.resolve(dirname), { | ||
| type, | ||
| alias: "programmatic item" | ||
| }); | ||
| return createItemFromDescriptor(descriptor); | ||
| } | ||
| const CONFIG_ITEM_BRAND = Symbol.for("@babel/core@7 - ConfigItem"); | ||
| export function getItemDescriptor(item) { | ||
| if (item?.[CONFIG_ITEM_BRAND]) { | ||
| return item._descriptor; | ||
| } | ||
| return undefined; | ||
| } | ||
| class ConfigItem { | ||
| _descriptor; | ||
| [CONFIG_ITEM_BRAND] = true; | ||
| value; | ||
| options; | ||
| dirname; | ||
| name; | ||
| file; | ||
| constructor(descriptor) { | ||
| this._descriptor = descriptor; | ||
| Object.defineProperty(this, "_descriptor", { | ||
| enumerable: false | ||
| }); | ||
| Object.defineProperty(this, CONFIG_ITEM_BRAND, { | ||
| enumerable: false | ||
| }); | ||
| this.value = this._descriptor.value; | ||
| this.options = this._descriptor.options; | ||
| this.dirname = this._descriptor.dirname; | ||
| this.name = this._descriptor.name; | ||
| this.file = this._descriptor.file ? { | ||
| request: this._descriptor.file.request, | ||
| resolved: this._descriptor.file.resolved | ||
| } : undefined; | ||
| Object.freeze(this); | ||
| } | ||
| } | ||
| Object.freeze(ConfigItem.prototype); | ||
| //# sourceMappingURL=item.js.map |
| {"version":3,"names":["path","createDescriptor","createItemFromDescriptor","desc","ConfigItem","createConfigItem","value","dirname","type","descriptor","resolve","alias","CONFIG_ITEM_BRAND","Symbol","for","getItemDescriptor","item","_descriptor","undefined","options","name","file","constructor","Object","defineProperty","enumerable","request","resolved","freeze","prototype"],"sources":["../../src/config/item.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\nimport type { PluginItem, PresetItem } from \"./validation/options.ts\";\n\nimport path from \"node:path\";\nimport { createDescriptor } from \"./config-descriptors.ts\";\n\nimport type { UnloadedDescriptor } from \"./config-descriptors.ts\";\n\nexport function createItemFromDescriptor<API>(\n desc: UnloadedDescriptor<API>,\n): ConfigItem<API> {\n return new ConfigItem(desc);\n}\n\n/**\n * Create a config item using the same value format used in Babel's config\n * files. Items returned from this function should be cached by the caller\n * ideally, as recreating the config item will mean re-resolving the item\n * and re-evaluating the plugin/preset function.\n */\nexport function* createConfigItem<API>(\n value: PluginItem | PresetItem,\n {\n dirname = \".\",\n type,\n }: {\n dirname?: string;\n type?: \"preset\" | \"plugin\";\n } = {},\n): Handler<ConfigItem<API>> {\n const descriptor = yield* createDescriptor(value, path.resolve(dirname), {\n type,\n alias: \"programmatic item\",\n });\n\n return createItemFromDescriptor(descriptor);\n}\n\nconst CONFIG_ITEM_BRAND = Symbol.for(\"@babel/core@7 - ConfigItem\");\n\nexport function getItemDescriptor<API>(\n item: unknown,\n): UnloadedDescriptor<API> | void {\n if ((item as any)?.[CONFIG_ITEM_BRAND]) {\n return (item as ConfigItem<API>)._descriptor;\n }\n\n return undefined;\n}\n\nexport type { ConfigItem };\n\n/**\n * A public representation of a plugin/preset that will _eventually_ be load.\n * Users can use this to interact with the results of a loaded Babel\n * configuration.\n *\n * Any changes to public properties of this class should be considered a\n * breaking change to Babel's API.\n */\nclass ConfigItem<API> {\n /**\n * The private underlying descriptor that Babel actually cares about.\n * If you access this, you are a bad person.\n */\n _descriptor: UnloadedDescriptor<API>;\n\n // TODO(Babel 9): Check if this symbol needs to be updated\n /**\n * Used to detect ConfigItem instances from other Babel instances.\n */\n [CONFIG_ITEM_BRAND] = true;\n\n /**\n * The resolved value of the item itself.\n */\n value: object | Function;\n\n /**\n * The options, if any, that were passed to the item.\n * Mutating this will lead to undefined behavior.\n *\n * \"false\" means that this item has been disabled.\n */\n options: object | void | false;\n\n /**\n * The directory that the options for this item are relative to.\n */\n dirname: string;\n\n /**\n * Get the name of the plugin, if the user gave it one.\n */\n name: string | void;\n\n /**\n * Data about the file that the item was loaded from, if Babel knows it.\n */\n file: {\n // The requested path, e.g. \"@babel/env\".\n request: string;\n // The resolved absolute path of the file.\n resolved: string;\n } | void;\n\n constructor(descriptor: UnloadedDescriptor<API>) {\n // Make people less likely to stumble onto this if they are exploring\n // programmatically, and also make sure that if people happen to\n // pass the item through JSON.stringify, it doesn't show up.\n this._descriptor = descriptor;\n Object.defineProperty(this, \"_descriptor\", { enumerable: false });\n\n Object.defineProperty(this, CONFIG_ITEM_BRAND, { enumerable: false });\n\n this.value = this._descriptor.value;\n this.options = this._descriptor.options;\n this.dirname = this._descriptor.dirname;\n this.name = this._descriptor.name;\n this.file = this._descriptor.file\n ? {\n request: this._descriptor.file.request,\n resolved: this._descriptor.file.resolved,\n }\n : undefined;\n\n // Freeze the object to make it clear that people shouldn't expect mutating\n // this object to do anything. A new item should be created if they want\n // to change something.\n Object.freeze(this);\n }\n}\n\nObject.freeze(ConfigItem.prototype);\n"],"mappings":"AAGA,OAAOA,IAAI,MAAM,WAAW;AAC5B,SAASC,gBAAgB,QAAQ,yBAAyB;AAI1D,OAAO,SAASC,wBAAwBA,CACtCC,IAA6B,EACZ;EACjB,OAAO,IAAIC,UAAU,CAACD,IAAI,CAAC;AAC7B;AAQA,OAAO,UAAUE,gBAAgBA,CAC/BC,KAA8B,EAC9B;EACEC,OAAO,GAAG,GAAG;EACbC;AAIF,CAAC,GAAG,CAAC,CAAC,EACoB;EAC1B,MAAMC,UAAU,GAAG,OAAOR,gBAAgB,CAACK,KAAK,EAAEN,IAAI,CAACU,OAAO,CAACH,OAAO,CAAC,E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;EACrB;AACF;AAEAL,MAAM,CAACK,MAAM,CAACxB,UAAU,CAACyB,SAAS,CAAC","ignoreList":[]} |
| import path from "node:path"; | ||
| import Plugin from "./plugin.js"; | ||
| import { mergeOptions } from "./util.js"; | ||
| import { createItemFromDescriptor } from "./item.js"; | ||
| import { buildRootChain } from "./config-chain.js"; | ||
| import { getEnv } from "./helpers/environment.js"; | ||
| import { validate } from "./validation/options.js"; | ||
| import { findConfigUpwards, resolveShowConfigPath, ROOT_CONFIG_FILENAMES } from "./files/index.js"; | ||
| import { resolveTargets } from "./resolve-targets.js"; | ||
| function resolveRootMode(rootDir, rootMode) { | ||
| switch (rootMode) { | ||
| case "root": | ||
| return rootDir; | ||
| case "upward-optional": | ||
| { | ||
| const upwardRootDir = findConfigUpwards(rootDir); | ||
| return upwardRootDir === null ? rootDir : upwardRootDir; | ||
| } | ||
| case "upward": | ||
| { | ||
| const upwardRootDir = findConfigUpwards(rootDir); | ||
| if (upwardRootDir !== null) return upwardRootDir; | ||
| throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}".\n` + `One of the following config files must be in the directory tree: ` + `"${ROOT_CONFIG_FILENAMES.join(", ")}".`), { | ||
| code: "BABEL_ROOT_NOT_FOUND", | ||
| dirname: rootDir | ||
| }); | ||
| } | ||
| default: | ||
| throw new Error(`Assertion failure - unknown rootMode value.`); | ||
| } | ||
| } | ||
| export default function* loadPrivatePartialConfig(inputOpts) { | ||
| if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) { | ||
| throw new Error("Babel options must be an object, null, or undefined"); | ||
| } | ||
| const args = inputOpts ? validate("arguments", inputOpts) : {}; | ||
| const { | ||
| envName = getEnv(), | ||
| cwd = ".", | ||
| root: rootDir = ".", | ||
| rootMode = "root", | ||
| caller, | ||
| cloneInputAst = true | ||
| } = args; | ||
| const absoluteCwd = path.resolve(cwd); | ||
| const absoluteRootDir = resolveRootMode(path.resolve(absoluteCwd, rootDir), rootMode); | ||
| const filename = typeof args.filename === "string" ? path.resolve(cwd, args.filename) : undefined; | ||
| const showConfigPath = yield* resolveShowConfigPath(absoluteCwd); | ||
| const context = { | ||
| filename, | ||
| cwd: absoluteCwd, | ||
| root: absoluteRootDir, | ||
| envName, | ||
| caller, | ||
| showConfig: showConfigPath === filename | ||
| }; | ||
| const configChain = yield* buildRootChain(args, context); | ||
| if (!configChain) return null; | ||
| const merged = { | ||
| assumptions: {} | ||
| }; | ||
| configChain.options.forEach(opts => { | ||
| mergeOptions(merged, opts); | ||
| }); | ||
| const options = { | ||
| ...merged, | ||
| targets: resolveTargets(merged, absoluteRootDir), | ||
| cloneInputAst, | ||
| babelrc: false, | ||
| configFile: false, | ||
| browserslistConfigFile: false, | ||
| passPerPreset: false, | ||
| envName: context.envName, | ||
| cwd: context.cwd, | ||
| root: context.root, | ||
| rootMode: "root", | ||
| filename: typeof context.filename === "string" ? context.filename : undefined, | ||
| plugins: configChain.plugins.map(descriptor => createItemFromDescriptor(descriptor)), | ||
| presets: configChain.presets.map(descriptor => createItemFromDescriptor(descriptor)) | ||
| }; | ||
| return { | ||
| options, | ||
| context, | ||
| fileHandling: configChain.fileHandling, | ||
| ignore: configChain.ignore, | ||
| babelrc: configChain.babelrc, | ||
| config: configChain.config, | ||
| files: configChain.files | ||
| }; | ||
| } | ||
| export function* loadPartialConfig(opts) { | ||
| let showIgnoredFiles = false; | ||
| if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) { | ||
| ({ | ||
| showIgnoredFiles, | ||
| ...opts | ||
| } = opts); | ||
| } | ||
| const result = yield* loadPrivatePartialConfig(opts); | ||
| if (!result) return null; | ||
| const { | ||
| options, | ||
| babelrc, | ||
| ignore, | ||
| config, | ||
| fileHandling, | ||
| files | ||
| } = result; | ||
| if (fileHandling === "ignored" && !showIgnoredFiles) { | ||
| return null; | ||
| } | ||
| (options.plugins || []).forEach(item => { | ||
| if (item.value instanceof Plugin) { | ||
| throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()"); | ||
| } | ||
| }); | ||
| return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined, fileHandling, files); | ||
| } | ||
| class PartialConfig { | ||
| options; | ||
| babelrc; | ||
| babelignore; | ||
| config; | ||
| fileHandling; | ||
| files; | ||
| constructor(options, babelrc, ignore, config, fileHandling, files) { | ||
| this.options = options; | ||
| this.babelignore = ignore; | ||
| this.babelrc = babelrc; | ||
| this.config = config; | ||
| this.fileHandling = fileHandling; | ||
| this.files = files; | ||
| Object.freeze(this); | ||
| } | ||
| hasFilesystemConfig() { | ||
| return this.babelrc !== undefined || this.config !== undefined; | ||
| } | ||
| } | ||
| Object.freeze(PartialConfig.prototype); | ||
| //# sourceMappingURL=partial.js.map |
| {"version":3,"names":["path","Plugin","mergeOptions","createItemFromDescriptor","buildRootChain","getEnv","validate","findConfigUpwards","resolveShowConfigPath","ROOT_CONFIG_FILENAMES","resolveTargets","resolveRootMode","rootDir","rootMode","upwardRootDir","Object","assign","Error","join","code","dirname","loadPrivatePartialConfig","inputOpts","Array","isArray","args","envName","cwd","root","caller","cloneInputAst","absoluteCwd","resolve","absoluteRootDir","filename","undefined","showConfigPath","context","showConfig","configChain","merged","assumptions","options","forEach","opts","targets","babelrc","configFile","browserslistConfigFile","passPerPreset","plugins","map","descriptor","presets","fileHandling","ignore","config","files","loadPartialConfig","showIgnoredFiles","result","item","value","PartialConfig","filepath","babelignore","constructor","freeze","hasFilesystemConfig","prototype"],"sources":["../../src/config/partial.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { Handler } from \"gensync\";\nimport Plugin from \"./plugin.ts\";\nimport { mergeOptions } from \"./util.ts\";\nimport { createItemFromDescriptor } from \"./item.ts\";\nimport { buildRootChain } from \"./config-chain.ts\";\nimport type { ConfigContext, FileHandling } from \"./config-chain.ts\";\nimport { getEnv } from \"./helpers/environment.ts\";\nimport { validate } from \"./validation/options.ts\";\n\nimport type {\n RootMode,\n InputOptions,\n NormalizedOptions,\n} from \"./validation/options.ts\";\n\nimport {\n findConfigUpwards,\n resolveShowConfigPath,\n ROOT_CONFIG_FILENAMES,\n} from \"./files/index.ts\";\nimport type { ConfigFile, IgnoreFile } from \"./files/index.ts\";\nimport { resolveTargets } from \"./resolve-targets.ts\";\n\nfunction resolveRootMode(rootDir: string, rootMode: RootMode): string {\n switch (rootMode) {\n case \"root\":\n return rootDir;\n\n case \"upward-optional\": {\n const upwardRootDir = findConfigUpwards(rootDir);\n return upwardRootDir === null ? rootDir : upwardRootDir;\n }\n\n case \"upward\": {\n const upwardRootDir = findConfigUpwards(rootDir);\n if (upwardRootDir !== null) return upwardRootDir;\n\n throw Object.assign(\n new Error(\n `Babel was run with rootMode:\"upward\" but a root could not ` +\n `be found when searching upward from \"${rootDir}\".\\n` +\n `One of the following config files must be in the directory tree: ` +\n `\"${ROOT_CONFIG_FILENAMES.join(\", \")}\".`,\n ) as any,\n {\n code: \"BABEL_ROOT_NOT_FOUND\",\n dirname: rootDir,\n },\n );\n }\n default:\n throw new Error(`Assertion failure - unknown rootMode value.`);\n }\n}\n\nexport type PrivPartialConfig = {\n showIgnoredFiles?: boolean;\n options: NormalizedOptions;\n context: ConfigContext;\n babelrc: ConfigFile | undefined;\n config: ConfigFile | undefined;\n ignore: IgnoreFile | undefined;\n fileHandling: FileHandling;\n files: Set<string>;\n};\n\nexport default function* loadPrivatePartialConfig(\n inputOpts: InputOptions,\n): Handler<PrivPartialConfig | null> {\n if (\n inputOpts != null &&\n (typeof inputOpts !== \"object\" || Array.isArray(inputOpts))\n ) {\n throw new Error(\"Babel options must be an object, null, or undefined\");\n }\n\n const args = inputOpts ? validate(\"arguments\", inputOpts) : {};\n\n const {\n envName = getEnv(),\n cwd = \".\",\n root: rootDir = \".\",\n rootMode = \"root\",\n caller,\n cloneInputAst = true,\n } = args;\n const absoluteCwd = path.resolve(cwd);\n const absoluteRootDir = resolveRootMode(\n path.resolve(absoluteCwd, rootDir),\n rootMode,\n );\n\n const filename =\n typeof args.filename === \"string\"\n ? path.resolve(cwd, args.filename)\n : undefined;\n\n const showConfigPath = yield* resolveShowConfigPath(absoluteCwd);\n\n const context: ConfigContext = {\n filename,\n cwd: absoluteCwd,\n root: absoluteRootDir,\n envName,\n caller,\n showConfig: showConfigPath === filename,\n };\n\n const configChain = yield* buildRootChain(args, context);\n if (!configChain) return null;\n\n const merged = {\n assumptions: {},\n };\n configChain.options.forEach(opts => {\n mergeOptions(merged as any, opts);\n });\n\n const options: NormalizedOptions = {\n ...merged,\n targets: resolveTargets(merged, absoluteRootDir),\n\n // Tack the passes onto the object itself so that, if this object is\n // passed back to Babel a second time, it will be in the right structure\n // to not change behavior.\n cloneInputAst,\n babelrc: false,\n configFile: false,\n browserslistConfigFile: false,\n passPerPreset: false,\n envName: context.envName,\n cwd: context.cwd,\n root: context.root,\n rootMode: \"root\",\n filename:\n typeof context.filename === \"string\" ? context.filename : undefined,\n\n plugins: configChain.plugins.map(descriptor =>\n createItemFromDescriptor(descriptor),\n ),\n presets: configChain.presets.map(descriptor =>\n createItemFromDescriptor(descriptor),\n ),\n };\n\n return {\n options,\n context,\n fileHandling: configChain.fileHandling,\n ignore: configChain.ignore,\n babelrc: configChain.babelrc,\n config: configChain.config,\n files: configChain.files,\n };\n}\n\nexport function* loadPartialConfig(\n opts?: InputOptions,\n): Handler<PartialConfig | null> {\n let showIgnoredFiles = false;\n // We only extract showIgnoredFiles if opts is an object, so that\n // loadPrivatePartialConfig can throw the appropriate error if it's not.\n if (typeof opts === \"object\" && opts !== null && !Array.isArray(opts)) {\n ({ showIgnoredFiles, ...opts } = opts);\n }\n\n const result: PrivPartialConfig | undefined | null =\n yield* loadPrivatePartialConfig(opts);\n if (!result) return null;\n\n const { options, babelrc, ignore, config, fileHandling, files } = result;\n\n if (fileHandling === \"ignored\" && !showIgnoredFiles) {\n return null;\n }\n\n (options.plugins || []).forEach(item => {\n if (item.value instanceof Plugin) {\n throw new Error(\n \"Passing cached plugin instances is not supported in \" +\n \"babel.loadPartialConfig()\",\n );\n }\n });\n\n return new PartialConfig(\n options,\n babelrc ? babelrc.filepath : undefined,\n ignore ? ignore.filepath : undefined,\n config ? config.filepath : undefined,\n fileHandling,\n files,\n );\n}\n\nexport type { PartialConfig };\n\nclass PartialConfig {\n /**\n * These properties are public, so any changes to them should be considered\n * a breaking change to Babel's API.\n */\n options: NormalizedOptions;\n babelrc: string | undefined;\n babelignore: string | undefined;\n config: string | undefined;\n fileHandling: FileHandling;\n files: Set<string>;\n\n constructor(\n options: NormalizedOptions,\n babelrc: string | undefined,\n ignore: string | undefined,\n config: string | undefined,\n fileHandling: FileHandling,\n files: Set<string>,\n ) {\n this.options = options;\n this.babelignore = ignore;\n this.babelrc = babelrc;\n this.config = config;\n this.fileHandling = fileHandling;\n this.files = files;\n\n // Freeze since this is a public API and it should be extremely obvious that\n // reassigning properties on here does nothing.\n Object.freeze(this);\n }\n\n /**\n * Returns true if there is a config file in the filesystem for this config.\n */\n hasFilesystemConfig(): boolean {\n return this.babelrc !== undefined || this.config !== undefined;\n }\n}\nObject.freeze(PartialConfig.prototype);\n"],"mappings":"AAAA,OAAOA,IAAI,MAAM,WAAW;AAE5B,OAAOC,MAAM,MAAM,aAAa;AAChC,SAASC,YAAY,QAAQ,WAAW;AACxC,SAASC,wBAAwB,QAAQ,WAAW;AACpD,SAASC,cAAc,QAAQ,mBAAmB;AAElD,SAASC,MAAM,QAAQ,0BAA0B;AACjD,SAASC,QAAQ,QAAQ,yBAAyB;AAQlD,SACEC,iBAAiB,EACjBC,qBAAqB,EACrBC,qBAAqB,QAChB,kBAAkB;AAEzB,SAASC,cAAc,QAAQ,sBAAsB;AAErD,SAASC,eAAeA,CAACC,OAAe,EAAEC,QAAkB,EAAU;EACpE,QAAQA,QAAQ;IACd,KAAK,MAAM;MACT,OAAOD,OAAO;IAEhB,KAAK,iBAAiB;MAAE;QACtB,MAAME,aAAa,GAAGP,iBAAiB,CAACK,OAAO,CAAC;QA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S,QAAQ,GAAG7B,SAAS,EACpCqB,MAAM,GAAGA,MAAM,CAACQ,QAAQ,GAAG7B,SAAS,EACpCmB,YAAY,EACZG,KACF,CAAC;AACH;AAIA,MAAMM,aAAa,CAAC;EAKlBrB,OAAO;EACPI,OAAO;EACPmB,WAAW;EACXT,MAAM;EACNF,YAAY;EACZG,KAAK;EAELS,WAAWA,CACTxB,OAA0B,EAC1BI,OAA2B,EAC3BS,MAA0B,EAC1BC,MAA0B,EAC1BF,YAA0B,EAC1BG,KAAkB,EAClB;IACA,IAAI,CAACf,OAAO,GAAGA,OAAO;IACtB,IAAI,CAACuB,WAAW,GAAGV,MAAM;IACzB,IAAI,CAACT,OAAO,GAAGA,OAAO;IACtB,IAAI,CAACU,MAAM,GAAGA,MAAM;IACpB,IAAI,CAACF,YAAY,GAAGA,YAAY;IAChC,IAAI,CAACG,KAAK,GAAGA,KAAK;IAIlB1C,MAAM,CAACoD,MAAM,CAAC,IAAI,CAAC;EACrB;EAKAC,mBAAmBA,CAAA,EAAY;IAC7B,OAAO,IAAI,CAACtB,OAAO,KAAKX,SAAS,IAAI,IAAI,CAACqB,MAAM,KAAKrB,SAAS;EAChE;AACF;AACApB,MAAM,CAACoD,MAAM,CAACJ,aAAa,CAACM,SAAS,CAAC","ignoreList":[]} |
| import path from "node:path"; | ||
| const sep = `\\${path.sep}`; | ||
| const endSep = `(?:${sep}|$)`; | ||
| const substitution = `[^${sep}]+`; | ||
| const starPat = `(?:${substitution}${sep})`; | ||
| const starPatLast = `(?:${substitution}${endSep})`; | ||
| const starStarPat = `${starPat}*?`; | ||
| const starStarPatLast = `${starPat}*?${starPatLast}?`; | ||
| function escapeRegExp(string) { | ||
| return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&"); | ||
| } | ||
| export default function pathToPattern(pattern, dirname) { | ||
| const parts = path.resolve(dirname, pattern).split(path.sep); | ||
| return new RegExp(["^", ...parts.map((part, i) => { | ||
| const last = i === parts.length - 1; | ||
| if (part === "**") return last ? starStarPatLast : starStarPat; | ||
| if (part === "*") return last ? starPatLast : starPat; | ||
| if (part.startsWith("*.")) { | ||
| return substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep); | ||
| } | ||
| return escapeRegExp(part) + (last ? endSep : sep); | ||
| })].join("")); | ||
| } | ||
| //# sourceMappingURL=pattern-to-regex.js.map |
| {"version":3,"names":["path","sep","endSep","substitution","starPat","starPatLast","starStarPat","starStarPatLast","escapeRegExp","string","replace","pathToPattern","pattern","dirname","parts","resolve","split","RegExp","map","part","i","last","length","startsWith","slice","join"],"sources":["../../src/config/pattern-to-regex.ts"],"sourcesContent":["import path from \"node:path\";\n\nconst sep = `\\\\${path.sep}`;\nconst endSep = `(?:${sep}|$)`;\n\nconst substitution = `[^${sep}]+`;\n\nconst starPat = `(?:${substitution}${sep})`;\nconst starPatLast = `(?:${substitution}${endSep})`;\n\nconst starStarPat = `${starPat}*?`;\nconst starStarPatLast = `${starPat}*?${starPatLast}?`;\n\nfunction escapeRegExp(string: string) {\n return string.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n}\n\n/**\n * Implement basic pattern matching that will allow users to do the simple\n * tests with * and **. If users want full complex pattern matching, then can\n * always use regex matching, or function validation.\n */\nexport default function pathToPattern(\n pattern: string,\n dirname: string,\n): RegExp {\n const parts = path.resolve(dirname, pattern).split(path.sep);\n\n return new RegExp(\n [\n \"^\",\n ...parts.map((part, i) => {\n const last = i === parts.length - 1;\n\n // ** matches 0 or more path parts.\n if (part === \"**\") return last ? starStarPatLast : starStarPat;\n\n // * matches 1 path part.\n if (part === \"*\") return last ? starPatLast : starPat;\n\n // *.ext matches a wildcard with an extension.\n if (part.startsWith(\"*.\")) {\n return (\n substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep)\n );\n }\n\n // Otherwise match the pattern text.\n return escapeRegExp(part) + (last ? endSep : sep);\n }),\n ].join(\"\"),\n );\n}\n"],"mappings":"AAAA,OAAOA,IAAI,MAAM,WAAW;AAE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,MAAM,GAAGD,GAAG,CAAC;EACnD,CAAC,CAAC,CACH,CAACwB,IAAI,CAAC,EAAE,CACX,CAAC;AACH","ignoreList":[]} |
| import { finalize } from "./helpers/deep-array.js"; | ||
| export default class Plugin { | ||
| key; | ||
| manipulateOptions; | ||
| post; | ||
| pre; | ||
| visitor; | ||
| parserOverride; | ||
| generatorOverride; | ||
| options; | ||
| externalDependencies; | ||
| constructor(plugin, options, key, externalDependencies = finalize([])) { | ||
| this.key = plugin.name || key; | ||
| this.manipulateOptions = plugin.manipulateOptions; | ||
| this.post = plugin.post; | ||
| this.pre = plugin.pre; | ||
| this.visitor = plugin.visitor || {}; | ||
| this.parserOverride = plugin.parserOverride; | ||
| this.generatorOverride = plugin.generatorOverride; | ||
| this.options = options; | ||
| this.externalDependencies = externalDependencies; | ||
| } | ||
| } | ||
| //# sourceMappingURL=plugin.js.map |
| {"version":3,"names":["finalize","Plugin","key","manipulateOptions","post","pre","visitor","parserOverride","generatorOverride","options","externalDependencies","constructor","plugin","name"],"sources":["../../src/config/plugin.ts"],"sourcesContent":["import { finalize } from \"./helpers/deep-array.ts\";\nimport type { ReadonlyDeepArray } from \"./helpers/deep-array.ts\";\nimport type { PluginObject } from \"./validation/plugins.ts\";\n\nexport default class Plugin {\n key: string | undefined | null;\n manipulateOptions?: PluginObject[\"manipulateOptions\"];\n post?: PluginObject[\"post\"];\n pre?: PluginObject[\"pre\"];\n visitor: PluginObject[\"visitor\"];\n\n parserOverride?: PluginObject[\"parserOverride\"];\n generatorOverride?: PluginObject[\"generatorOverride\"];\n\n options: object;\n\n externalDependencies: ReadonlyDeepArray<string>;\n\n constructor(\n plugin: PluginObject,\n options: object,\n key?: string,\n externalDependencies: ReadonlyDeepArray<string> = finalize([]),\n ) {\n this.key = plugin.name || key;\n\n this.manipulateOptions = plugin.manipulateOptions;\n this.post = plugin.post;\n this.pre = plugin.pre;\n this.visitor = plugin.visitor || {};\n this.parserOverride = plugin.parserOverride;\n this.generatorOverride = plugin.generatorOverride;\n\n this.options = options;\n this.externalDependencies = externalDependencies;\n }\n}\n"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,yBAAyB;AAIlD,eAAe,MAAMC,MAAM,CAAC;EAC1BC,GAAG;EACHC,iBAAiB;EACjBC,IAAI;EACJC,GAAG;EACHC,OAAO;EAEPC,cAAc;EACdC,iBAAiB;EAEjBC,OAAO;EAEPC,oBAAoB;EAEpBC,WAAWA,CACTC,MAAoB,EACpBH,OAAe,EACfP,GAAY,EACZQ,oBAA+C,GAAGV,QAAQ,CAAC,EAAE,CAAC,EAC9D;IACA,IAAI,CAACE,GAAG,GAAGU,MAAM,CAACC,IAAI,IAAIX,GAAG;IAE7B,IAAI,CAACC,iBAAiB,GAAGS,MAAM,CAACT,iBAAiB;IACjD,IAAI,CAACC,IAAI,GAAGQ,MAAM,CAACR,IAAI;IACvB,IAAI,CAACC,GAAG,GAAGO,MAAM,CAACP,GAAG;IACrB,IAAI,CAACC,OAAO,GAAGM,MAAM,CAACN,OAAO,IAAI,CAAC,CAAC;IACnC,IAAI,CAACC,cAAc,GAAGK,MAAM,CAACL,cAAc;IAC3C,IAAI,CAACC,iBAAiB,GAAGI,MAAM,CAACJ,iBAAiB;IAEjD,IAAI,CAACC,OAAO,GAAGA,OAAO;IACtB,IAAI,CAACC,oBAAoB,GAAGA,oBAAoB;EAClD;AACF","ignoreList":[]} |
| import gensync from "gensync"; | ||
| export const ChainFormatter = { | ||
| Programmatic: 0, | ||
| Config: 1 | ||
| }; | ||
| const Formatter = { | ||
| title(type, callerName, filepath) { | ||
| let title = ""; | ||
| if (type === ChainFormatter.Programmatic) { | ||
| title = "programmatic options"; | ||
| if (callerName) { | ||
| title += " from " + callerName; | ||
| } | ||
| } else { | ||
| title = "config " + filepath; | ||
| } | ||
| return title; | ||
| }, | ||
| loc(index, envName) { | ||
| let loc = ""; | ||
| if (index != null) { | ||
| loc += `.overrides[${index}]`; | ||
| } | ||
| if (envName != null) { | ||
| loc += `.env["${envName}"]`; | ||
| } | ||
| return loc; | ||
| }, | ||
| *optionsAndDescriptors(opt) { | ||
| const content = { | ||
| ...opt.options | ||
| }; | ||
| delete content.overrides; | ||
| delete content.env; | ||
| const pluginDescriptors = [...(yield* opt.plugins())]; | ||
| if (pluginDescriptors.length) { | ||
| content.plugins = pluginDescriptors.map(d => descriptorToConfig(d)); | ||
| } | ||
| const presetDescriptors = [...(yield* opt.presets())]; | ||
| if (presetDescriptors.length) { | ||
| content.presets = [...presetDescriptors].map(d => descriptorToConfig(d)); | ||
| } | ||
| return JSON.stringify(content, undefined, 2); | ||
| } | ||
| }; | ||
| function descriptorToConfig(d) { | ||
| let name = d.file?.request; | ||
| if (name == null) { | ||
| if (typeof d.value === "object") { | ||
| name = d.value; | ||
| } else if (typeof d.value === "function") { | ||
| name = `[Function: ${d.value.toString().slice(0, 50)} ... ]`; | ||
| } | ||
| } | ||
| if (name == null) { | ||
| name = "[Unknown]"; | ||
| } | ||
| if (d.options === undefined) { | ||
| return name; | ||
| } else if (d.name == null) { | ||
| return [name, d.options]; | ||
| } else { | ||
| return [name, d.options, d.name]; | ||
| } | ||
| } | ||
| export class ConfigPrinter { | ||
| _stack = []; | ||
| configure(enabled, type, { | ||
| callerName, | ||
| filepath | ||
| }) { | ||
| if (!enabled) return () => {}; | ||
| return (content, index, envName) => { | ||
| this._stack.push({ | ||
| type, | ||
| callerName, | ||
| filepath, | ||
| content, | ||
| index, | ||
| envName | ||
| }); | ||
| }; | ||
| } | ||
| static *format(config) { | ||
| let title = Formatter.title(config.type, config.callerName, config.filepath); | ||
| const loc = Formatter.loc(config.index, config.envName); | ||
| if (loc) title += ` ${loc}`; | ||
| const content = yield* Formatter.optionsAndDescriptors(config.content); | ||
| return `${title}\n${content}`; | ||
| } | ||
| *output() { | ||
| if (this._stack.length === 0) return ""; | ||
| const configs = yield* gensync.all(this._stack.map(s => ConfigPrinter.format(s))); | ||
| return configs.join("\n\n"); | ||
| } | ||
| } | ||
| //# sourceMappingURL=printer.js.map |
| {"version":3,"names":["gensync","ChainFormatter","Programmatic","Config","Formatter","title","type","callerName","filepath","loc","index","envName","optionsAndDescriptors","opt","content","options","overrides","env","pluginDescriptors","plugins","length","map","d","descriptorToConfig","presetDescriptors","presets","JSON","stringify","undefined","name","file","request","value","toString","slice","ConfigPrinter","_stack","configure","enabled","push","format","config","output","configs","all","s","join"],"sources":["../../src/config/printer.ts"],"sourcesContent":["import gensync from \"gensync\";\n\nimport type { Handler } from \"gensync\";\n\nimport type {\n OptionsAndDescriptors,\n UnloadedDescriptor,\n} from \"./config-descriptors.ts\";\n\n// todo: Use flow enums when @babel/transform-flow-types supports it\nexport const ChainFormatter = {\n Programmatic: 0,\n Config: 1,\n};\n\ntype PrintableConfig = {\n content: OptionsAndDescriptors;\n type: (typeof ChainFormatter)[keyof typeof ChainFormatter];\n callerName: string | undefined | null;\n filepath: string | undefined | null;\n index: number | undefined | null;\n envName: string | undefined | null;\n};\n\nconst Formatter = {\n title(\n type: (typeof ChainFormatter)[keyof typeof ChainFormatter],\n callerName?: string | null,\n filepath?: string | null,\n ): string {\n let title = \"\";\n if (type === ChainFormatter.Programmatic) {\n title = \"programmatic options\";\n if (callerName) {\n title += \" from \" + callerName;\n }\n } else {\n title = \"config \" + filepath;\n }\n return title;\n },\n loc(index?: number | null, envName?: string | null): string {\n let loc = \"\";\n if (index != null) {\n loc += `.overrides[${index}]`;\n }\n if (envName != null) {\n loc += `.env[\"${envName}\"]`;\n }\n return loc;\n },\n\n *optionsAndDescriptors(opt: OptionsAndDescriptors) {\n const content = { ...opt.options };\n // overrides and env will be printed as separated config items\n delete content.overrides;\n delete content.env;\n // resolve to descriptors\n const pluginDescriptors = [...(yield* opt.plugins())];\n if (pluginDescriptors.length) {\n content.plugins = pluginDescriptors.map(d => descriptorToConfig(d));\n }\n const presetDescriptors = [...(yield* opt.presets())];\n if (presetDescriptors.length) {\n content.presets = [...presetDescriptors].map(d => descriptorToConfig(d));\n }\n return JSON.stringify(content, undefined, 2);\n },\n};\n\nfunction descriptorToConfig<API>(\n d: UnloadedDescriptor<API>,\n): string | [string, object] | [string, object, string] {\n let name: string = d.file?.request;\n if (name == null) {\n if (typeof d.value === \"object\") {\n // @ts-expect-error FIXME\n name = d.value;\n } else if (typeof d.value === \"function\") {\n // If the unloaded descriptor is a function, i.e. `plugins: [ require(\"my-plugin\") ]`,\n // we print the first 50 characters of the function source code and hopefully we can see\n // `name: 'my-plugin'` in the source\n name = `[Function: ${d.value.toString().slice(0, 50)} ... ]`;\n }\n }\n if (name == null) {\n name = \"[Unknown]\";\n }\n if (d.options === undefined) {\n return name;\n } else if (d.name == null) {\n return [name, d.options];\n } else {\n return [name, d.options, d.name];\n }\n}\n\nexport class ConfigPrinter {\n _stack: PrintableConfig[] = [];\n configure(\n enabled: boolean,\n type: (typeof ChainFormatter)[keyof typeof ChainFormatter],\n {\n callerName,\n filepath,\n }: {\n callerName?: string;\n filepath?: string;\n },\n ) {\n if (!enabled) return () => {};\n return (\n content: OptionsAndDescriptors,\n index?: number | null,\n envName?: string | null,\n ) => {\n this._stack.push({\n type,\n callerName,\n filepath,\n content,\n index,\n envName,\n });\n };\n }\n static *format(config: PrintableConfig): Handler<string> {\n let title = Formatter.title(\n config.type,\n config.callerName,\n config.filepath,\n );\n const loc = Formatter.loc(config.index, config.envName);\n if (loc) title += ` ${loc}`;\n const content = yield* Formatter.optionsAndDescriptors(config.content);\n return `${title}\\n${content}`;\n }\n\n *output(): Handler<string> {\n if (this._stack.length === 0) return \"\";\n const configs = yield* gensync.all(\n this._stack.map(s => ConfigPrinter.format(s)),\n );\n return configs.join(\"\\n\\n\");\n }\n}\n"],"mappings":"AAAA,OAAOA,OAAO,MAAM,SAAS;AAU7B,OAAO,MAAMC,cAAc,GAAG;EAC5BC,YAAY,EAAE,CAAC;EACfC,MAAM,EAAE;AACV,CAAC;AAWD,MAAMC,SAAS,GAAG;EAChBC,KAAKA,CACHC,IAA0D,EAC1DC,UAA0B,EAC1BC,QAAwB,EAChB;IACR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;MACF,CAAC,CAAC;IACJ,CAAC;EACH;EACA,QAAQ6B,MAAMA,CAACC,MAAuB,EAAmB;IACvD,IAAIpC,KAAK,GAAGD,SAAS,CAACC,KAAK,CACzBoC,MAAM,CAACnC,IAAI,EACXmC,MAAM,CAAClC,UAAU,EACjBkC,MAAM,CAACjC,QACT,CAAC;IACD,MAAMC,GAAG,GAAGL,SAAS,CAACK,GAAG,CAACgC,MAAM,CAAC/B,KAAK,EAAE+B,MAAM,CAAC9B,OAAO,CAAC;IACvD,IAAIF,GAAG,EAAEJ,KAAK,IAAI,IAAII,GAAG,EAAE;IAC3B,MAAMK,OAAO,GAAG,OAAOV,SAAS,CAACQ,qBAAqB,CAAC6B,MAAM,CAAC3B,OAAO,CAAC;IACtE,OAAO,GAAGT,KAAK,KAAKS,OAAO,EAAE;EAC/B;EAEA,CAAC4B,MAAMA,CAAA,EAAoB;IACzB,IAAI,IAAI,CAACN,MAAM,CAAChB,MAAM,KAAK,CAAC,EAAE,OAAO,EAAE;IACvC,MAAMuB,OAAO,GAAG,OAAO3C,OAAO,CAAC4C,GAAG,CAChC,IAAI,CAACR,MAAM,CAACf,GAAG,CAACwB,CAAC,IAAIV,aAAa,CAACK,MAAM,CAACK,CAAC,CAAC,CAC9C,CAAC;IACD,OAAOF,OAAO,CAACG,IAAI,CAAC,MAAM,CAAC;EAC7B;AACF","ignoreList":[]} |
| export function mergeOptions(target, source) { | ||
| for (const k of Object.keys(source)) { | ||
| if ((k === "parserOpts" || k === "generatorOpts" || k === "assumptions") && source[k]) { | ||
| const parserOpts = source[k]; | ||
| const targetObj = target[k] || (target[k] = {}); | ||
| mergeDefaultFields(targetObj, parserOpts); | ||
| } else { | ||
| const val = source[k]; | ||
| if (val !== undefined) target[k] = val; | ||
| } | ||
| } | ||
| } | ||
| function mergeDefaultFields(target, source) { | ||
| for (const k of Object.keys(source)) { | ||
| const val = source[k]; | ||
| if (val !== undefined) target[k] = val; | ||
| } | ||
| } | ||
| export function isIterableIterator(value) { | ||
| return !!value && typeof value.next === "function" && typeof value[Symbol.iterator] === "function"; | ||
| } | ||
| //# sourceMappingURL=util.js.map |
| {"version":3,"names":["mergeOptions","target","source","k","Object","keys","parserOpts","targetObj","mergeDefaultFields","val","undefined","isIterableIterator","value","next","Symbol","iterator"],"sources":["../../src/config/util.ts"],"sourcesContent":["import type { InputOptions, ResolvedOptions } from \"./validation/options.ts\";\n\nexport function mergeOptions(\n target: InputOptions | ResolvedOptions,\n source: InputOptions,\n): void {\n for (const k of Object.keys(source)) {\n if (\n (k === \"parserOpts\" || k === \"generatorOpts\" || k === \"assumptions\") &&\n source[k]\n ) {\n const parserOpts = source[k];\n const targetObj = target[k] || (target[k] = {});\n mergeDefaultFields(targetObj, parserOpts);\n } else {\n //@ts-expect-error k must index source\n const val = source[k];\n //@ts-expect-error assigning source to target\n if (val !== undefined) target[k] = val as any;\n }\n }\n}\n\nfunction mergeDefaultFields<T extends object>(target: T, source: T) {\n for (const k of Object.keys(source) as (keyof T)[]) {\n const val = source[k];\n if (val !== undefined) target[k] = val;\n }\n}\n\nexport function isIterableIterator(value: any): value is IterableIterator<any> {\n return (\n !!value &&\n typeof value.next === \"function\" &&\n typeof value[Symbol.iterator] === \"function\"\n );\n}\n"],"mappings":"AAEA,OAAO,SAASA,YAAYA,CAC1BC,MAAsC,EACtCC,MAAoB,EACd;EACN,KAAK,MAAMC,CAAC,IAAIC,MAAM,CAACC,IAAI,CAACH,MAAM,CAAC,EAAE;IACnC,IACE,CAACC,CAAC,KAAK,YAAY,IAAIA,CAAC,KAAK,eAAe,IAAIA,CAAC,KAAK,aAAa,KACnED,MAAM,CAACC,CAAC,CAAC,EACT;MACA,MAAMG,UAAU,GAAGJ,MAAM,CAACC,CAAC,CAAC;MAC5B,MAAMI,SAAS,GAAGN,MAAM,CAACE,CAAC,CAAC,KAAKF,MAAM,CAACE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;MAC/CK,kBAAkB,CAACD,SAAS,EAAED,UAAU,CAAC;IAC3C,CAAC,MAAM;MAEL,MAAMG,GAAG,GAAGP,MAAM,CAACC,CAAC,CAAC;MAErB,IAAIM,GAAG,KAAKC,SAAS,EAAET,MAAM,CAACE,CAAC,CAAC,GAAGM,GAAU;IAC/C;EACF;AACF;AAEA,SAASD,kBAAkBA,CAAmBP,MAAS,EAAEC,MAAS,EAAE;EAClE,KAAK,MAAMC,CAAC,IAAIC,MAAM,CAACC,IAAI,CAACH,MAAM,CAAC,EAAiB;IAClD,MAAMO,GAAG,GAAGP,MAAM,CAACC,CAAC,CAAC;IACrB,IAAIM,GAAG,KAAKC,SAAS,EAAET,MAAM,CAACE,CAAC,CAAC,GAAGM,GAAG;EACxC;AACF;AAEA,OAAO,SAASE,kBAAkBA,CAACC,KAAU,EAAkC;EAC7E,OACE,CAAC,CAACA,KAAK,IACP,OAAOA,KAAK,CAACC,IAAI,KAAK,UAAU,IAChC,OAAOD,KAAK,CAACE,MAAM,CAACC,QAAQ,CAAC,KAAK,UAAU;AAEhD","ignoreList":[]} |
| import { isBrowsersQueryValid, TargetNames } from "@babel/helper-compilation-targets"; | ||
| import { assumptionsNames } from "./options.js"; | ||
| export function msg(loc) { | ||
| switch (loc.type) { | ||
| case "root": | ||
| return ``; | ||
| case "env": | ||
| return `${msg(loc.parent)}.env["${loc.name}"]`; | ||
| case "overrides": | ||
| return `${msg(loc.parent)}.overrides[${loc.index}]`; | ||
| case "option": | ||
| return `${msg(loc.parent)}.${loc.name}`; | ||
| case "access": | ||
| return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`; | ||
| default: | ||
| throw new Error(`Assertion failure: Unknown type ${loc.type}`); | ||
| } | ||
| } | ||
| export function access(loc, name) { | ||
| return { | ||
| type: "access", | ||
| name, | ||
| parent: loc | ||
| }; | ||
| } | ||
| export function assertRootMode(loc, value) { | ||
| if (value !== undefined && value !== "root" && value !== "upward" && value !== "upward-optional") { | ||
| throw new Error(`${msg(loc)} must be a "root", "upward", "upward-optional" or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertSourceMaps(loc, value) { | ||
| if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") { | ||
| throw new Error(`${msg(loc)} must be a boolean, "inline", "both", or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertCompact(loc, value) { | ||
| if (value !== undefined && typeof value !== "boolean" && value !== "auto") { | ||
| throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertSourceType(loc, value) { | ||
| if (value !== undefined && value !== "module" && value !== "commonjs" && value !== "script" && value !== "unambiguous") { | ||
| throw new Error(`${msg(loc)} must be "module", "commonjs", "script", "unambiguous", or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertCallerMetadata(loc, value) { | ||
| const obj = assertObject(loc, value); | ||
| if (obj) { | ||
| if (typeof obj.name !== "string") { | ||
| throw new Error(`${msg(loc)} set but does not contain "name" property string`); | ||
| } | ||
| for (const prop of Object.keys(obj)) { | ||
| const propLoc = access(loc, prop); | ||
| const value = obj[prop]; | ||
| if (value != null && typeof value !== "boolean" && typeof value !== "string" && typeof value !== "number") { | ||
| throw new Error(`${msg(propLoc)} must be null, undefined, a boolean, a string, or a number.`); | ||
| } | ||
| } | ||
| } | ||
| return value; | ||
| } | ||
| export function assertInputSourceMap(loc, value) { | ||
| if (value !== undefined && typeof value !== "boolean" && (typeof value !== "object" || !value)) { | ||
| throw new Error(`${msg(loc)} must be a boolean, object, or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertString(loc, value) { | ||
| if (value !== undefined && typeof value !== "string") { | ||
| throw new Error(`${msg(loc)} must be a string, or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertFunction(loc, value) { | ||
| if (value !== undefined && typeof value !== "function") { | ||
| throw new Error(`${msg(loc)} must be a function, or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertBoolean(loc, value) { | ||
| if (value !== undefined && typeof value !== "boolean") { | ||
| throw new Error(`${msg(loc)} must be a boolean, or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertObject(loc, value) { | ||
| if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) { | ||
| throw new Error(`${msg(loc)} must be an object, or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertArray(loc, value) { | ||
| if (value != null && !Array.isArray(value)) { | ||
| throw new Error(`${msg(loc)} must be an array, or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertIgnoreList(loc, value) { | ||
| const arr = assertArray(loc, value); | ||
| arr?.forEach((item, i) => assertIgnoreItem(access(loc, i), item)); | ||
| return arr; | ||
| } | ||
| function assertIgnoreItem(loc, value) { | ||
| if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) { | ||
| throw new Error(`${msg(loc)} must be an array of string/Function/RegExp values, or undefined`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertConfigApplicableTest(loc, value) { | ||
| if (value === undefined) { | ||
| return value; | ||
| } | ||
| if (Array.isArray(value)) { | ||
| value.forEach((item, i) => { | ||
| if (!checkValidTest(item)) { | ||
| throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); | ||
| } | ||
| }); | ||
| } else if (!checkValidTest(value)) { | ||
| throw new Error(`${msg(loc)} must be a string/Function/RegExp, or an array of those`); | ||
| } | ||
| return value; | ||
| } | ||
| function checkValidTest(value) { | ||
| return typeof value === "string" || typeof value === "function" || value instanceof RegExp; | ||
| } | ||
| export function assertConfigFileSearch(loc, value) { | ||
| if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") { | ||
| throw new Error(`${msg(loc)} must be a undefined, a boolean, a string, ` + `got ${JSON.stringify(value)}`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertBabelrcSearch(loc, value) { | ||
| if (value === undefined || typeof value === "boolean") { | ||
| return value; | ||
| } | ||
| if (Array.isArray(value)) { | ||
| value.forEach((item, i) => { | ||
| if (!checkValidTest(item)) { | ||
| throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); | ||
| } | ||
| }); | ||
| } else if (!checkValidTest(value)) { | ||
| throw new Error(`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` + `or an array of those, got ${JSON.stringify(value)}`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertPluginList(loc, value) { | ||
| const arr = assertArray(loc, value); | ||
| if (arr) { | ||
| arr.forEach((item, i) => assertPluginItem(access(loc, i), item)); | ||
| } | ||
| return arr; | ||
| } | ||
| function assertPluginItem(loc, value) { | ||
| if (Array.isArray(value)) { | ||
| if (value.length === 0) { | ||
| throw new Error(`${msg(loc)} must include an object`); | ||
| } | ||
| if (value.length > 3) { | ||
| throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`); | ||
| } | ||
| assertPluginTarget(access(loc, 0), value[0]); | ||
| if (value.length > 1) { | ||
| const opts = value[1]; | ||
| if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts) || opts === null)) { | ||
| throw new Error(`${msg(access(loc, 1))} must be an object, false, or undefined`); | ||
| } | ||
| } | ||
| if (value.length === 3) { | ||
| const name = value[2]; | ||
| if (name !== undefined && typeof name !== "string") { | ||
| throw new Error(`${msg(access(loc, 2))} must be a string, or undefined`); | ||
| } | ||
| } | ||
| } else { | ||
| assertPluginTarget(loc, value); | ||
| } | ||
| return value; | ||
| } | ||
| function assertPluginTarget(loc, value) { | ||
| if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") { | ||
| throw new Error(`${msg(loc)} must be a string, object, function`); | ||
| } | ||
| return value; | ||
| } | ||
| export function assertTargets(loc, value) { | ||
| if (isBrowsersQueryValid(value)) return value; | ||
| if (typeof value !== "object" || !value || Array.isArray(value)) { | ||
| throw new Error(`${msg(loc)} must be a string, an array of strings or an object`); | ||
| } | ||
| const browsersLoc = access(loc, "browsers"); | ||
| const esmodulesLoc = access(loc, "esmodules"); | ||
| assertBrowsersList(browsersLoc, value.browsers); | ||
| assertBoolean(esmodulesLoc, value.esmodules); | ||
| for (const key of Object.keys(value)) { | ||
| const val = value[key]; | ||
| const subLoc = access(loc, key); | ||
| if (key === "esmodules") assertBoolean(subLoc, val);else if (key === "browsers") assertBrowsersList(subLoc, val);else if (!Object.hasOwn(TargetNames, key)) { | ||
| const validTargets = Object.keys(TargetNames).join(", "); | ||
| throw new Error(`${msg(subLoc)} is not a valid target. Supported targets are ${validTargets}`); | ||
| } else assertBrowserVersion(subLoc, val); | ||
| } | ||
| return value; | ||
| } | ||
| function assertBrowsersList(loc, value) { | ||
| if (value !== undefined && !isBrowsersQueryValid(value)) { | ||
| throw new Error(`${msg(loc)} must be undefined, a string or an array of strings`); | ||
| } | ||
| } | ||
| function assertBrowserVersion(loc, value) { | ||
| if (typeof value === "number" && Math.round(value) === value) return; | ||
| if (typeof value === "string") return; | ||
| throw new Error(`${msg(loc)} must be a string or an integer number`); | ||
| } | ||
| export function assertAssumptions(loc, value) { | ||
| if (value === undefined) return; | ||
| if (typeof value !== "object" || value === null) { | ||
| throw new Error(`${msg(loc)} must be an object or undefined.`); | ||
| } | ||
| let root = loc; | ||
| do { | ||
| root = root.parent; | ||
| } while (root.type !== "root"); | ||
| const inPreset = root.source === "preset"; | ||
| for (const name of Object.keys(value)) { | ||
| const subLoc = access(loc, name); | ||
| if (!assumptionsNames.has(name)) { | ||
| throw new Error(`${msg(subLoc)} is not a supported assumption.`); | ||
| } | ||
| if (typeof value[name] !== "boolean") { | ||
| throw new Error(`${msg(subLoc)} must be a boolean.`); | ||
| } | ||
| if (inPreset && value[name] === false) { | ||
| throw new Error(`${msg(subLoc)} cannot be set to 'false' inside presets.`); | ||
| } | ||
| } | ||
| return value; | ||
| } | ||
| //# sourceMappingURL=option-assertions.js.map |
| {"version":3,"names":["isBrowsersQueryValid","TargetNames","assumptionsNames","msg","loc","type","parent","name","index","JSON","stringify","Error","access","assertRootMode","value","undefined","assertSourceMaps","assertCompact","assertSourceType","assertCallerMetadata","obj","assertObject","prop","Object","keys","propLoc","assertInputSourceMap","assertString","assertFunction","assertBoolean","Array","isArray","assertArray","assertIgnoreList","arr","forEach","item","i","assertIgnoreItem","RegExp","assertConfigApplicableTest","checkValidTest","assertConfigFileSearch","assertBabelrcSearch","assertPluginList","assertPluginItem","length","assertPluginTarget","opts","assertTargets","browsersLoc","esmodulesLoc","assertBrowsersList","browsers","esmodules","key","val","subLoc","hasOwn","validTargets","join","assertBrowserVersion","Math","round","assertAssumptions","root","inPreset","source","has"],"sources":["../../../src/config/validation/option-assertions.ts"],"sourcesContent":["import {\n isBrowsersQueryValid,\n TargetNames,\n} from \"@babel/helper-compilation-targets\";\n\nimport type {\n ConfigFileSearch,\n BabelrcSearch,\n MatchItem,\n PluginTarget,\n ConfigApplicableTest,\n SourceMapsOption,\n SourceTypeOption,\n CompactOption,\n RootInputSourceMapOption,\n NestingPath,\n CallerMetadata,\n RootMode,\n TargetsListOrObject,\n AssumptionName,\n PluginItem,\n} from \"./options.ts\";\n\nimport { assumptionsNames } from \"./options.ts\";\n\nexport type { RootPath } from \"./options.ts\";\n\nexport type ValidatorSet = Record<string, Validator<any>>;\n\nexport type Validator<T> = (loc: OptionPath, value: unknown) => T;\n\nexport function msg(loc: NestingPath | GeneralPath): string {\n switch (loc.type) {\n case \"root\":\n return ``;\n case \"env\":\n return `${msg(loc.parent)}.env[\"${loc.name}\"]`;\n case \"overrides\":\n return `${msg(loc.parent)}.overrides[${loc.index}]`;\n case \"option\":\n return `${msg(loc.parent)}.${loc.name}`;\n case \"access\":\n return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`;\n default:\n // @ts-expect-error should not happen when code is type checked\n throw new Error(`Assertion failure: Unknown type ${loc.type}`);\n }\n}\n\nexport function access(loc: GeneralPath, name: string | number): AccessPath {\n return {\n type: \"access\",\n name,\n parent: loc,\n };\n}\n\nexport type OptionPath = Readonly<{\n type: \"option\";\n name: string;\n parent: NestingPath;\n}>;\ntype AccessPath = Readonly<{\n type: \"access\";\n name: string | number;\n parent: GeneralPath;\n}>;\ntype GeneralPath = OptionPath | AccessPath;\n\nexport function assertRootMode(\n loc: OptionPath,\n value: unknown,\n): RootMode | void {\n if (\n value !== undefined &&\n value !== \"root\" &&\n value !== \"upward\" &&\n value !== \"upward-optional\"\n ) {\n throw new Error(\n `${msg(loc)} must be a \"root\", \"upward\", \"upward-optional\" or undefined`,\n );\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertSourceMaps(\n loc: OptionPath,\n value: unknown,\n): SourceMapsOption | void {\n if (\n value !== undefined &&\n typeof value !== \"boolean\" &&\n value !== \"inline\" &&\n value !== \"both\"\n ) {\n throw new Error(\n `${msg(loc)} must be a boolean, \"inline\", \"both\", or undefined`,\n );\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertCompact(\n loc: OptionPath,\n value: unknown,\n): CompactOption | void {\n if (value !== undefined && typeof value !== \"boolean\" && value !== \"auto\") {\n throw new Error(`${msg(loc)} must be a boolean, \"auto\", or undefined`);\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertSourceType(\n loc: OptionPath,\n value: unknown,\n): SourceTypeOption | void {\n if (\n value !== undefined &&\n value !== \"module\" &&\n value !== \"commonjs\" &&\n value !== \"script\" &&\n value !== \"unambiguous\"\n ) {\n throw new Error(\n `${msg(loc)} must be \"module\", \"commonjs\", \"script\", \"unambiguous\", or undefined`,\n );\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertCallerMetadata(\n loc: OptionPath,\n value: unknown,\n): CallerMetadata | undefined {\n const obj = assertObject(loc, value);\n if (obj) {\n if (typeof obj.name !== \"string\") {\n throw new Error(\n `${msg(loc)} set but does not contain \"name\" property string`,\n );\n }\n\n for (const prop of Object.keys(obj)) {\n const propLoc = access(loc, prop);\n const value = obj[prop];\n if (\n value != null &&\n typeof value !== \"boolean\" &&\n typeof value !== \"string\" &&\n typeof value !== \"number\"\n ) {\n // NOTE(logan): I'm limiting the type here so that we can guarantee that\n // the \"caller\" value will serialize to JSON nicely. We can always\n // allow more complex structures later though.\n throw new Error(\n `${msg(\n propLoc,\n )} must be null, undefined, a boolean, a string, or a number.`,\n );\n }\n }\n }\n // @ts-expect-error todo(flow->ts)\n return value;\n}\n\nexport function assertInputSourceMap(\n loc: OptionPath,\n value: unknown,\n): RootInputSourceMapOption {\n if (\n value !== undefined &&\n typeof value !== \"boolean\" &&\n (typeof value !== \"object\" || !value)\n ) {\n throw new Error(`${msg(loc)} must be a boolean, object, or undefined`);\n }\n return value as RootInputSourceMapOption;\n}\n\nexport function assertString(loc: GeneralPath, value: unknown): string | void {\n if (value !== undefined && typeof value !== \"string\") {\n throw new Error(`${msg(loc)} must be a string, or undefined`);\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertFunction(\n loc: GeneralPath,\n value: unknown,\n): Function | void {\n if (value !== undefined && typeof value !== \"function\") {\n throw new Error(`${msg(loc)} must be a function, or undefined`);\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertBoolean(\n loc: GeneralPath,\n value: unknown,\n): boolean | void {\n if (value !== undefined && typeof value !== \"boolean\") {\n throw new Error(`${msg(loc)} must be a boolean, or undefined`);\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertObject(\n loc: GeneralPath,\n value: unknown,\n): Readonly<Record<string, unknown>> | void {\n if (\n value !== undefined &&\n (typeof value !== \"object\" || Array.isArray(value) || !value)\n ) {\n throw new Error(`${msg(loc)} must be an object, or undefined`);\n }\n // @ts-expect-error todo(flow->ts) value is still typed as unknown, also assert function typically should not return a value\n return value;\n}\n\nexport function assertArray<T>(\n loc: GeneralPath,\n value: T[] | undefined | null,\n): T[] | undefined | null {\n if (value != null && !Array.isArray(value)) {\n throw new Error(`${msg(loc)} must be an array, or undefined`);\n }\n return value;\n}\n\nexport function assertIgnoreList(\n loc: OptionPath,\n value: unknown[] | undefined,\n): MatchItem[] | void {\n const arr = assertArray(loc, value);\n arr?.forEach((item, i) => assertIgnoreItem(access(loc, i), item));\n // @ts-expect-error todo(flow->ts)\n return arr;\n}\nfunction assertIgnoreItem(loc: GeneralPath, value: unknown): MatchItem {\n if (\n typeof value !== \"string\" &&\n typeof value !== \"function\" &&\n !(value instanceof RegExp)\n ) {\n throw new Error(\n `${msg(\n loc,\n )} must be an array of string/Function/RegExp values, or undefined`,\n );\n }\n return value as MatchItem;\n}\n\nexport function assertConfigApplicableTest(\n loc: OptionPath,\n value: unknown,\n): ConfigApplicableTest | void {\n if (value === undefined) {\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n }\n\n if (Array.isArray(value)) {\n value.forEach((item, i) => {\n if (!checkValidTest(item)) {\n throw new Error(\n `${msg(access(loc, i))} must be a string/Function/RegExp.`,\n );\n }\n });\n } else if (!checkValidTest(value)) {\n throw new Error(\n `${msg(loc)} must be a string/Function/RegExp, or an array of those`,\n );\n }\n return value as ConfigApplicableTest;\n}\n\nfunction checkValidTest(value: unknown): value is string | Function | RegExp {\n return (\n typeof value === \"string\" ||\n typeof value === \"function\" ||\n value instanceof RegExp\n );\n}\n\nexport function assertConfigFileSearch(\n loc: OptionPath,\n value: unknown,\n): ConfigFileSearch | void {\n if (\n value !== undefined &&\n typeof value !== \"boolean\" &&\n typeof value !== \"string\"\n ) {\n throw new Error(\n `${msg(loc)} must be a undefined, a boolean, a string, ` +\n `got ${JSON.stringify(value)}`,\n );\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertBabelrcSearch(\n loc: OptionPath,\n value: unknown,\n): BabelrcSearch | void {\n if (value === undefined || typeof value === \"boolean\") {\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n }\n\n if (Array.isArray(value)) {\n value.forEach((item, i) => {\n if (!checkValidTest(item)) {\n throw new Error(\n `${msg(access(loc, i))} must be a string/Function/RegExp.`,\n );\n }\n });\n } else if (!checkValidTest(value)) {\n throw new Error(\n `${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` +\n `or an array of those, got ${JSON.stringify(value as any)}`,\n );\n }\n return value as BabelrcSearch;\n}\n\nexport function assertPluginList(\n loc: OptionPath,\n value: unknown[] | null | undefined,\n): PluginItem[] {\n const arr = assertArray(loc, value);\n if (arr) {\n // Loop instead of using `.map` in order to preserve object identity\n // for plugin array for use during config chain processing.\n arr.forEach((item, i) => assertPluginItem(access(loc, i), item));\n }\n return arr as PluginItem[];\n}\nfunction assertPluginItem(loc: GeneralPath, value: unknown): PluginItem {\n if (Array.isArray(value)) {\n if (value.length === 0) {\n throw new Error(`${msg(loc)} must include an object`);\n }\n\n if (value.length > 3) {\n throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`);\n }\n\n assertPluginTarget(access(loc, 0), value[0]);\n\n if (value.length > 1) {\n const opts = value[1];\n if (\n opts !== undefined &&\n opts !== false &&\n (typeof opts !== \"object\" || Array.isArray(opts) || opts === null)\n ) {\n throw new Error(\n `${msg(access(loc, 1))} must be an object, false, or undefined`,\n );\n }\n }\n if (value.length === 3) {\n const name = value[2];\n if (name !== undefined && typeof name !== \"string\") {\n throw new Error(\n `${msg(access(loc, 2))} must be a string, or undefined`,\n );\n }\n }\n } else {\n assertPluginTarget(loc, value);\n }\n\n return value as PluginItem;\n}\nfunction assertPluginTarget(loc: GeneralPath, value: unknown): PluginTarget {\n if (\n (typeof value !== \"object\" || !value) &&\n typeof value !== \"string\" &&\n typeof value !== \"function\"\n ) {\n throw new Error(`${msg(loc)} must be a string, object, function`);\n }\n return value as PluginTarget;\n}\n\nexport function assertTargets(\n loc: GeneralPath,\n value: any,\n): TargetsListOrObject {\n if (isBrowsersQueryValid(value)) return value;\n\n if (typeof value !== \"object\" || !value || Array.isArray(value)) {\n throw new Error(\n `${msg(loc)} must be a string, an array of strings or an object`,\n );\n }\n\n const browsersLoc = access(loc, \"browsers\");\n const esmodulesLoc = access(loc, \"esmodules\");\n\n assertBrowsersList(browsersLoc, value.browsers);\n assertBoolean(esmodulesLoc, value.esmodules);\n\n for (const key of Object.keys(value)) {\n const val = value[key];\n const subLoc = access(loc, key);\n\n if (key === \"esmodules\") assertBoolean(subLoc, val);\n else if (key === \"browsers\") assertBrowsersList(subLoc, val);\n else if (!Object.hasOwn(TargetNames, key)) {\n const validTargets = Object.keys(TargetNames).join(\", \");\n throw new Error(\n `${msg(\n subLoc,\n )} is not a valid target. Supported targets are ${validTargets}`,\n );\n } else assertBrowserVersion(subLoc, val);\n }\n\n return value;\n}\n\nfunction assertBrowsersList(loc: GeneralPath, value: unknown) {\n if (value !== undefined && !isBrowsersQueryValid(value)) {\n throw new Error(\n `${msg(loc)} must be undefined, a string or an array of strings`,\n );\n }\n}\n\nfunction assertBrowserVersion(loc: GeneralPath, value: unknown) {\n if (typeof value === \"number\" && Math.round(value) === value) return;\n if (typeof value === \"string\") return;\n\n throw new Error(`${msg(loc)} must be a string or an integer number`);\n}\n\nexport function assertAssumptions(\n loc: GeneralPath,\n value: Record<string, unknown>,\n): Record<string, boolean> | void {\n if (value === undefined) return;\n\n if (typeof value !== \"object\" || value === null) {\n throw new Error(`${msg(loc)} must be an object or undefined.`);\n }\n\n // todo(flow->ts): remove any\n let root: any = loc;\n do {\n root = root.parent;\n } while (root.type !== \"root\");\n const inPreset = root.source === \"preset\";\n\n for (const name of Object.keys(value)) {\n const subLoc = access(loc, name);\n if (!assumptionsNames.has(name as AssumptionName)) {\n throw new Error(`${msg(subLoc)} is not a supported assumption.`);\n }\n if (typeof value[name] !== \"boolean\") {\n throw new Error(`${msg(subLoc)} must be a boolean.`);\n }\n if (inPreset && value[name] === false) {\n throw new Error(\n `${msg(subLoc)} cannot be set to 'false' inside presets.`,\n );\n }\n }\n\n // @ts-expect-error todo(flow->ts)\n return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KAAK,SAAS,EAAE;MACpC,MAAM,IAAII,KAAK,CAAC,GAAGR,GAAG,CAACsD,MAAM,CAAC,qBAAqB,CAAC;IACtD;IACA,IAAIS,QAAQ,IAAIpD,KAAK,CAACP,IAAI,CAAC,KAAK,KAAK,EAAE;MACrC,MAAM,IAAII,KAAK,CACb,GAAGR,GAAG,CAACsD,MAAM,CAAC,2CAChB,CAAC;IACH;EACF;EAGA,OAAO3C,KAAK;AACd","ignoreList":[]} |
| import removed from "./removed.js"; | ||
| import { msg, access, assertString, assertBoolean, assertObject, assertArray, assertCallerMetadata, assertInputSourceMap, assertIgnoreList, assertPluginList, assertConfigApplicableTest, assertConfigFileSearch, assertBabelrcSearch, assertFunction, assertRootMode, assertSourceMaps, assertCompact, assertSourceType, assertTargets, assertAssumptions } from "./option-assertions.js"; | ||
| import ConfigError from "../../errors/config-error.js"; | ||
| const ROOT_VALIDATORS = { | ||
| cwd: assertString, | ||
| root: assertString, | ||
| rootMode: assertRootMode, | ||
| configFile: assertConfigFileSearch, | ||
| caller: assertCallerMetadata, | ||
| filename: assertString, | ||
| filenameRelative: assertString, | ||
| code: assertBoolean, | ||
| ast: assertBoolean, | ||
| cloneInputAst: assertBoolean, | ||
| envName: assertString | ||
| }; | ||
| const BABELRC_VALIDATORS = { | ||
| babelrc: assertBoolean, | ||
| babelrcRoots: assertBabelrcSearch | ||
| }; | ||
| const NONPRESET_VALIDATORS = { | ||
| extends: assertString, | ||
| ignore: assertIgnoreList, | ||
| only: assertIgnoreList, | ||
| targets: assertTargets, | ||
| browserslistConfigFile: assertConfigFileSearch, | ||
| browserslistEnv: assertString | ||
| }; | ||
| const COMMON_VALIDATORS = { | ||
| inputSourceMap: assertInputSourceMap, | ||
| presets: assertPluginList, | ||
| plugins: assertPluginList, | ||
| passPerPreset: assertBoolean, | ||
| assumptions: assertAssumptions, | ||
| env: assertEnvSet, | ||
| overrides: assertOverridesList, | ||
| test: assertConfigApplicableTest, | ||
| include: assertConfigApplicableTest, | ||
| exclude: assertConfigApplicableTest, | ||
| retainLines: assertBoolean, | ||
| comments: assertBoolean, | ||
| shouldPrintComment: assertFunction, | ||
| compact: assertCompact, | ||
| minified: assertBoolean, | ||
| auxiliaryCommentBefore: assertString, | ||
| auxiliaryCommentAfter: assertString, | ||
| sourceType: assertSourceType, | ||
| wrapPluginVisitorMethod: assertFunction, | ||
| highlightCode: assertBoolean, | ||
| sourceMaps: assertSourceMaps, | ||
| sourceMap: assertSourceMaps, | ||
| sourceFileName: assertString, | ||
| sourceRoot: assertString, | ||
| parserOpts: assertObject, | ||
| generatorOpts: assertObject | ||
| }; | ||
| const knownAssumptions = ["arrayLikeIsIterable", "constantReexports", "constantSuper", "enumerableModuleMeta", "ignoreFunctionLength", "ignoreToPrimitiveHint", "iterableIsArray", "mutableTemplateObject", "noClassCalls", "noDocumentAll", "noIncompleteNsImportDetection", "noNewArrows", "noUninitializedPrivateFieldAccess", "objectRestNoSymbols", "privateFieldsAsSymbols", "privateFieldsAsProperties", "pureGetters", "setClassMethods", "setComputedProperties", "setPublicClassFields", "setSpreadProperties", "skipForOfIteratorClosing", "superIsCallableConstructor"]; | ||
| export const assumptionsNames = new Set(knownAssumptions); | ||
| function getSource(loc) { | ||
| return loc.type === "root" ? loc.source : getSource(loc.parent); | ||
| } | ||
| export function validate(type, opts, filename) { | ||
| try { | ||
| return validateNested({ | ||
| type: "root", | ||
| source: type | ||
| }, opts); | ||
| } catch (error) { | ||
| const configError = new ConfigError(error.message, filename); | ||
| if (error.code) configError.code = error.code; | ||
| throw configError; | ||
| } | ||
| } | ||
| function validateNested(loc, opts) { | ||
| const type = getSource(loc); | ||
| assertNoDuplicateSourcemap(opts); | ||
| Object.keys(opts).forEach(key => { | ||
| const optLoc = { | ||
| type: "option", | ||
| name: key, | ||
| parent: loc | ||
| }; | ||
| if (type === "preset" && NONPRESET_VALIDATORS[key]) { | ||
| throw new Error(`${msg(optLoc)} is not allowed in preset options`); | ||
| } | ||
| if (type !== "arguments" && ROOT_VALIDATORS[key]) { | ||
| throw new Error(`${msg(optLoc)} is only allowed in root programmatic options`); | ||
| } | ||
| if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) { | ||
| if (type === "babelrcfile" || type === "extendsfile") { | ||
| throw new Error(`${msg(optLoc)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`); | ||
| } | ||
| throw new Error(`${msg(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`); | ||
| } | ||
| const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError; | ||
| validator(optLoc, opts[key]); | ||
| }); | ||
| return opts; | ||
| } | ||
| function throwUnknownError(loc) { | ||
| const key = loc.name; | ||
| if (removed[key]) { | ||
| const { | ||
| message, | ||
| version = 5 | ||
| } = removed[key]; | ||
| throw new Error(`Using removed Babel ${version} option: ${msg(loc)} - ${message}`); | ||
| } else { | ||
| const unknownOptErr = new Error(`Unknown option: ${msg(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`); | ||
| unknownOptErr.code = "BABEL_UNKNOWN_OPTION"; | ||
| throw unknownOptErr; | ||
| } | ||
| } | ||
| function assertNoDuplicateSourcemap(opts) { | ||
| if (Object.hasOwn(opts, "sourceMap") && Object.hasOwn(opts, "sourceMaps")) { | ||
| throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both"); | ||
| } | ||
| } | ||
| function assertEnvSet(loc, value) { | ||
| if (loc.parent.type === "env") { | ||
| throw new Error(`${msg(loc)} is not allowed inside of another .env block`); | ||
| } | ||
| const parent = loc.parent; | ||
| const obj = assertObject(loc, value); | ||
| if (obj) { | ||
| for (const envName of Object.keys(obj)) { | ||
| const env = assertObject(access(loc, envName), obj[envName]); | ||
| if (!env) continue; | ||
| const envLoc = { | ||
| type: "env", | ||
| name: envName, | ||
| parent | ||
| }; | ||
| validateNested(envLoc, env); | ||
| } | ||
| } | ||
| return obj; | ||
| } | ||
| function assertOverridesList(loc, value) { | ||
| if (loc.parent.type === "env") { | ||
| throw new Error(`${msg(loc)} is not allowed inside an .env block`); | ||
| } | ||
| if (loc.parent.type === "overrides") { | ||
| throw new Error(`${msg(loc)} is not allowed inside an .overrides block`); | ||
| } | ||
| const parent = loc.parent; | ||
| const arr = assertArray(loc, value); | ||
| if (arr) { | ||
| for (const [index, item] of arr.entries()) { | ||
| const objLoc = access(loc, index); | ||
| const env = assertObject(objLoc, item); | ||
| if (!env) throw new Error(`${msg(objLoc)} must be an object`); | ||
| const overridesLoc = { | ||
| type: "overrides", | ||
| index, | ||
| parent | ||
| }; | ||
| validateNested(overridesLoc, env); | ||
| } | ||
| } | ||
| return arr; | ||
| } | ||
| export function checkNoUnwrappedItemOptionPairs(items, index, type, e) { | ||
| if (index === 0) return; | ||
| const lastItem = items[index - 1]; | ||
| const thisItem = items[index]; | ||
| if (lastItem.file && lastItem.options === undefined && typeof thisItem.value === "object") { | ||
| e.message += `\n- Maybe you meant to use\n` + `"${type}s": [\n ["${lastItem.file.request}", ${JSON.stringify(thisItem.value, undefined, 2)}]\n]\n` + `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`; | ||
| } | ||
| } | ||
| //# sourceMappingURL=options.js.map |
| {"version":3,"names":["removed","msg","access","assertString","assertBoolean","assertObject","assertArray","assertCallerMetadata","assertInputSourceMap","assertIgnoreList","assertPluginList","assertConfigApplicableTest","assertConfigFileSearch","assertBabelrcSearch","assertFunction","assertRootMode","assertSourceMaps","assertCompact","assertSourceType","assertTargets","assertAssumptions","ConfigError","ROOT_VALIDATORS","cwd","root","rootMode","configFile","caller","filename","filenameRelative","code","ast","cloneInputAst","envName","BABELRC_VALIDATORS","babelrc","babelrcRoots","NONPRESET_VALIDATORS","extends","ignore","only","targets","browserslistConfigFile","browserslistEnv","COMMON_VALIDATORS","inputSourceMap","presets","plugins","passPerPreset","assumptions","env","assertEnvSet","overrides","assertOverridesList","test","include","exclude","retainLines","comments","shouldPrintComment","compact","minified","auxiliaryCommentBefore","auxiliaryCommentAfter","sourceType","wrapPluginVisitorMethod","highlightCode","sourceMaps","sourceMap","sourceFileName","sourceRoot","parserOpts","generatorOpts","knownAssumptions","assumptionsNames","Set","getSource","loc","type","source","parent","validate","opts","validateNested","error","configError","message","assertNoDuplicateSourcemap","Object","keys","forEach","key","optLoc","name","Error","validator","throwUnknownError","version","unknownOptErr","hasOwn","value","obj","envLoc","arr","index","item","entries","objLoc","overridesLoc","checkNoUnwrappedItemOptionPairs","items","e","lastItem","thisItem","file","options","undefined","request","JSON","stringify"],"sources":["../../../src/config/validation/options.ts"],"sourcesContent":["import type { InputTargets, Targets } from \"@babel/helper-compilation-targets\";\n\nimport type { ConfigItem } from \"../item.ts\";\n\nimport removed from \"./removed.ts\";\nimport {\n msg,\n access,\n assertString,\n assertBoolean,\n assertObject,\n assertArray,\n assertCallerMetadata,\n assertInputSourceMap,\n assertIgnoreList,\n assertPluginList,\n assertConfigApplicableTest,\n assertConfigFileSearch,\n assertBabelrcSearch,\n assertFunction,\n assertRootMode,\n assertSourceMaps,\n assertCompact,\n assertSourceType,\n assertTargets,\n assertAssumptions,\n} from \"./option-assertions.ts\";\nimport type {\n ValidatorSet,\n Validator,\n OptionPath,\n} from \"./option-assertions.ts\";\nimport type { UnloadedDescriptor } from \"../config-descriptors.ts\";\nimport type { PluginAPI } from \"../helpers/config-api.ts\";\nimport type { ParserOptions } from \"@babel/parser\";\nimport type { GeneratorOptions } from \"@babel/generator\";\nimport type { VisitWrapper } from \"@babel/traverse\";\nimport ConfigError from \"../../errors/config-error.ts\";\nimport type { PluginObject } from \"./plugins.ts\";\nimport type Plugin from \"../plugin.ts\";\nimport type { PresetAPI } from \"../index.ts\";\nimport type { PresetObject } from \"../../index.ts\";\n\nconst ROOT_VALIDATORS: ValidatorSet = {\n cwd: assertString as Validator<InputOptions[\"cwd\"]>,\n root: assertString as Validator<InputOptions[\"root\"]>,\n rootMode: assertRootMode as Validator<InputOptions[\"rootMode\"]>,\n configFile: assertConfigFileSearch as Validator<InputOptions[\"configFile\"]>,\n\n caller: assertCallerMetadata as Validator<InputOptions[\"caller\"]>,\n filename: assertString as Validator<InputOptions[\"filename\"]>,\n filenameRelative: assertString as Validator<InputOptions[\"filenameRelative\"]>,\n code: assertBoolean as Validator<InputOptions[\"code\"]>,\n ast: assertBoolean as Validator<InputOptions[\"ast\"]>,\n\n cloneInputAst: assertBoolean as Validator<InputOptions[\"cloneInputAst\"]>,\n\n envName: assertString as Validator<InputOptions[\"envName\"]>,\n};\n\nconst BABELRC_VALIDATORS: ValidatorSet = {\n babelrc: assertBoolean as Validator<InputOptions[\"babelrc\"]>,\n babelrcRoots: assertBabelrcSearch as Validator<InputOptions[\"babelrcRoots\"]>,\n};\n\nconst NONPRESET_VALIDATORS: ValidatorSet = {\n extends: assertString as Validator<InputOptions[\"extends\"]>,\n ignore: assertIgnoreList as Validator<InputOptions[\"ignore\"]>,\n only: assertIgnoreList as Validator<InputOptions[\"only\"]>,\n\n targets: assertTargets as Validator<InputOptions[\"targets\"]>,\n browserslistConfigFile: assertConfigFileSearch as Validator<\n InputOptions[\"browserslistConfigFile\"]\n >,\n browserslistEnv: assertString as Validator<InputOptions[\"browserslistEnv\"]>,\n};\n\nconst COMMON_VALIDATORS: ValidatorSet = {\n // TODO: Should 'inputSourceMap' be moved to be a root-only option?\n // We may want a boolean-only version to be a common option, with the\n // object only allowed as a root config argument.\n inputSourceMap: assertInputSourceMap as Validator<\n InputOptions[\"inputSourceMap\"]\n >,\n presets: assertPluginList as Validator<InputOptions[\"presets\"]>,\n plugins: assertPluginList as Validator<InputOptions[\"plugins\"]>,\n passPerPreset: assertBoolean as Validator<InputOptions[\"passPerPreset\"]>,\n assumptions: assertAssumptions as Validator<InputOptions[\"assumptions\"]>,\n\n env: assertEnvSet as Validator<InputOptions[\"env\"]>,\n overrides: assertOverridesList as Validator<InputOptions[\"overrides\"]>,\n\n // We could limit these to 'overrides' blocks, but it's not clear why we'd\n // bother, when the ability to limit a config to a specific set of files\n // is a fairly general useful feature.\n test: assertConfigApplicableTest as Validator<InputOptions[\"test\"]>,\n include: assertConfigApplicableTest as Validator<InputOptions[\"include\"]>,\n exclude: assertConfigApplicableTest as Validator<InputOptions[\"exclude\"]>,\n\n retainLines: assertBoolean as Validator<InputOptions[\"retainLines\"]>,\n comments: assertBoolean as Validator<InputOptions[\"comments\"]>,\n shouldPrintComment: assertFunction as Validator<\n InputOptions[\"shouldPrintComment\"]\n >,\n compact: assertCompact as Validator<InputOptions[\"compact\"]>,\n minified: assertBoolean as Validator<InputOptions[\"minified\"]>,\n auxiliaryCommentBefore: assertString as Validator<\n InputOptions[\"auxiliaryCommentBefore\"]\n >,\n auxiliaryCommentAfter: assertString as Validator<\n InputOptions[\"auxiliaryCommentAfter\"]\n >,\n sourceType: assertSourceType as Validator<InputOptions[\"sourceType\"]>,\n wrapPluginVisitorMethod: assertFunction as Validator<\n InputOptions[\"wrapPluginVisitorMethod\"]\n >,\n highlightCode: assertBoolean as Validator<InputOptions[\"highlightCode\"]>,\n sourceMaps: assertSourceMaps as Validator<InputOptions[\"sourceMaps\"]>,\n sourceMap: assertSourceMaps as Validator<InputOptions[\"sourceMap\"]>,\n sourceFileName: assertString as Validator<InputOptions[\"sourceFileName\"]>,\n sourceRoot: assertString as Validator<InputOptions[\"sourceRoot\"]>,\n parserOpts: assertObject as Validator<InputOptions[\"parserOpts\"]>,\n generatorOpts: assertObject as Validator<InputOptions[\"generatorOpts\"]>,\n};\n\ntype Assumptions = {\n arrayLikeIsIterable?: boolean;\n constantReexports?: boolean;\n constantSuper?: boolean;\n enumerableModuleMeta?: boolean;\n ignoreFunctionLength?: boolean;\n ignoreToPrimitiveHint?: boolean;\n iterableIsArray?: boolean;\n mutableTemplateObject?: boolean;\n noClassCalls?: boolean;\n noDocumentAll?: boolean;\n noIncompleteNsImportDetection?: boolean;\n noNewArrows?: boolean;\n noUninitializedPrivateFieldAccess?: boolean;\n objectRestNoSymbols?: boolean;\n privateFieldsAsProperties?: boolean;\n privateFieldsAsSymbols?: boolean;\n pureGetters?: boolean;\n setClassMethods?: boolean;\n setComputedProperties?: boolean;\n setPublicClassFields?: boolean;\n setSpreadProperties?: boolean;\n skipForOfIteratorClosing?: boolean;\n superIsCallableConstructor?: boolean;\n};\n\nexport type AssumptionName = keyof Assumptions;\n\nexport type InputOptions = {\n cwd?: string;\n filename?: string;\n filenameRelative?: string;\n babelrc?: boolean;\n babelrcRoots?: BabelrcSearch;\n configFile?: ConfigFileSearch;\n root?: string;\n rootMode?: RootMode;\n code?: boolean;\n ast?: boolean;\n cloneInputAst?: boolean;\n inputSourceMap?: RootInputSourceMapOption;\n envName?: string;\n caller?: CallerMetadata;\n extends?: string;\n env?: EnvSet<InputOptions>;\n ignore?: MatchItem[];\n only?: MatchItem[];\n overrides?: InputOptions[];\n showIgnoredFiles?: boolean;\n // Generally verify if a given config object should be applied to the given file.\n test?: ConfigApplicableTest;\n include?: ConfigApplicableTest;\n exclude?: ConfigApplicableTest;\n presets?: PresetItem[];\n plugins?: PluginItem[];\n passPerPreset?: boolean;\n assumptions?: Assumptions;\n // browserslists-related options\n targets?: TargetsListOrObject;\n browserslistConfigFile?: ConfigFileSearch;\n browserslistEnv?: string;\n // Options for @babel/generator\n retainLines?: GeneratorOptions[\"retainLines\"];\n comments?: GeneratorOptions[\"comments\"];\n shouldPrintComment?: GeneratorOptions[\"shouldPrintComment\"];\n compact?: GeneratorOptions[\"compact\"];\n minified?: GeneratorOptions[\"minified\"];\n auxiliaryCommentBefore?: GeneratorOptions[\"auxiliaryCommentBefore\"];\n auxiliaryCommentAfter?: GeneratorOptions[\"auxiliaryCommentAfter\"];\n // Parser\n sourceType?: SourceTypeOption;\n wrapPluginVisitorMethod?: VisitWrapper | null;\n highlightCode?: boolean;\n // Sourcemap generation options.\n sourceMaps?: SourceMapsOption;\n sourceMap?: SourceMapsOption;\n sourceFileName?: string;\n sourceRoot?: string;\n // Todo(Babel 9): Deprecate top level parserOpts\n parserOpts?: ParserOptions;\n // Todo(Babel 9): Deprecate top level generatorOpts\n generatorOpts?: GeneratorOptions;\n};\n\nexport type NormalizedOptions = Omit<InputOptions, \"presets\" | \"plugins\"> & {\n assumptions: Assumptions;\n targets: Targets;\n cloneInputAst: boolean;\n babelrc: false;\n configFile: false;\n browserslistConfigFile: false;\n passPerPreset: false;\n envName: string;\n cwd: string;\n root: string;\n rootMode: \"root\";\n filename: string | undefined;\n presets: ConfigItem<PresetAPI>[];\n plugins: ConfigItem<PluginAPI>[];\n};\n\nexport type ResolvedOptions = Omit<\n NormalizedOptions,\n \"presets\" | \"plugins\" | \"passPerPreset\"\n> & {\n presets: { plugins: Plugin[] }[];\n plugins: Plugin[];\n passPerPreset: boolean;\n};\n\nexport type ConfigChainOptions = Omit<\n InputOptions,\n | \"extends\"\n | \"env\"\n | \"overrides\"\n | \"plugins\"\n | \"presets\"\n | \"passPerPreset\"\n | \"ignore\"\n | \"only\"\n | \"test\"\n | \"include\"\n | \"exclude\"\n | \"sourceMap\"\n>;\n\nexport type CallerMetadata = {\n // If 'caller' is specified, require that the name is given for debugging\n // messages.\n name: string;\n supportsStaticESM?: boolean;\n supportsDynamicImport?: boolean;\n supportsTopLevelAwait?: boolean;\n supportsExportNamespaceFrom?: boolean;\n};\nexport type EnvSet<T> = Record<string, T>;\nexport type MatchItem =\n | string\n | RegExp\n | ((\n path: string | undefined,\n context: { dirname: string; caller: CallerMetadata; envName: string },\n ) => unknown);\n\nexport type MaybeDefaultProperty<T> = T | { default: T };\n\nexport type PluginTarget =\n | string\n | MaybeDefaultProperty<\n (api: PluginAPI, options?: object, dirname?: string) => PluginObject\n >;\nexport type PluginItem =\n | ConfigItem<PluginAPI>\n | PluginTarget\n | [PluginTarget, object]\n | [PluginTarget, object, string];\n\nexport type PresetTarget =\n | string\n | MaybeDefaultProperty<\n (api: PresetAPI, options?: object, dirname?: string) => PresetObject\n >;\nexport type PresetItem =\n | ConfigItem<PresetAPI>\n | PresetTarget\n | [PresetTarget, object]\n | [PresetTarget, object, string];\n\nexport type ConfigApplicableTest = MatchItem | MatchItem[];\n\nexport type ConfigFileSearch = string | boolean;\nexport type BabelrcSearch = boolean | MatchItem | MatchItem[];\nexport type SourceMapsOption = boolean | \"inline\" | \"both\";\nexport type SourceTypeOption = \"module\" | \"commonjs\" | \"script\" | \"unambiguous\";\nexport type CompactOption = boolean | \"auto\";\n// https://github.com/mozilla/source-map/blob/801be934007c3ed0ef66c620641b1668e92c891d/source-map.d.ts#L15C8-L23C2\ninterface InputSourceMap {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n}\nexport type RootInputSourceMapOption = InputSourceMap | boolean;\nexport type RootMode = \"root\" | \"upward\" | \"upward-optional\";\n\nexport type TargetsListOrObject =\n | Targets\n | InputTargets\n | InputTargets[\"browsers\"];\n\nexport type OptionsSource =\n | \"arguments\"\n | \"configfile\"\n | \"babelrcfile\"\n | \"extendsfile\"\n | \"preset\"\n | \"plugin\";\n\nexport type RootPath = Readonly<{\n type: \"root\";\n source: OptionsSource;\n}>;\n\ntype OverridesPath = Readonly<{\n type: \"overrides\";\n index: number;\n parent: RootPath;\n}>;\n\ntype EnvPath = Readonly<{\n type: \"env\";\n name: string;\n parent: RootPath | OverridesPath;\n}>;\n\nexport type NestingPath = RootPath | OverridesPath | EnvPath;\n\nconst knownAssumptions = [\n \"arrayLikeIsIterable\",\n \"constantReexports\",\n \"constantSuper\",\n \"enumerableModuleMeta\",\n \"ignoreFunctionLength\",\n \"ignoreToPrimitiveHint\",\n \"iterableIsArray\",\n \"mutableTemplateObject\",\n \"noClassCalls\",\n \"noDocumentAll\",\n \"noIncompleteNsImportDetection\",\n \"noNewArrows\",\n \"noUninitializedPrivateFieldAccess\",\n \"objectRestNoSymbols\",\n \"privateFieldsAsSymbols\",\n \"privateFieldsAsProperties\",\n \"pureGetters\",\n \"setClassMethods\",\n \"setComputedProperties\",\n \"setPublicClassFields\",\n \"setSpreadProperties\",\n \"skipForOfIteratorClosing\",\n \"superIsCallableConstructor\",\n] as const;\nexport const assumptionsNames = new Set(knownAssumptions);\n\nfunction getSource(loc: NestingPath): OptionsSource {\n return loc.type === \"root\" ? loc.source : getSource(loc.parent);\n}\n\nexport function validate(\n type: OptionsSource,\n opts: any,\n filename?: string,\n): InputOptions {\n try {\n return validateNested(\n {\n type: \"root\",\n source: type,\n },\n opts,\n );\n } catch (error) {\n const configError = new ConfigError(error.message, filename);\n // @ts-expect-error TODO: .code is not defined on ConfigError or Error\n if (error.code) configError.code = error.code;\n throw configError;\n }\n}\n\nfunction validateNested(loc: NestingPath, opts: Record<string, unknown>) {\n const type = getSource(loc);\n assertNoDuplicateSourcemap(opts);\n\n Object.keys(opts).forEach((key: string) => {\n const optLoc = {\n type: \"option\",\n name: key,\n parent: loc,\n } as const;\n\n if (type === \"preset\" && NONPRESET_VALIDATORS[key]) {\n throw new Error(`${msg(optLoc)} is not allowed in preset options`);\n }\n if (type !== \"arguments\" && ROOT_VALIDATORS[key]) {\n throw new Error(\n `${msg(optLoc)} is only allowed in root programmatic options`,\n );\n }\n if (\n type !== \"arguments\" &&\n type !== \"configfile\" &&\n BABELRC_VALIDATORS[key]\n ) {\n if (type === \"babelrcfile\" || type === \"extendsfile\") {\n throw new Error(\n `${msg(\n optLoc,\n )} is not allowed in .babelrc or \"extends\"ed files, only in root programmatic options, ` +\n `or babel.config.js/config file options`,\n );\n }\n\n throw new Error(\n `${msg(\n optLoc,\n )} is only allowed in root programmatic options, or babel.config.js/config file options`,\n );\n }\n\n const validator =\n COMMON_VALIDATORS[key] ||\n NONPRESET_VALIDATORS[key] ||\n BABELRC_VALIDATORS[key] ||\n ROOT_VALIDATORS[key] ||\n (throwUnknownError as Validator<void>);\n\n validator(optLoc, opts[key]);\n });\n\n return opts;\n}\n\nfunction throwUnknownError(loc: OptionPath) {\n const key = loc.name;\n\n if (removed[key]) {\n const { message, version = 5 } = removed[key];\n\n throw new Error(\n `Using removed Babel ${version} option: ${msg(loc)} - ${message}`,\n );\n } else {\n const unknownOptErr = new Error(\n `Unknown option: ${msg(\n loc,\n )}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`,\n );\n // @ts-expect-error todo(flow->ts): consider creating something like BabelConfigError with code field in it\n unknownOptErr.code = \"BABEL_UNKNOWN_OPTION\";\n\n throw unknownOptErr;\n }\n}\n\nfunction assertNoDuplicateSourcemap(opts: any): void {\n if (Object.hasOwn(opts, \"sourceMap\") && Object.hasOwn(opts, \"sourceMaps\")) {\n throw new Error(\".sourceMap is an alias for .sourceMaps, cannot use both\");\n }\n}\n\nfunction assertEnvSet(\n loc: OptionPath,\n value: unknown,\n): void | EnvSet<InputOptions> {\n if (loc.parent.type === \"env\") {\n throw new Error(`${msg(loc)} is not allowed inside of another .env block`);\n }\n const parent: RootPath | OverridesPath = loc.parent;\n\n const obj = assertObject(loc, value);\n if (obj) {\n // Validate but don't copy the .env object in order to preserve\n // object identity for use during config chain processing.\n for (const envName of Object.keys(obj)) {\n const env = assertObject(access(loc, envName), obj[envName]);\n if (!env) continue;\n\n const envLoc = {\n type: \"env\",\n name: envName,\n parent,\n } as const;\n validateNested(envLoc, env);\n }\n }\n return obj;\n}\n\nfunction assertOverridesList(\n loc: OptionPath,\n value: unknown[],\n): undefined | InputOptions[] {\n if (loc.parent.type === \"env\") {\n throw new Error(`${msg(loc)} is not allowed inside an .env block`);\n }\n if (loc.parent.type === \"overrides\") {\n throw new Error(`${msg(loc)} is not allowed inside an .overrides block`);\n }\n const parent: RootPath = loc.parent;\n\n const arr = assertArray(loc, value);\n if (arr) {\n for (const [index, item] of arr.entries()) {\n const objLoc = access(loc, index);\n const env = assertObject(objLoc, item);\n if (!env) throw new Error(`${msg(objLoc)} must be an object`);\n\n const overridesLoc = {\n type: \"overrides\",\n index,\n parent,\n } as const;\n validateNested(overridesLoc, env);\n }\n }\n return arr;\n}\n\nexport function checkNoUnwrappedItemOptionPairs<API>(\n items: UnloadedDescriptor<API>[],\n index: number,\n type: \"plugin\" | \"preset\",\n e: Error,\n): void {\n if (index === 0) return;\n\n const lastItem = items[index - 1];\n const thisItem = items[index];\n\n if (\n lastItem.file &&\n lastItem.options === undefined &&\n typeof thisItem.value === \"object\"\n ) {\n e.message +=\n `\\n- Maybe you meant to use\\n` +\n `\"${type}s\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n thisItem.value,\n undefined,\n 2,\n )}]\\n]\\n` +\n `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`;\n }\n}\n"],"mappings":"AAIA,OAAOA,OAAO,MAAM,cAAc;AAClC,SACEC,GAAG,EACHC,MAAM,EACNC,YAAY,EACZC,aAAa,EACbC,YAAY,EACZC,WAAW,EACXC,oBAAoB,EACpBC,oBAAoB,EACpBC,gBAAgB,EAChBC,gBAAgB,EAChBC,0BAA0B,EAC1BC,sBAAsB,EACtBC,mBAAmB,EACnBC,cAAc,EACdC,cAAc,EACdC,gBAAgB,EAChBC,aAAa,EACbC,gBAAgB,EAChBC,aAAa,EACbC,iBAAiB,QACZ,wBAAwB;AAW/B,OAAOC,WAAW,MAAM,8BAA8B;AAMtD,MAAMC,eAA6B,GAAG;EACpCC,GAAG,EAAEpB,YAA8C;EACnDqB,IAAI,EAAErB,YAA+C;EACrDsB,QAAQ,EAAEV,cAAqD;EAC/DW,UAAU,EAAEd,sBAA+D;EAE3Ee,MAAM,EAAEpB,oBAAyD;EACjEqB,QAAQ,EAAEzB,YAAmD;EAC7D0B,gBAAgB,EAAE1B,YAA2D;EAC7E2B,IAAI,EAAE1B,aAAgD;EACtD2B,GAAG,EAAE3B,aAA+C;EAEpD4B,aAAa,EAAE5B,aAAyD;EAExE6B,OAAO,EAAE9B;AACX,CAAC;AAED,MAAM+B,kBAAgC,GAAG;EACvCC,OAAO,EAAE/B,aAAmD;EAC5DgC,YAAY,EAAEvB;AAChB,CAAC;AAED,MAAMwB,oBAAkC,GAAG;EACzCC,OAAO,EA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,8BAA8B,GAC9B,IAAIR,IAAI,cAAckC,QAAQ,CAACE,IAAI,CAACG,OAAO,MAAMC,IAAI,CAACC,SAAS,CAC7DN,QAAQ,CAACb,KAAK,EACdgB,SAAS,EACT,CACF,CAAC,QAAQ,GACT,iBAAiBtC,IAAI,gEAAgE;EACzF;AACF","ignoreList":[]} |
| import { assertString, assertFunction, assertObject, msg } from "./option-assertions.js"; | ||
| const VALIDATORS = { | ||
| name: assertString, | ||
| manipulateOptions: assertFunction, | ||
| pre: assertFunction, | ||
| post: assertFunction, | ||
| inherits: assertFunction, | ||
| visitor: assertVisitorMap, | ||
| parserOverride: assertFunction, | ||
| generatorOverride: assertFunction | ||
| }; | ||
| function assertVisitorMap(loc, value) { | ||
| const obj = assertObject(loc, value); | ||
| if (obj) { | ||
| Object.keys(obj).forEach(prop => { | ||
| if (prop !== "_exploded" && prop !== "_verified") { | ||
| assertVisitorHandler(prop, obj[prop]); | ||
| } | ||
| }); | ||
| if (obj.enter || obj.exit) { | ||
| throw new Error(`${msg(loc)} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`); | ||
| } | ||
| } | ||
| return obj; | ||
| } | ||
| function assertVisitorHandler(key, value) { | ||
| if (value && typeof value === "object") { | ||
| Object.keys(value).forEach(handler => { | ||
| if (handler !== "enter" && handler !== "exit") { | ||
| throw new Error(`.visitor["${key}"] may only have .enter and/or .exit handlers.`); | ||
| } | ||
| }); | ||
| } else if (typeof value !== "function") { | ||
| throw new Error(`.visitor["${key}"] must be a function`); | ||
| } | ||
| } | ||
| export function validatePluginObject(obj) { | ||
| const rootPath = { | ||
| type: "root", | ||
| source: "plugin" | ||
| }; | ||
| Object.keys(obj).forEach(key => { | ||
| const validator = VALIDATORS[key]; | ||
| if (validator) { | ||
| const optLoc = { | ||
| type: "option", | ||
| name: key, | ||
| parent: rootPath | ||
| }; | ||
| validator(optLoc, obj[key]); | ||
| } else { | ||
| const invalidPluginPropertyError = new Error(`.${key} is not a valid Plugin property`); | ||
| invalidPluginPropertyError.code = "BABEL_UNKNOWN_PLUGIN_PROPERTY"; | ||
| throw invalidPluginPropertyError; | ||
| } | ||
| }); | ||
| return obj; | ||
| } | ||
| //# sourceMappingURL=plugins.js.map |
| {"version":3,"names":["assertString","assertFunction","assertObject","msg","VALIDATORS","name","manipulateOptions","pre","post","inherits","visitor","assertVisitorMap","parserOverride","generatorOverride","loc","value","obj","Object","keys","forEach","prop","assertVisitorHandler","enter","exit","Error","key","handler","validatePluginObject","rootPath","type","source","validator","optLoc","parent","invalidPluginPropertyError","code"],"sources":["../../../src/config/validation/plugins.ts"],"sourcesContent":["import {\n assertString,\n assertFunction,\n assertObject,\n msg,\n} from \"./option-assertions.ts\";\n\nimport type {\n ValidatorSet,\n Validator,\n OptionPath,\n RootPath,\n} from \"./option-assertions.ts\";\nimport type { parse, ParserOptions } from \"@babel/parser\";\nimport type { Visitor } from \"@babel/traverse\";\nimport type { ResolvedOptions } from \"./options.ts\";\nimport type { File, PluginAPI, PluginPass } from \"../../index.ts\";\nimport type { GeneratorOptions, GeneratorResult } from \"@babel/generator\";\nimport type babelGenerator from \"@babel/generator\";\n\n// Note: The casts here are just meant to be static assertions to make sure\n// that the assertion functions actually assert that the value's type matches\n// the declared types.\nconst VALIDATORS: ValidatorSet = {\n name: assertString as Validator<PluginObject[\"name\"]>,\n manipulateOptions: assertFunction as Validator<\n PluginObject[\"manipulateOptions\"]\n >,\n pre: assertFunction as Validator<PluginObject[\"pre\"]>,\n post: assertFunction as Validator<PluginObject[\"post\"]>,\n inherits: assertFunction as Validator<PluginObject[\"inherits\"]>,\n visitor: assertVisitorMap as Validator<PluginObject[\"visitor\"]>,\n\n parserOverride: assertFunction as Validator<PluginObject[\"parserOverride\"]>,\n generatorOverride: assertFunction as Validator<\n PluginObject[\"generatorOverride\"]\n >,\n};\n\nfunction assertVisitorMap(loc: OptionPath, value: unknown): Visitor {\n const obj = assertObject(loc, value);\n if (obj) {\n Object.keys(obj).forEach(prop => {\n if (prop !== \"_exploded\" && prop !== \"_verified\") {\n assertVisitorHandler(prop, obj[prop]);\n }\n });\n\n if (obj.enter || obj.exit) {\n throw new Error(\n `${msg(\n loc,\n )} cannot contain catch-all \"enter\" or \"exit\" handlers. Please target individual nodes.`,\n );\n }\n }\n return obj as Visitor;\n}\n\nfunction assertVisitorHandler(\n key: string,\n value: unknown,\n): asserts value is VisitorHandler {\n if (value && typeof value === \"object\") {\n Object.keys(value).forEach((handler: string) => {\n if (handler !== \"enter\" && handler !== \"exit\") {\n throw new Error(\n `.visitor[\"${key}\"] may only have .enter and/or .exit handlers.`,\n );\n }\n });\n } else if (typeof value !== \"function\") {\n throw new Error(`.visitor[\"${key}\"] must be a function`);\n }\n}\n\ntype VisitorHandler =\n | Function\n | {\n enter?: Function;\n exit?: Function;\n };\n\nexport type PluginObject<S extends PluginPass = PluginPass> = {\n name?: string;\n manipulateOptions?: (\n options: ResolvedOptions,\n parserOpts: ParserOptions,\n ) => void;\n pre?: (this: S, file: File) => void | Promise<void>;\n post?: (this: S, file: File) => void | Promise<void>;\n inherits?: (\n api: PluginAPI,\n options: unknown,\n dirname: string,\n ) => PluginObject;\n visitor?: Visitor<S>;\n parserOverride?: (\n ...args: [...Parameters<typeof parse>, typeof parse]\n ) => ReturnType<typeof parse>;\n generatorOverride?: (\n ast: File[\"ast\"],\n generatorOpts: GeneratorOptions,\n code: File[\"code\"],\n generate: typeof babelGenerator,\n ) => GeneratorResult;\n};\n\nexport function validatePluginObject(\n obj: Record<string, unknown>,\n): PluginObject {\n const rootPath: RootPath = {\n type: \"root\",\n source: \"plugin\",\n };\n Object.keys(obj).forEach((key: string) => {\n const validator = VALIDATORS[key];\n\n if (validator) {\n const optLoc: OptionPath = {\n type: \"option\",\n name: key,\n parent: rootPath,\n };\n validator(optLoc, obj[key]);\n } else {\n const invalidPluginPropertyError = new Error(\n `.${key} is not a valid Plugin property`,\n );\n // @ts-expect-error todo(flow->ts) consider adding BabelConfigError with code field\n invalidPluginPropertyError.code = \"BAB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,CACb,aAAaC,GAAG,gDAClB,CAAC;MACH;IACF,CAAC,CAAC;EACJ,CAAC,MAAM,IAAI,OAAOV,KAAK,KAAK,UAAU,EAAE;IACtC,MAAM,IAAIS,KAAK,CAAC,aAAaC,GAAG,uBAAuB,CAAC;EAC1D;AACF;AAkCA,OAAO,SAASE,oBAAoBA,CAClCX,GAA4B,EACd;EACd,MAAMY,QAAkB,GAAG;IACzBC,IAAI,EAAE,MAAM;IACZC,MAAM,EAAE;EACV,CAAC;EACDb,MAAM,CAACC,IAAI,CAACF,GAAG,CAAC,CAACG,OAAO,CAAEM,GAAW,IAAK;IACxC,MAAMM,SAAS,GAAG3B,UAAU,CAACqB,GAAG,CAAC;IAEjC,IAAIM,SAAS,EAAE;MACb,MAAMC,MAAkB,GAAG;QACzBH,IAAI,EAAE,QAAQ;QACdxB,IAAI,EAAEoB,GAAG;QACTQ,MAAM,EAAEL;MACV,CAAC;MACDG,SAAS,CAACC,MAAM,EAAEhB,GAAG,CAACS,GAAG,CAAC,CAAC;IAC7B,CAAC,MAAM;MACL,MAAMS,0BAA0B,GAAG,IAAIV,KAAK,CAC1C,IAAIC,GAAG,iCACT,CAAC;MAEDS,0BAA0B,CAACC,IAAI,GAAG,+BAA+B;MACjE,MAAMD,0BAA0B;IAClC;EACF,CAAC,CAAC;EAEF,OAAOlB,GAAG;AACZ","ignoreList":[]} |
| export default { | ||
| auxiliaryComment: { | ||
| message: "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" | ||
| }, | ||
| blacklist: { | ||
| message: "Put the specific transforms you want in the `plugins` option" | ||
| }, | ||
| breakConfig: { | ||
| message: "This is not a necessary option in Babel 6" | ||
| }, | ||
| experimental: { | ||
| message: "Put the specific transforms you want in the `plugins` option" | ||
| }, | ||
| externalHelpers: { | ||
| message: "Use the `external-helpers` plugin instead. " + "Check out http://babeljs.io/docs/plugins/external-helpers/" | ||
| }, | ||
| extra: { | ||
| message: "" | ||
| }, | ||
| jsxPragma: { | ||
| message: "use the `pragma` option in the `react-jsx` plugin. " + "Check out http://babeljs.io/docs/plugins/transform-react-jsx/" | ||
| }, | ||
| loose: { | ||
| message: "Specify the `loose` option for the relevant plugin you are using " + "or use a preset that sets the option." | ||
| }, | ||
| metadataUsedHelpers: { | ||
| message: "Not required anymore as this is enabled by default" | ||
| }, | ||
| modules: { | ||
| message: "Use the corresponding module transform plugin in the `plugins` option. " + "Check out http://babeljs.io/docs/plugins/#modules" | ||
| }, | ||
| nonStandard: { | ||
| message: "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. " + "Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" | ||
| }, | ||
| optional: { | ||
| message: "Put the specific transforms you want in the `plugins` option" | ||
| }, | ||
| sourceMapName: { | ||
| message: "The `sourceMapName` option has been removed because it makes more sense for the " + "tooling that calls Babel to assign `map.file` themselves." | ||
| }, | ||
| stage: { | ||
| message: "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" | ||
| }, | ||
| whitelist: { | ||
| message: "Put the specific transforms you want in the `plugins` option" | ||
| }, | ||
| resolveModuleSource: { | ||
| version: 6, | ||
| message: "Use `babel-plugin-module-resolver@3`'s 'resolvePath' options" | ||
| }, | ||
| metadata: { | ||
| version: 6, | ||
| message: "Generated plugin metadata is always included in the output result" | ||
| }, | ||
| sourceMapTarget: { | ||
| version: 6, | ||
| message: "The `sourceMapTarget` option has been removed because it makes more sense for the tooling " + "that calls Babel to assign `map.file` themselves." | ||
| } | ||
| }; | ||
| //# sourceMappingURL=removed.js.map |
| {"version":3,"names":["auxiliaryComment","message","blacklist","breakConfig","experimental","externalHelpers","extra","jsxPragma","loose","metadataUsedHelpers","modules","nonStandard","optional","sourceMapName","stage","whitelist","resolveModuleSource","version","metadata","sourceMapTarget"],"sources":["../../../src/config/validation/removed.ts"],"sourcesContent":["export default {\n auxiliaryComment: {\n message: \"Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`\",\n },\n blacklist: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n breakConfig: {\n message: \"This is not a necessary option in Babel 6\",\n },\n experimental: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n externalHelpers: {\n message:\n \"Use the `external-helpers` plugin instead. \" +\n \"Check out http://babeljs.io/docs/plugins/external-helpers/\",\n },\n extra: {\n message: \"\",\n },\n jsxPragma: {\n message:\n \"use the `pragma` option in the `react-jsx` plugin. \" +\n \"Check out http://babeljs.io/docs/plugins/transform-react-jsx/\",\n },\n loose: {\n message:\n \"Specify the `loose` option for the relevant plugin you are using \" +\n \"or use a preset that sets the option.\",\n },\n metadataUsedHelpers: {\n message: \"Not required anymore as this is enabled by default\",\n },\n modules: {\n message:\n \"Use the corresponding module transform plugin in the `plugins` option. \" +\n \"Check out http://babeljs.io/docs/plugins/#modules\",\n },\n nonStandard: {\n message:\n \"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. \" +\n \"Also check out the react preset http://babeljs.io/docs/plugins/preset-react/\",\n },\n optional: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n sourceMapName: {\n message:\n \"The `sourceMapName` option has been removed because it makes more sense for the \" +\n \"tooling that calls Babel to assign `map.file` themselves.\",\n },\n stage: {\n message:\n \"Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets\",\n },\n whitelist: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n\n resolveModuleSource: {\n version: 6,\n message: \"Use `babel-plugin-module-resolver@3`'s 'resolvePath' options\",\n },\n metadata: {\n version: 6,\n message:\n \"Generated plugin metadata is always included in the output result\",\n },\n sourceMapTarget: {\n version: 6,\n message:\n \"The `sourceMapTarget` option has been removed because it makes more sense for the tooling \" +\n \"that calls Babel to assign `map.file` themselves.\",\n },\n} as Record<string, { version?: number; message: string }>;\n"],"mappings":"AAAA,eAAe;EACbA,gBAAgB,EAAE;IAChBC,OAAO,EAAE;EACX,CAAC;EACDC,SAAS,EAAE;IACTD,OAAO,EAAE;EACX,CAAC;EACDE,WAAW,EAAE;IACXF,OAAO,EAAE;EACX,CAAC;EACDG,YAAY,EAAE;IACZH,OAAO,EAAE;EACX,CAAC;EACDI,eAAe,EAAE;IACfJ,OAAO,EACL,6CAA6C,GAC7C;EACJ,CAAC;EACDK,KAAK,EAAE;IACLL,OAAO,EAAE;EACX,CAAC;EACDM,SAAS,EAAE;IACTN,OAAO,EACL,qDAAqD,GACrD;EACJ,CAAC;EACDO,KAAK,EAAE;IACLP,OAAO,EACL,mEAAmE,GACnE;EACJ,CAAC;EACDQ,mBAAmB,EAAE;IACnBR,OAAO,EAAE;EACX,CAAC;EACDS,OAAO,EAAE;IACPT,OAAO,EACL,yEAAyE,GACzE;EACJ,CAAC;EACDU,WAAW,EAAE;IACXV,OAAO,EACL,8EAA8E,GAC9E;EACJ,CAAC;EACDW,QAAQ,EAAE;IACRX,OAAO,EAAE;EACX,CAAC;EACDY,aAAa,EAAE;IACbZ,OAAO,EACL,kFAAkF,GAClF;EACJ,CAAC;EACDa,KAAK,EAAE;IACLb,OAAO,EACL;EACJ,CAAC;EACDc,SAAS,EAAE;IACTd,OAAO,EAAE;EACX,CAAC;EAEDe,mBAAmB,EAAE;IACnBC,OAAO,EAAE,CAAC;IACVhB,OAAO,EAAE;EACX,CAAC;EACDiB,QAAQ,EAAE;IACRD,OAAO,EAAE,CAAC;IACVhB,OAAO,EACL;EACJ,CAAC;EACDkB,eAAe,EAAE;IACfF,OAAO,EAAE,CAAC;IACVhB,OAAO,EACL,4FAA4F,GAC5F;EACJ;AACF,CAAC","ignoreList":[]} |
| import { injectVirtualStackFrame, expectedError } from "./rewrite-stack-trace.js"; | ||
| export default class ConfigError extends Error { | ||
| constructor(message, filename) { | ||
| super(message); | ||
| expectedError(this); | ||
| if (filename) injectVirtualStackFrame(this, filename); | ||
| } | ||
| } | ||
| //# sourceMappingURL=config-error.js.map |
| {"version":3,"names":["injectVirtualStackFrame","expectedError","ConfigError","Error","constructor","message","filename"],"sources":["../../src/errors/config-error.ts"],"sourcesContent":["import {\n injectVirtualStackFrame,\n expectedError,\n} from \"./rewrite-stack-trace.ts\";\n\nexport default class ConfigError extends Error {\n constructor(message: string, filename?: string) {\n super(message);\n expectedError(this);\n if (filename) injectVirtualStackFrame(this, filename);\n }\n}\n"],"mappings":"AAAA,SACEA,uBAAuB,EACvBC,aAAa,QACR,0BAA0B;AAEjC,eAAe,MAAMC,WAAW,SAASC,KAAK,CAAC;EAC7CC,WAAWA,CAACC,OAAe,EAAEC,QAAiB,EAAE;IAC9C,KAAK,CAACD,OAAO,CAAC;IACdJ,aAAa,CAAC,IAAI,CAAC;IACnB,IAAIK,QAAQ,EAAEN,uBAAuB,CAAC,IAAI,EAAEM,QAAQ,CAAC;EACvD;AACF","ignoreList":[]} |
| import gensync from "gensync"; | ||
| const runGenerator = gensync(function* (item) { | ||
| return yield* item; | ||
| }); | ||
| export const isAsync = gensync({ | ||
| sync: () => false, | ||
| errback: cb => cb(null, true) | ||
| }); | ||
| export function maybeAsync(fn, message) { | ||
| return gensync({ | ||
| sync(...args) { | ||
| const result = fn.apply(this, args); | ||
| if (isThenable(result)) throw new Error(message); | ||
| return result; | ||
| }, | ||
| async(...args) { | ||
| return Promise.resolve(fn.apply(this, args)); | ||
| } | ||
| }); | ||
| } | ||
| const withKind = gensync({ | ||
| sync: cb => cb("sync"), | ||
| async: async cb => cb("async") | ||
| }); | ||
| export function forwardAsync(action, cb) { | ||
| const g = gensync(action); | ||
| return withKind(kind => { | ||
| const adapted = g[kind]; | ||
| return cb(adapted); | ||
| }); | ||
| } | ||
| export const onFirstPause = gensync({ | ||
| name: "onFirstPause", | ||
| arity: 2, | ||
| sync: function (item) { | ||
| return runGenerator.sync(item); | ||
| }, | ||
| errback: function (item, firstPause, cb) { | ||
| let completed = false; | ||
| runGenerator.errback(item, (err, value) => { | ||
| completed = true; | ||
| cb(err, value); | ||
| }); | ||
| if (!completed) { | ||
| firstPause(); | ||
| } | ||
| } | ||
| }); | ||
| export const waitFor = gensync({ | ||
| sync: x => x, | ||
| async: async x => x | ||
| }); | ||
| export function isThenable(val) { | ||
| return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; | ||
| } | ||
| //# sourceMappingURL=async.js.map |
| {"version":3,"names":["gensync","runGenerator","item","isAsync","sync","errback","cb","maybeAsync","fn","message","args","result","apply","isThenable","Error","async","Promise","resolve","withKind","forwardAsync","action","g","kind","adapted","onFirstPause","name","arity","firstPause","completed","err","value","waitFor","x","val","then"],"sources":["../../src/gensync-utils/async.ts"],"sourcesContent":["import gensync, { type Gensync, type Handler, type Callback } from \"gensync\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nconst runGenerator: {\n sync<Return>(gen: Handler<Return>): Return;\n async<Return>(gen: Handler<Return>): Promise<Return>;\n errback<Return>(gen: Handler<Return>, cb: Callback<Return>): void;\n} = gensync(function* (item: Handler<any>): Handler<any> {\n return yield* item;\n});\n\n// This Gensync returns true if the current execution context is\n// asynchronous, otherwise it returns false.\nexport const isAsync = gensync({\n sync: () => false,\n errback: cb => cb(null, true),\n});\n\n// This function wraps any functions (which could be either synchronous or\n// asynchronous) with a Gensync. If the wrapped function returns a promise\n// but the current execution context is synchronous, it will throw the\n// provided error.\n// This is used to handle user-provided functions which could be asynchronous.\nexport function maybeAsync<Args extends unknown[], Return>(\n fn: (...args: Args) => Return,\n message: string,\n): Gensync<Args, Return> {\n return gensync({\n sync(...args) {\n const result = fn.apply(this, args);\n if (isThenable(result)) throw new Error(message);\n return result;\n },\n async(...args) {\n return Promise.resolve(fn.apply(this, args));\n },\n });\n}\n\nconst withKind = gensync({\n sync: cb => cb(\"sync\"),\n async: async cb => cb(\"async\"),\n}) as <T>(cb: (kind: \"sync\" | \"async\") => MaybePromise<T>) => Handler<T>;\n\n// This function wraps a generator (or a Gensync) into another function which,\n// when called, will run the provided generator in a sync or async way, depending\n// on the execution context where this forwardAsync function is called.\n// This is useful, for example, when passing a callback to a function which isn't\n// aware of gensync, but it only knows about synchronous and asynchronous functions.\n// An example is cache.using, which being exposed to the user must be as simple as\n// possible:\n// yield* forwardAsync(gensyncFn, wrappedFn =>\n// cache.using(x => {\n// // Here we don't know about gensync. wrappedFn is a\n// // normal sync or async function\n// return wrappedFn(x);\n// })\n// )\nexport function forwardAsync<Args extends unknown[], Return>(\n action: (...args: Args) => Handler<Return>,\n cb: (\n adapted: (...args: Args) => MaybePromise<Return>,\n ) => MaybePromise<Return>,\n): Handler<Return> {\n const g = gensync(action);\n return withKind(kind => {\n const adapted = g[kind];\n return cb(adapted);\n });\n}\n\n// If the given generator is executed asynchronously, the first time that it\n// is paused (i.e. When it yields a gensync generator which can't be run\n// synchronously), call the \"firstPause\" callback.\nexport const onFirstPause = gensync<\n [gen: Handler<unknown>, firstPause: () => void],\n unknown\n>({\n name: \"onFirstPause\",\n arity: 2,\n sync: function (item) {\n return runGenerator.sync(item);\n },\n errback: function (item, firstPause, cb) {\n let completed = false;\n\n runGenerator.errback(item, (err, value) => {\n completed = true;\n cb(err, value);\n });\n\n if (!completed) {\n firstPause();\n }\n },\n}) as <T>(gen: Handler<T>, firstPause: () => void) => Handler<T>;\n\n// Wait for the given promise to be resolved\nexport const waitFor = gensync({\n sync: x => x,\n async: async x => x,\n}) as <T>(p: T | Promise<T>) => Handler<T>;\n\nexport function isThenable<T = any>(val: any): val is PromiseLike<T> {\n return (\n !!val &&\n (typeof val === \"object\" || typeof val === \"function\") &&\n !!val.then &&\n typeof val.then === \"function\"\n );\n}\n"],"mappings":"AAAA,OAAOA,OAAO,MAAqD,SAAS;AAI5E,MAAMC,YAIL,GAAGD,OAAO,CAAC,WAAWE,IAAkB,EAAgB;EACvD,OAAO,OAAOA,IAAI;AACpB,CAAC,CAAC;AAIF,OAAO,MAAMC,OAAO,GAAGH,OAAO,CAAC;EAC7BI,IAAI,EAAEA,CAAA,KAAM,KAAK;EACjBC,OAAO,EAAEC,EAAE,IAAIA,EAAE,CAAC,IAAI,EAAE,IAAI;AAC9B,CAAC,CAAC;AAOF,OAAO,SAASC,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AAO,CAACH,IAAI,EAAE,CAAC2B,GAAG,EAAEC,KAAK,KAAK;MACzCF,SAAS,GAAG,IAAI;MAChBtB,EAAE,CAACuB,GAAG,EAAEC,KAAK,CAAC;IAChB,CAAC,CAAC;IAEF,IAAI,CAACF,SAAS,EAAE;MACdD,UAAU,CAAC,CAAC;IACd;EACF;AACF,CAAC,CAA+D;AAGhE,OAAO,MAAMI,OAAO,GAAG/B,OAAO,CAAC;EAC7BI,IAAI,EAAE4B,CAAC,IAAIA,CAAC;EACZjB,KAAK,EAAE,MAAMiB,CAAC,IAAIA;AACpB,CAAC,CAAyC;AAE1C,OAAO,SAASnB,UAAUA,CAAUoB,GAAQ,EAAyB;EACnE,OACE,CAAC,CAACA,GAAG,KACJ,OAAOA,GAAG,KAAK,QAAQ,IAAI,OAAOA,GAAG,KAAK,UAAU,CAAC,IACtD,CAAC,CAACA,GAAG,CAACC,IAAI,IACV,OAAOD,GAAG,CAACC,IAAI,KAAK,UAAU;AAElC","ignoreList":[]} |
| import fs from "node:fs"; | ||
| import gensync from "gensync"; | ||
| export const readFile = gensync({ | ||
| sync: fs.readFileSync, | ||
| errback: fs.readFile | ||
| }); | ||
| export const stat = gensync({ | ||
| sync: fs.statSync, | ||
| errback: fs.stat | ||
| }); | ||
| //# sourceMappingURL=fs.js.map |
| {"version":3,"names":["fs","gensync","readFile","sync","readFileSync","errback","stat","statSync"],"sources":["../../src/gensync-utils/fs.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport gensync from \"gensync\";\n\nexport const readFile = gensync<[filepath: string, encoding: \"utf8\"], string>({\n sync: fs.readFileSync,\n errback: fs.readFile,\n});\n\nexport const stat = gensync({\n sync: fs.statSync,\n errback: fs.stat,\n});\n"],"mappings":"AAAA,OAAOA,EAAE,MAAM,SAAS;AACxB,OAAOC,OAAO,MAAM,SAAS;AAE7B,OAAO,MAAMC,QAAQ,GAAGD,OAAO,CAA+C;EAC5EE,IAAI,EAAEH,EAAE,CAACI,YAAY;EACrBC,OAAO,EAAEL,EAAE,CAACE;AACd,CAAC,CAAC;AAEF,OAAO,MAAMI,IAAI,GAAGL,OAAO,CAAC;EAC1BE,IAAI,EAAEH,EAAE,CAACO,QAAQ;EACjBF,OAAO,EAAEL,EAAE,CAACM;AACd,CAAC,CAAC","ignoreList":[]} |
| import { isAsync, waitFor } from "./async.js"; | ||
| export function once(fn) { | ||
| let result; | ||
| let resultP; | ||
| let promiseReferenced = false; | ||
| return function* () { | ||
| if (!result) { | ||
| if (resultP) { | ||
| promiseReferenced = true; | ||
| return yield* waitFor(resultP); | ||
| } | ||
| if (!(yield* isAsync())) { | ||
| try { | ||
| result = { | ||
| ok: true, | ||
| value: yield* fn() | ||
| }; | ||
| } catch (error) { | ||
| result = { | ||
| ok: false, | ||
| value: error | ||
| }; | ||
| } | ||
| } else { | ||
| let resolve, reject; | ||
| resultP = new Promise((res, rej) => { | ||
| resolve = res; | ||
| reject = rej; | ||
| }); | ||
| try { | ||
| result = { | ||
| ok: true, | ||
| value: yield* fn() | ||
| }; | ||
| resultP = null; | ||
| if (promiseReferenced) resolve(result.value); | ||
| } catch (error) { | ||
| result = { | ||
| ok: false, | ||
| value: error | ||
| }; | ||
| resultP = null; | ||
| if (promiseReferenced) reject(error); | ||
| } | ||
| } | ||
| } | ||
| if (result.ok) return result.value;else throw result.value; | ||
| }; | ||
| } | ||
| //# sourceMappingURL=functional.js.map |
| {"version":3,"names":["isAsync","waitFor","once","fn","result","resultP","promiseReferenced","ok","value","error","resolve","reject","Promise","res","rej"],"sources":["../../src/gensync-utils/functional.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport { isAsync, waitFor } from \"./async.ts\";\n\nexport function once<R>(fn: () => Handler<R>): () => Handler<R> {\n let result: { ok: true; value: R } | { ok: false; value: unknown };\n let resultP: Promise<R>;\n let promiseReferenced = false;\n return function* () {\n if (!result) {\n if (resultP) {\n promiseReferenced = true;\n return yield* waitFor(resultP);\n }\n\n if (!(yield* isAsync())) {\n try {\n result = { ok: true, value: yield* fn() };\n } catch (error) {\n result = { ok: false, value: error };\n }\n } else {\n let resolve: (result: R) => void, reject: (error: unknown) => void;\n resultP = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n try {\n result = { ok: true, value: yield* fn() };\n // Avoid keeping the promise around\n // now that we have the result.\n resultP = null;\n // We only resolve/reject the promise if it has been actually\n // referenced. If there are no listeners we can forget about it.\n // In the reject case, this avoid uncatchable unhandledRejection\n // events.\n if (promiseReferenced) resolve(result.value);\n } catch (error) {\n result = { ok: false, value: error };\n resultP = null;\n if (promiseReferenced) reject(error);\n }\n }\n }\n\n if (result.ok) return result.value;\n else throw result.value;\n };\n}\n"],"mappings":"AAEA,SAASA,OAAO,EAAEC,OAAO,QAAQ,YAAY;AAE7C,OAAO,SAASC,IAAIA,CAAIC,EAAoB,EAAoB;EAC9D,IAAIC,MAA8D;EAClE,IAAIC,OAAmB;EACvB,IAAIC,iBAAiB,GAAG,KAAK;EAC7B,OAAO,aAAa;IAClB,IAAI,CAACF,MAAM,EAAE;MACX,IAAIC,OAAO,EAAE;QACXC,iBAAiB,GAAG,IAAI;QACxB,OAAO,OAAOL,OAAO,CAACI,OAAO,CAAC;MAChC;MAEA,IAAI,EAAE,OAAOL,OAAO,CAAC,CAAC,CAAC,EAAE;QACvB,IAAI;UACFI,MAAM,GAAG;YAAEG,EAAE,EAAE,IAAI;YAAEC,KAAK,EAAE,OAAOL,EAAE,CAAC;UAAE,CAAC;QAC3C,CAAC,CAAC,OAAOM,KAAK,EAAE;UACdL,MAAM,GAAG;YAAEG,EAAE,EAAE,KAAK;YAAEC,KAAK,EAAEC;UAAM,CAAC;QACtC;MACF,CAAC,MAAM;QACL,IAAIC,OAA4B,EAAEC,MAAgC;QAClEN,OAAO,GAAG,IAAIO,OAAO,CAAC,CAACC,GAAG,EAAEC,GAAG,KAAK;UAClCJ,OAAO,GAAGG,GAAG;UACbF,MAAM,GAAGG,GAAG;QACd,CAAC,CAAC;QAEF,IAAI;UACFV,MAAM,GAAG;YAAEG,EAAE,EAAE,IAAI;YAAEC,KAAK,EAAE,OAAOL,EAAE,CAAC;UAAE,CAAC;UAGzCE,OAAO,GAAG,IAAI;UAKd,IAAIC,iBAAiB,EAAEI,OAAO,CAACN,MAAM,CAACI,KAAK,CAAC;QAC9C,CAAC,CAAC,OAAOC,KAAK,EAAE;UACdL,MAAM,GAAG;YAAEG,EAAE,EAAE,KAAK;YAAEC,KAAK,EAAEC;UAAM,CAAC;UACpCJ,OAAO,GAAG,IAAI;UACd,IAAIC,iBAAiB,EAAEK,MAAM,CAACF,KAAK,CAAC;QACtC;MACF;IACF;IAEA,IAAIL,MAAM,CAACG,EAAE,EAAE,OAAOH,MAAM,CAACI,KAAK,CAAC,KAC9B,MAAMJ,MAAM,CAACI,KAAK;EACzB,CAAC;AACH","ignoreList":[]} |
-30
| import gensync from "gensync"; | ||
| import loadConfig from "./config/index.js"; | ||
| import parser from "./parser/index.js"; | ||
| import normalizeOptions from "./transformation/normalize-opts.js"; | ||
| import { beginHiddenCallStack } from "./errors/rewrite-stack-trace.js"; | ||
| const parseRunner = gensync(function* parse(code, opts) { | ||
| const config = yield* loadConfig(opts); | ||
| if (config === null) { | ||
| return null; | ||
| } | ||
| return yield* parser(config.passes, normalizeOptions(config), code); | ||
| }); | ||
| export const parse = function parse(code, opts, callback) { | ||
| if (typeof opts === "function") { | ||
| callback = opts; | ||
| opts = undefined; | ||
| } | ||
| if (callback === undefined) { | ||
| throw new Error("Starting from Babel 8.0.0, the 'parse' function expects a callback. If you need to call it synchronously, please use 'parseSync'."); | ||
| } | ||
| beginHiddenCallStack(parseRunner.errback)(code, opts, callback); | ||
| }; | ||
| export function parseSync(...args) { | ||
| return beginHiddenCallStack(parseRunner.sync)(...args); | ||
| } | ||
| export function parseAsync(...args) { | ||
| return beginHiddenCallStack(parseRunner.async)(...args); | ||
| } | ||
| //# sourceMappingURL=parse.js.map |
| {"version":3,"names":["gensync","loadConfig","parser","normalizeOptions","beginHiddenCallStack","parseRunner","parse","code","opts","config","passes","callback","undefined","Error","errback","parseSync","args","sync","parseAsync","async"],"sources":["../src/parse.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig, { type InputOptions } from \"./config/index.ts\";\nimport parser, { type ParseResult } from \"./parser/index.ts\";\nimport normalizeOptions from \"./transformation/normalize-opts.ts\";\n\nimport { beginHiddenCallStack } from \"./errors/rewrite-stack-trace.ts\";\n\ntype FileParseCallback = {\n (err: Error, ast: null): void;\n (err: null, ast: ParseResult | null): void;\n};\n\ntype Parse = {\n (code: string, callback: FileParseCallback): void;\n (\n code: string,\n opts: InputOptions | undefined | null,\n callback: FileParseCallback,\n ): void;\n};\n\nconst parseRunner = gensync(function* parse(\n code: string,\n opts: InputOptions | undefined | null,\n): Handler<ParseResult | null> {\n const config = yield* loadConfig(opts);\n\n if (config === null) {\n return null;\n }\n\n return yield* parser(config.passes, normalizeOptions(config), code);\n});\n\nexport const parse: Parse = function parse(\n code,\n opts?,\n callback?: FileParseCallback,\n) {\n if (typeof opts === \"function\") {\n callback = opts;\n opts = undefined as InputOptions;\n }\n\n if (callback === undefined) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'parse' function expects a callback. If you need to call it synchronously, please use 'parseSync'.\",\n );\n }\n\n beginHiddenCallStack(parseRunner.errback)(code, opts, callback);\n};\n\nexport function parseSync(...args: Parameters<typeof parseRunner.sync>) {\n return beginHiddenCallStack(parseRunner.sync)(...args);\n}\nexport function parseAsync(...args: Parameters<typeof parseRunner.async>) {\n return beginHiddenCallStack(parseRunner.async)(...args);\n}\n"],"mappings":"AAAA,OAAOA,OAAO,MAAwB,SAAS;AAE/C,OAAOC,UAAU,MAA6B,mBAAmB;AACjE,OAAOC,MAAM,MAA4B,mBAAmB;AAC5D,OAAOC,gBAAgB,MAAM,oCAAoC;AAEjE,SAASC,oBAAoB,QAAQ,iCAAiC;AAgBtE,MAAMC,WAAW,GAAGL,OAAO,CAAC,UAAUM,KAAKA,CACzCC,IAAY,EACZC,IAAqC,EACR;EAC7B,MAAMC,MAAM,GAAG,OAAOR,UAAU,CAACO,IAAI,CAAC;EAEtC,IAAIC,MAAM,KAAK,IAAI,EAAE;IACnB,OAAO,IAAI;EACb;EAEA,OAAO,OAAOP,MAAM,CAACO,MAAM,CAACC,MAAM,EAAEP,gBAAgB,CAACM,MAAM,CAAC,EAAEF,IAAI,CAAC;AACrE,CAAC,CAAC;AAEF,OAAO,MAAMD,KAAY,GAAG,SAASA,KAAKA,CACxCC,IAAI,EACJC,IAAK,EACLG,QAA4B,EAC5B;EACA,IAAI,OAAOH,IAAI,KAAK,UAAU,EAAE;IAC9BG,QAAQ,GAAGH,IAAI;IACfA,IAAI,GAAGI,SAAyB;EAClC;EAEA,IAAID,QAAQ,KAAKC,SAAS,EAAE;IAC1B,MAAM,IAAIC,KAAK,CACb,mIACF,CAAC;EACH;EAEAT,oBAAoB,CAACC,WAAW,CAACS,OAAO,CAAC,CAACP,IAAI,EAAEC,IAAI,EAAEG,QAAQ,CAAC;AACjE,CAAC;AAED,OAAO,SAASI,SAASA,CAAC,GAAGC,IAAyC,EAAE;EACtE,OAAOZ,oBAAoB,CAACC,WAAW,CAACY,IAAI,CAAC,CAAC,GAAGD,IAAI,CAAC;AACxD;AACA,OAAO,SAASE,UAAUA,CAAC,GAAGF,IAA0C,EAAE;EACxE,OAAOZ,oBAAoB,CAACC,WAAW,CAACc,KAAK,CAAC,CAAC,GAAGH,IAAI,CAAC;AACzD","ignoreList":[]} |
| import { parse } from "@babel/parser"; | ||
| import { codeFrameColumns } from "@babel/code-frame"; | ||
| import generateMissingPluginMessage from "./util/missing-plugin-helper.js"; | ||
| export default function* parser(pluginPasses, { | ||
| parserOpts, | ||
| highlightCode = true, | ||
| filename = "unknown" | ||
| }, code) { | ||
| try { | ||
| const results = []; | ||
| for (const plugins of pluginPasses) { | ||
| for (const plugin of plugins) { | ||
| const { | ||
| parserOverride | ||
| } = plugin; | ||
| if (parserOverride) { | ||
| const ast = parserOverride(code, parserOpts, parse); | ||
| if (ast !== undefined) results.push(ast); | ||
| } | ||
| } | ||
| } | ||
| if (results.length === 0) { | ||
| return parse(code, parserOpts); | ||
| } else if (results.length === 1) { | ||
| yield* []; | ||
| if (typeof results[0].then === "function") { | ||
| throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); | ||
| } | ||
| return results[0]; | ||
| } | ||
| throw new Error("More than one plugin attempted to override parsing."); | ||
| } catch (err) { | ||
| if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") { | ||
| err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file."; | ||
| } | ||
| const { | ||
| loc, | ||
| missingPlugin | ||
| } = err; | ||
| if (loc) { | ||
| const codeFrame = codeFrameColumns(code, { | ||
| start: { | ||
| line: loc.line, | ||
| column: loc.column + 1 | ||
| } | ||
| }, { | ||
| highlightCode | ||
| }); | ||
| if (missingPlugin) { | ||
| err.message = `${filename}: ` + generateMissingPluginMessage(missingPlugin[0], loc, codeFrame, filename); | ||
| } else { | ||
| err.message = `${filename}: ${err.message}\n\n` + codeFrame; | ||
| } | ||
| err.code = "BABEL_PARSE_ERROR"; | ||
| } | ||
| throw err; | ||
| } | ||
| } | ||
| //# sourceMappingURL=index.js.map |
| {"version":3,"names":["parse","codeFrameColumns","generateMissingPluginMessage","parser","pluginPasses","parserOpts","highlightCode","filename","code","results","plugins","plugin","parserOverride","ast","undefined","push","length","then","Error","err","message","loc","missingPlugin","codeFrame","start","line","column"],"sources":["../../src/parser/index.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\nimport { parse, type ParseResult } from \"@babel/parser\";\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport generateMissingPluginMessage from \"./util/missing-plugin-helper.ts\";\nimport type { PluginPasses } from \"../config/index.ts\";\nimport type { ResolvedOptions } from \"../config/validation/options.ts\";\n\nexport type { ParseResult };\n\nexport default function* parser(\n pluginPasses: PluginPasses,\n { parserOpts, highlightCode = true, filename = \"unknown\" }: ResolvedOptions,\n code: string,\n): Handler<ParseResult> {\n try {\n const results = [];\n for (const plugins of pluginPasses) {\n for (const plugin of plugins) {\n const { parserOverride } = plugin;\n if (parserOverride) {\n const ast = parserOverride(code, parserOpts, parse);\n\n if (ast !== undefined) results.push(ast);\n }\n }\n }\n\n if (results.length === 0) {\n return parse(code, parserOpts);\n } else if (results.length === 1) {\n // If we want to allow async parsers\n yield* [];\n if (typeof (results[0] as any).then === \"function\") {\n throw new Error(\n `You appear to be using an async parser plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, you may need to upgrade ` +\n `your @babel/core version.`,\n );\n }\n return results[0];\n }\n // TODO: Add an error code\n throw new Error(\"More than one plugin attempted to override parsing.\");\n } catch (err) {\n if (err.code === \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\") {\n err.message +=\n \"\\nConsider renaming the file to '.mjs', or setting sourceType:module \" +\n \"or sourceType:unambiguous in your Babel config for this file.\";\n // err.code will be changed to BABEL_PARSE_ERROR later.\n }\n\n const { loc, missingPlugin } = err;\n if (loc) {\n const codeFrame = codeFrameColumns(\n code,\n {\n start: {\n line: loc.line,\n column: loc.column + 1,\n },\n },\n {\n highlightCode,\n },\n );\n if (missingPlugin) {\n err.message =\n `${filename}: ` +\n generateMissingPluginMessage(\n missingPlugin[0],\n loc,\n codeFrame,\n filename,\n );\n } else {\n err.message = `${filename}: ${err.message}\\n\\n` + codeFrame;\n }\n err.code = \"BABEL_PARSE_ERROR\";\n }\n throw err;\n }\n}\n"],"mappings":"AACA,SAASA,KAAK,QAA0B,eAAe;AACvD,SAASC,gBAAgB,QAAQ,mBAAmB;AACpD,OAAOC,4BAA4B,MAAM,iCAAiC;AAM1E,eAAe,UAAUC,MAAMA,CAC7BC,YAA0B,EAC1B;EAAEC,UAAU;EAAEC,aAAa,GAAG,IAAI;EAAEC,QA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AM,GAAG;QACvB;MACF,CAAC,EACD;QACEpB;MACF,CACF,CAAC;MACD,IAAIgB,aAAa,EAAE;QACjBH,GAAG,CAACC,OAAO,GACT,GAAGb,QAAQ,IAAI,GACfL,4BAA4B,CAC1BoB,aAAa,CAAC,CAAC,CAAC,EAChBD,GAAG,EACHE,SAAS,EACThB,QACF,CAAC;MACL,CAAC,MAAM;QACLY,GAAG,CAACC,OAAO,GAAG,GAAGb,QAAQ,KAAKY,GAAG,CAACC,OAAO,MAAM,GAAGG,SAAS;MAC7D;MACAJ,GAAG,CAACX,IAAI,GAAG,mBAAmB;IAChC;IACA,MAAMW,GAAG;EACX;AACF","ignoreList":[]} |
| const pluginNameMap = { | ||
| asyncDoExpressions: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-async-do-expressions", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-do-expressions" | ||
| } | ||
| }, | ||
| decimal: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-decimal", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decimal" | ||
| } | ||
| }, | ||
| decorators: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-decorators", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decorators" | ||
| }, | ||
| transform: { | ||
| name: "@babel/plugin-proposal-decorators", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-decorators" | ||
| } | ||
| }, | ||
| doExpressions: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-do-expressions", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-do-expressions" | ||
| }, | ||
| transform: { | ||
| name: "@babel/plugin-proposal-do-expressions", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-do-expressions" | ||
| } | ||
| }, | ||
| exportDefaultFrom: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-export-default-from", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-default-from" | ||
| }, | ||
| transform: { | ||
| name: "@babel/plugin-proposal-export-default-from", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-default-from" | ||
| } | ||
| }, | ||
| flow: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-flow", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-flow" | ||
| }, | ||
| transform: { | ||
| name: "@babel/preset-flow", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-preset-flow" | ||
| } | ||
| }, | ||
| functionBind: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-function-bind", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-bind" | ||
| }, | ||
| transform: { | ||
| name: "@babel/plugin-proposal-function-bind", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-bind" | ||
| } | ||
| }, | ||
| functionSent: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-function-sent", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-sent" | ||
| }, | ||
| transform: { | ||
| name: "@babel/plugin-proposal-function-sent", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-sent" | ||
| } | ||
| }, | ||
| jsx: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-jsx", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx" | ||
| }, | ||
| transform: { | ||
| name: "@babel/preset-react", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-preset-react" | ||
| } | ||
| }, | ||
| pipelineOperator: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-pipeline-operator", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-pipeline-operator" | ||
| }, | ||
| transform: { | ||
| name: "@babel/plugin-proposal-pipeline-operator", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-pipeline-operator" | ||
| } | ||
| }, | ||
| recordAndTuple: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-record-and-tuple", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-record-and-tuple" | ||
| } | ||
| }, | ||
| throwExpressions: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-throw-expressions", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-throw-expressions" | ||
| }, | ||
| transform: { | ||
| name: "@babel/plugin-proposal-throw-expressions", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-throw-expressions" | ||
| } | ||
| }, | ||
| typescript: { | ||
| syntax: { | ||
| name: "@babel/plugin-syntax-typescript", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-typescript" | ||
| }, | ||
| transform: { | ||
| name: "@babel/preset-typescript", | ||
| url: "https://github.com/babel/babel/tree/main/packages/babel-preset-typescript" | ||
| } | ||
| } | ||
| }; | ||
| const getNameURLCombination = ({ | ||
| name, | ||
| url | ||
| }) => `${name} (${url})`; | ||
| export default function generateMissingPluginMessage(missingPluginName, loc, codeFrame, filename) { | ||
| let helpMessage = `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` + `(${loc.line}:${loc.column + 1}):\n\n` + codeFrame; | ||
| const pluginInfo = pluginNameMap[missingPluginName]; | ||
| if (pluginInfo) { | ||
| const { | ||
| syntax: syntaxPlugin, | ||
| transform: transformPlugin | ||
| } = pluginInfo; | ||
| if (syntaxPlugin) { | ||
| const syntaxPluginInfo = getNameURLCombination(syntaxPlugin); | ||
| if (transformPlugin) { | ||
| const transformPluginInfo = getNameURLCombination(transformPlugin); | ||
| const sectionType = transformPlugin.name.startsWith("@babel/plugin") ? "plugins" : "presets"; | ||
| helpMessage += `\n\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation. | ||
| If you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`; | ||
| } else { | ||
| helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`; | ||
| } | ||
| } | ||
| } | ||
| const msgFilename = filename === "unknown" ? "<name of the input file>" : filename; | ||
| helpMessage += ` | ||
| If you already added the plugin for this syntax to your config, it's possible that your config \ | ||
| isn't being loaded. | ||
| You can re-run Babel with the BABEL_SHOW_CONFIG_FOR environment variable to show the loaded \ | ||
| configuration: | ||
| \tnpx cross-env BABEL_SHOW_CONFIG_FOR=${msgFilename} <your build command> | ||
| See https://babeljs.io/docs/configuration#print-effective-configs for more info. | ||
| `; | ||
| return helpMessage; | ||
| } | ||
| //# sourceMappingURL=missing-plugin-helper.js.map |
| {"version":3,"names":["pluginNameMap","asyncDoExpressions","syntax","name","url","decimal","decorators","transform","doExpressions","exportDefaultFrom","flow","functionBind","functionSent","jsx","pipelineOperator","recordAndTuple","throwExpressions","typescript","getNameURLCombination","generateMissingPluginMessage","missingPluginName","loc","codeFrame","filename","helpMessage","line","column","pluginInfo","syntaxPlugin","transformPlugin","syntaxPluginInfo","transformPluginInfo","sectionType","startsWith","msgFilename"],"sources":["../../../src/parser/util/missing-plugin-helper.ts"],"sourcesContent":["const pluginNameMap: Record<\n string,\n Partial<Record<\"syntax\" | \"transform\", Record<\"name\" | \"url\", string>>>\n> = {\n asyncDoExpressions: {\n syntax: {\n name: \"@babel/plugin-syntax-async-do-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-do-expressions\",\n },\n },\n decimal: {\n syntax: {\n name: \"@babel/plugin-syntax-decimal\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decimal\",\n },\n },\n decorators: {\n syntax: {\n name: \"@babel/plugin-syntax-decorators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decorators\",\n },\n transform: {\n name: \"@babel/plugin-proposal-decorators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-decorators\",\n },\n },\n doExpressions: {\n syntax: {\n name: \"@babel/plugin-syntax-do-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-do-expressions\",\n },\n transform: {\n name: \"@babel/plugin-proposal-do-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-do-expressions\",\n },\n },\n exportDefaultFrom: {\n syntax: {\n name: \"@babel/plugin-syntax-export-default-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-default-from\",\n },\n transform: {\n name: \"@babel/plugin-proposal-export-default-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-default-from\",\n },\n },\n flow: {\n syntax: {\n name: \"@babel/plugin-syntax-flow\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-flow\",\n },\n transform: {\n name: \"@babel/preset-flow\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-preset-flow\",\n },\n },\n functionBind: {\n syntax: {\n name: \"@babel/plugin-syntax-function-bind\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-bind\",\n },\n transform: {\n name: \"@babel/plugin-proposal-function-bind\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-bind\",\n },\n },\n functionSent: {\n syntax: {\n name: \"@babel/plugin-syntax-function-sent\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-sent\",\n },\n transform: {\n name: \"@babel/plugin-proposal-function-sent\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-sent\",\n },\n },\n jsx: {\n syntax: {\n name: \"@babel/plugin-syntax-jsx\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx\",\n },\n transform: {\n name: \"@babel/preset-react\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-preset-react\",\n },\n },\n pipelineOperator: {\n syntax: {\n name: \"@babel/plugin-syntax-pipeline-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-pipeline-operator\",\n },\n transform: {\n name: \"@babel/plugin-proposal-pipeline-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-pipeline-operator\",\n },\n },\n recordAndTuple: {\n syntax: {\n name: \"@babel/plugin-syntax-record-and-tuple\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-record-and-tuple\",\n },\n },\n throwExpressions: {\n syntax: {\n name: \"@babel/plugin-syntax-throw-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-throw-expressions\",\n },\n transform: {\n name: \"@babel/plugin-proposal-throw-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-throw-expressions\",\n },\n },\n typescript: {\n syntax: {\n name: \"@babel/plugin-syntax-typescript\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-typescript\",\n },\n transform: {\n name: \"@babel/preset-typescript\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-preset-typescript\",\n },\n },\n};\n\nconst getNameURLCombination = ({ name, url }: { name: string; url: string }) =>\n `${name} (${url})`;\n\n/*\nReturns a string of the format:\nSupport for the experimental syntax [@babel/parser plugin name] isn't currently enabled ([loc]):\n\n[code frame]\n\nAdd [npm package name] ([url]) to the 'plugins' section of your Babel config\nto enable [parsing|transformation].\n*/\nexport default function generateMissingPluginMessage(\n missingPluginName: string,\n loc: {\n line: number;\n column: number;\n },\n codeFrame: string,\n filename: string,\n): string {\n let helpMessage =\n `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` +\n `(${loc.line}:${loc.column + 1}):\\n\\n` +\n codeFrame;\n const pluginInfo = pluginNameMap[missingPluginName];\n if (pluginInfo) {\n const { syntax: syntaxPlugin, transform: transformPlugin } = pluginInfo;\n if (syntaxPlugin) {\n const syntaxPluginInfo = getNameURLCombination(syntaxPlugin);\n if (transformPlugin) {\n const transformPluginInfo = getNameURLCombination(transformPlugin);\n const sectionType = transformPlugin.name.startsWith(\"@babel/plugin\")\n ? \"plugins\"\n : \"presets\";\n helpMessage += `\\n\\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation.\nIf you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`;\n } else {\n helpMessage +=\n `\\n\\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` +\n `to enable parsing.`;\n }\n }\n }\n\n const msgFilename =\n filename === \"unknown\" ? \"<name of the input file>\" : filename;\n helpMessage += `\n\nIf you already added the plugin for this syntax to your config, it's possible that your config \\\nisn't being loaded.\nYou can re-run Babel with the BABEL_SHOW_CONFIG_FOR environment variable to show the loaded \\\nconfiguration:\n\\tnpx cross-env BABEL_SHOW_CONFIG_FOR=${msgFilename} <your build command>\nSee https://babeljs.io/docs/configuration#print-effective-configs for more info.\n`;\n return helpMessage;\n}\n"],"mappings":"AAAA,MAAMA,aAGL,GAAG;EACFC,kBAAkB,EAAE;IAClBC,MAAM,EAAE;MACNC,IAAI,EAAE,2CAA2C;MACjDC,GAAG,EAAE;IACP;EACF,CAAC;EACDC,OAAO,EAAE;IACPH,MAAM,EAAE;MACNC,IAAI,EAAE,8BAA8B;MACpCC,GAAG,EAAE;IACP;EACF,CAAC;EACDE,UAAU,EAAE;IACVJ,MAAM,EAAE;MACNC,IAAI,EAAE,iCAAiC;MACvCC,GAAG,EAAE;IACP,CAAC;IACDG,SAAS,EAAE;MACTJ,IAAI,EAAE,mCAAmC;MACzCC,GAAG,EAAE;IACP;EACF,CAAC;EACDI,aAAa,EAAE;IACbN,MAAM,EAAE;MACNC,IAAI,EAAE,qCAAqC;MAC3CC,GAAG,EAAE;IACP,CAAC;IACDG,SAAS,EAAE;MACTJ,IAAI,EAAE,uCAAuC;MAC7CC,GAAG,EAAE;IACP;EACF,CAAC;EACDK,iBAAiB,EAAE;IACjBP,MAAM,EAAE;MACNC,IAAI,EAAE,0CAA0C;MAChDC,GAAG,EAAE;IACP,CAAC;IACDG,SAAS,EAAE;M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AwCU,WAAW;AACnD;AACA,CAAC;EACC,OAAOV,WAAW;AACpB","ignoreList":[]} |
| import * as helpers from "@babel/helpers"; | ||
| import generator from "@babel/generator"; | ||
| import template from "@babel/template"; | ||
| import * as _t from "@babel/types"; | ||
| const { | ||
| arrayExpression, | ||
| assignmentExpression, | ||
| binaryExpression, | ||
| blockStatement, | ||
| callExpression, | ||
| cloneNode, | ||
| conditionalExpression, | ||
| exportNamedDeclaration, | ||
| exportSpecifier, | ||
| expressionStatement, | ||
| functionExpression, | ||
| identifier, | ||
| memberExpression, | ||
| objectExpression, | ||
| program, | ||
| stringLiteral, | ||
| unaryExpression, | ||
| variableDeclaration, | ||
| variableDeclarator | ||
| } = _t; | ||
| const buildUmdWrapper = replacements => template.statement` | ||
| (function (root, factory) { | ||
| if (typeof define === "function" && define.amd) { | ||
| define(AMD_ARGUMENTS, factory); | ||
| } else if (typeof exports === "object") { | ||
| factory(COMMON_ARGUMENTS); | ||
| } else { | ||
| factory(BROWSER_ARGUMENTS); | ||
| } | ||
| })(UMD_ROOT, function (FACTORY_PARAMETERS) { | ||
| FACTORY_BODY | ||
| }); | ||
| `(replacements); | ||
| function buildGlobal(allowlist) { | ||
| const namespace = identifier("babelHelpers"); | ||
| const body = []; | ||
| const container = functionExpression(null, [identifier("global")], blockStatement(body)); | ||
| const tree = program([expressionStatement(callExpression(container, [conditionalExpression(binaryExpression("===", unaryExpression("typeof", identifier("global")), stringLiteral("undefined")), identifier("self"), identifier("global"))]))]); | ||
| body.push(variableDeclaration("var", [variableDeclarator(namespace, assignmentExpression("=", memberExpression(identifier("global"), namespace), objectExpression([])))])); | ||
| buildHelpers(body, namespace, allowlist); | ||
| return tree; | ||
| } | ||
| function buildModule(allowlist) { | ||
| const body = []; | ||
| const refs = buildHelpers(body, null, allowlist); | ||
| body.unshift(exportNamedDeclaration(null, Object.keys(refs).map(name => { | ||
| return exportSpecifier(cloneNode(refs[name]), identifier(name)); | ||
| }))); | ||
| return program(body, [], "module"); | ||
| } | ||
| function buildUmd(allowlist) { | ||
| const namespace = identifier("babelHelpers"); | ||
| const body = []; | ||
| body.push(variableDeclaration("var", [variableDeclarator(namespace, identifier("global"))])); | ||
| buildHelpers(body, namespace, allowlist); | ||
| return program([buildUmdWrapper({ | ||
| FACTORY_PARAMETERS: identifier("global"), | ||
| BROWSER_ARGUMENTS: assignmentExpression("=", memberExpression(identifier("root"), namespace), objectExpression([])), | ||
| COMMON_ARGUMENTS: identifier("exports"), | ||
| AMD_ARGUMENTS: arrayExpression([stringLiteral("exports")]), | ||
| FACTORY_BODY: body, | ||
| UMD_ROOT: identifier("this") | ||
| })]); | ||
| } | ||
| function buildVar(allowlist) { | ||
| const namespace = identifier("babelHelpers"); | ||
| const body = []; | ||
| body.push(variableDeclaration("var", [variableDeclarator(namespace, objectExpression([]))])); | ||
| const tree = program(body); | ||
| buildHelpers(body, namespace, allowlist); | ||
| body.push(expressionStatement(namespace)); | ||
| return tree; | ||
| } | ||
| function buildHelpers(body, namespace, allowlist) { | ||
| const getHelperReference = name => { | ||
| return namespace ? memberExpression(namespace, identifier(name)) : identifier(`_${name}`); | ||
| }; | ||
| const refs = {}; | ||
| helpers.list.forEach(function (name) { | ||
| if (allowlist && !allowlist.includes(name)) return; | ||
| const ref = refs[name] = getHelperReference(name); | ||
| const { | ||
| nodes | ||
| } = helpers.get(name, getHelperReference, namespace ? null : `_${name}`, [], namespace ? (ast, exportName, mapExportBindingAssignments) => { | ||
| mapExportBindingAssignments(node => assignmentExpression("=", ref, node)); | ||
| ast.body.push(expressionStatement(assignmentExpression("=", ref, identifier(exportName)))); | ||
| } : null); | ||
| body.push(...nodes); | ||
| }); | ||
| return refs; | ||
| } | ||
| export default function (allowlist, outputType = "global") { | ||
| let tree; | ||
| const build = { | ||
| global: buildGlobal, | ||
| module: buildModule, | ||
| umd: buildUmd, | ||
| var: buildVar | ||
| }[outputType]; | ||
| if (build) { | ||
| tree = build(allowlist); | ||
| } else { | ||
| throw new Error(`Unsupported output type ${outputType}`); | ||
| } | ||
| return generator(tree).code; | ||
| } | ||
| //# sourceMappingURL=build-external-helpers.js.map |
| {"version":3,"names":["helpers","generator","template","_t","arrayExpression","assignmentExpression","binaryExpression","blockStatement","callExpression","cloneNode","conditionalExpression","exportNamedDeclaration","exportSpecifier","expressionStatement","functionExpression","identifier","memberExpression","objectExpression","program","stringLiteral","unaryExpression","variableDeclaration","variableDeclarator","buildUmdWrapper","replacements","statement","buildGlobal","allowlist","namespace","body","container","tree","push","buildHelpers","buildModule","refs","unshift","Object","keys","map","name","buildUmd","FACTORY_PARAMETERS","BROWSER_ARGUMENTS","COMMON_ARGUMENTS","AMD_ARGUMENTS","FACTORY_BODY","UMD_ROOT","buildVar","getHelperReference","list","forEach","includes","ref","nodes","get","ast","exportName","mapExportBindingAssignments","node","outputType","build","global","module","umd","var","Error","code"],"sources":["../../src/tools/build-external-helpers.ts"],"sourcesContent":["import * as helpers from \"@babel/helpers\";\nimport generator from \"@babel/generator\";\nimport template from \"@babel/template\";\nimport {\n arrayExpression,\n assignmentExpression,\n binaryExpression,\n blockStatement,\n callExpression,\n cloneNode,\n conditionalExpression,\n exportNamedDeclaration,\n exportSpecifier,\n expressionStatement,\n functionExpression,\n identifier,\n memberExpression,\n objectExpression,\n program,\n stringLiteral,\n unaryExpression,\n variableDeclaration,\n variableDeclarator,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport type { Replacements } from \"@babel/template\";\n\n// Wrapped to avoid wasting time parsing this when almost no-one uses\n// build-external-helpers.\nconst buildUmdWrapper = (replacements: Replacements) =>\n template.statement`\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n `(replacements);\n\nfunction buildGlobal(allowlist?: string[]) {\n const namespace = identifier(\"babelHelpers\");\n\n const body: t.Statement[] = [];\n const container = functionExpression(\n null,\n [identifier(\"global\")],\n blockStatement(body),\n );\n const tree = program([\n expressionStatement(\n callExpression(container, [\n // typeof global === \"undefined\" ? self : global\n conditionalExpression(\n binaryExpression(\n \"===\",\n unaryExpression(\"typeof\", identifier(\"global\")),\n stringLiteral(\"undefined\"),\n ),\n identifier(\"self\"),\n identifier(\"global\"),\n ),\n ]),\n ),\n ]);\n\n body.push(\n variableDeclaration(\"var\", [\n variableDeclarator(\n namespace,\n assignmentExpression(\n \"=\",\n memberExpression(identifier(\"global\"), namespace),\n objectExpression([]),\n ),\n ),\n ]),\n );\n\n buildHelpers(body, namespace, allowlist);\n\n return tree;\n}\n\nfunction buildModule(allowlist?: string[]) {\n const body: t.Statement[] = [];\n const refs = buildHelpers(body, null, allowlist);\n\n body.unshift(\n exportNamedDeclaration(\n null,\n Object.keys(refs).map(name => {\n return exportSpecifier(cloneNode(refs[name]), identifier(name));\n }),\n ),\n );\n\n return program(body, [], \"module\");\n}\n\nfunction buildUmd(allowlist?: string[]) {\n const namespace = identifier(\"babelHelpers\");\n\n const body: t.Statement[] = [];\n body.push(\n variableDeclaration(\"var\", [\n variableDeclarator(namespace, identifier(\"global\")),\n ]),\n );\n\n buildHelpers(body, namespace, allowlist);\n\n return program([\n buildUmdWrapper({\n FACTORY_PARAMETERS: identifier(\"global\"),\n BROWSER_ARGUMENTS: assignmentExpression(\n \"=\",\n memberExpression(identifier(\"root\"), namespace),\n objectExpression([]),\n ),\n COMMON_ARGUMENTS: identifier(\"exports\"),\n AMD_ARGUMENTS: arrayExpression([stringLiteral(\"exports\")]),\n FACTORY_BODY: body,\n UMD_ROOT: identifier(\"this\"),\n }),\n ]);\n}\n\nfunction buildVar(allowlist?: string[]) {\n const namespace = identifier(\"babelHelpers\");\n\n const body: t.Statement[] = [];\n body.push(\n variableDeclaration(\"var\", [\n variableDeclarator(namespace, objectExpression([])),\n ]),\n );\n const tree = program(body);\n buildHelpers(body, namespace, allowlist);\n body.push(expressionStatement(namespace));\n return tree;\n}\n\nfunction buildHelpers(\n body: t.Statement[],\n namespace: t.Expression,\n allowlist?: string[],\n): Record<string, t.MemberExpression>;\nfunction buildHelpers(\n body: t.Statement[],\n namespace: null,\n allowlist?: string[],\n): Record<string, t.Identifier>;\n\nfunction buildHelpers(\n body: t.Statement[],\n namespace: t.Expression | null,\n allowlist?: string[],\n) {\n const getHelperReference = (name: string) => {\n return namespace\n ? memberExpression(namespace, identifier(name))\n : identifier(`_${name}`);\n };\n\n const refs: Record<string, t.Identifier | t.MemberExpression> = {};\n helpers.list.forEach(function (name) {\n if (allowlist && !allowlist.includes(name)) return;\n\n const ref = (refs[name] = getHelperReference(name));\n\n const { nodes } = helpers.get(\n name,\n getHelperReference,\n namespace ? null : `_${name}`,\n [],\n namespace\n ? (ast, exportName, mapExportBindingAssignments) => {\n mapExportBindingAssignments(node =>\n assignmentExpression(\"=\", ref, node),\n );\n ast.body.push(\n expressionStatement(\n assignmentExpression(\"=\", ref, identifier(exportName)),\n ),\n );\n }\n : null,\n );\n\n body.push(...nodes);\n });\n return refs;\n}\nexport default function (\n allowlist?: string[],\n outputType: \"global\" | \"module\" | \"umd\" | \"var\" = \"global\",\n) {\n let tree: t.Program;\n\n const build = {\n global: buildGlobal,\n module: buildModule,\n umd: buildUmd,\n var: buildVar,\n }[outputType];\n\n if (build) {\n tree = build(allowlist);\n } else {\n throw new Error(`Unsupported output type ${outputType}`);\n }\n\n return generator(tree).code;\n}\n"],"mappings":"AAAA,OAAO,KAAKA,OAAO,MAAM,gBAAgB;AACzC,OAAOC,SAAS,MAAM,kBAAkB;AACxC,OAAOC,QAAQ,MAAM,iBAAiB;AACtC,YAAAC,EAAA,MAoBO,cAAc;AAAC;EAnBpBC,eAAe;EACfC,oBAAoB;EACpBC,gBAAgB;EAChBC,cAAc;EACdC,cAAc;EACdC,SAAS;EACTC,qBAAqB;EACrBC,sBAAsB;EACtBC,eAAe;EACfC,mBAAmB;EACnBC,k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CAACC,IAAI,IAC9BtD,oBAAoB,CAAC,GAAG,EAAEgD,GAAG,EAAEM,IAAI,CACrC,CAAC;MACDH,GAAG,CAAC3B,IAAI,CAACG,IAAI,CACXnB,mBAAmB,CACjBR,oBAAoB,CAAC,GAAG,EAAEgD,GAAG,EAAEtC,UAAU,CAAC0C,UAAU,CAAC,CACvD,CACF,CAAC;IACH,CAAC,GACD,IACN,CAAC;IAED5B,IAAI,CAACG,IAAI,CAAC,GAAGsB,KAAK,CAAC;EACrB,CAAC,CAAC;EACF,OAAOnB,IAAI;AACb;AACA,eAAe,UACbR,SAAoB,EACpBiC,UAA+C,GAAG,QAAQ,EAC1D;EACA,IAAI7B,IAAe;EAEnB,MAAM8B,KAAK,GAAG;IACZC,MAAM,EAAEpC,WAAW;IACnBqC,MAAM,EAAE7B,WAAW;IACnB8B,GAAG,EAAEvB,QAAQ;IACbwB,GAAG,EAAEjB;EACP,CAAC,CAACY,UAAU,CAAC;EAEb,IAAIC,KAAK,EAAE;IACT9B,IAAI,GAAG8B,KAAK,CAAClC,SAAS,CAAC;EACzB,CAAC,MAAM;IACL,MAAM,IAAIuC,KAAK,CAAC,2BAA2BN,UAAU,EAAE,CAAC;EAC1D;EAEA,OAAO3D,SAAS,CAAC8B,IAAI,CAAC,CAACoC,IAAI;AAC7B","ignoreList":[]} |
| import gensync from "gensync"; | ||
| import loadConfig from "./config/index.js"; | ||
| import { run } from "./transformation/index.js"; | ||
| import { beginHiddenCallStack } from "./errors/rewrite-stack-trace.js"; | ||
| const transformFromAstRunner = gensync(function* (ast, code, opts) { | ||
| const config = yield* loadConfig(opts); | ||
| if (config === null) return null; | ||
| if (!ast) throw new Error("No AST given"); | ||
| return yield* run(config, code, ast); | ||
| }); | ||
| export const transformFromAst = function transformFromAst(ast, code, optsOrCallback, maybeCallback) { | ||
| let opts; | ||
| let callback; | ||
| if (typeof optsOrCallback === "function") { | ||
| callback = optsOrCallback; | ||
| opts = undefined; | ||
| } else { | ||
| opts = optsOrCallback; | ||
| callback = maybeCallback; | ||
| } | ||
| if (callback === undefined) { | ||
| throw new Error("Starting from Babel 8.0.0, the 'transformFromAst' function expects a callback. If you need to call it synchronously, please use 'transformFromAstSync'."); | ||
| } | ||
| beginHiddenCallStack(transformFromAstRunner.errback)(ast, code, opts, callback); | ||
| }; | ||
| export function transformFromAstSync(...args) { | ||
| return beginHiddenCallStack(transformFromAstRunner.sync)(...args); | ||
| } | ||
| export function transformFromAstAsync(...args) { | ||
| return beginHiddenCallStack(transformFromAstRunner.async)(...args); | ||
| } | ||
| //# sourceMappingURL=transform-ast.js.map |
| {"version":3,"names":["gensync","loadConfig","run","beginHiddenCallStack","transformFromAstRunner","ast","code","opts","config","Error","transformFromAst","optsOrCallback","maybeCallback","callback","undefined","errback","transformFromAstSync","args","sync","transformFromAstAsync","async"],"sources":["../src/transform-ast.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config/index.ts\";\nimport type { InputOptions, ResolvedConfig } from \"./config/index.ts\";\nimport { run } from \"./transformation/index.ts\";\nimport type * as t from \"@babel/types\";\n\nimport { beginHiddenCallStack } from \"./errors/rewrite-stack-trace.ts\";\n\nimport type { FileResult, FileResultCallback } from \"./transformation/index.ts\";\ntype AstRoot = t.File | t.Program;\n\ntype TransformFromAst = {\n (ast: AstRoot, code: string, callback: FileResultCallback): void;\n (\n ast: AstRoot,\n code: string,\n opts: InputOptions | undefined | null,\n callback: FileResultCallback,\n ): void;\n};\n\nconst transformFromAstRunner = gensync(function* (\n ast: AstRoot,\n code: string,\n opts: InputOptions | undefined | null,\n): Handler<FileResult | null> {\n const config: ResolvedConfig | null = yield* loadConfig(opts);\n if (config === null) return null;\n\n if (!ast) throw new Error(\"No AST given\");\n\n return yield* run(config, code, ast);\n});\n\nexport const transformFromAst: TransformFromAst = function transformFromAst(\n ast,\n code,\n optsOrCallback?: InputOptions | null | undefined | FileResultCallback,\n maybeCallback?: FileResultCallback,\n) {\n let opts: InputOptions | undefined | null;\n let callback: FileResultCallback | undefined;\n if (typeof optsOrCallback === \"function\") {\n callback = optsOrCallback;\n opts = undefined;\n } else {\n opts = optsOrCallback;\n callback = maybeCallback;\n }\n\n if (callback === undefined) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'transformFromAst' function expects a callback. If you need to call it synchronously, please use 'transformFromAstSync'.\",\n );\n }\n\n beginHiddenCallStack(transformFromAstRunner.errback)(\n ast,\n code,\n opts,\n callback,\n );\n};\n\nexport function transformFromAstSync(\n ...args: Parameters<typeof transformFromAstRunner.sync>\n) {\n return beginHiddenCallStack(transformFromAstRunner.sync)(...args);\n}\n\nexport function transformFromAstAsync(\n ...args: Parameters<typeof transformFromAstRunner.async>\n) {\n return beginHiddenCallStack(transformFromAstRunner.async)(...args);\n}\n"],"mappings":"AAAA,OAAOA,OAAO,MAAwB,SAAS;AAE/C,OAAOC,UAAU,MAAM,mBAAmB;AAE1C,SAASC,GAAG,QAAQ,2BAA2B;AAG/C,SAASC,oBAAoB,QAAQ,iCAAiC;AAetE,MAAMC,sBAAsB,GAAGJ,OAAO,CAAC,WACrCK,GAAY,EACZC,IAAY,EACZC,IAAqC,EACT;EAC5B,MAAMC,MAA6B,GAAG,OAAOP,UAAU,CAACM,IAAI,CAAC;EAC7D,IAAIC,MAAM,KAAK,IAAI,EAAE,OAAO,IAAI;EAEhC,IAAI,CAACH,GAAG,EAAE,MAAM,IAAII,KAAK,CAAC,cAAc,CAAC;EAEzC,OAAO,OAAOP,GAAG,CAACM,MAAM,EAAEF,IAAI,EAAED,GAAG,CAAC;AACtC,CAAC,CAAC;AAEF,OAAO,MAAMK,gBAAkC,GAAG,SAASA,gBAAgBA,CACzEL,GAAG,EACHC,IAAI,EACJK,cAAqE,EACrEC,aAAkC,EAClC;EACA,IAAIL,IAAqC;EACzC,IAAIM,QAAwC;EAC5C,IAAI,OAAOF,cAAc,KAAK,UAAU,EAAE;IACxCE,QAAQ,GAAGF,cAAc;IACzBJ,IAAI,GAAGO,SAAS;EAClB,CAAC,MAAM;IACLP,IAAI,GAAGI,cAAc;IACrBE,QAAQ,GAAGD,aAAa;EAC1B;EAEA,IAAIC,QAAQ,KAAKC,SAAS,EAAE;IAC1B,MAAM,IAAIL,KAAK,CACb,yJACF,CAAC;EACH;EAEAN,oBAAoB,CAACC,sBAAsB,CAACW,OAAO,CAAC,CAClDV,GAAG,EACHC,IAAI,EACJC,IAAI,EACJM,QACF,CAAC;AACH,CAAC;AAED,OAAO,SAASG,oBAAoBA,CAClC,GAAGC,IAAoD,EACvD;EACA,OAAOd,oBAAoB,CAACC,sBAAsB,CAACc,IAAI,CAAC,CAAC,GAAGD,IAAI,CAAC;AACnE;AAEA,OAAO,SAASE,qBAAqBA,CACnC,GAAGF,IAAqD,EACxD;EACA,OAAOd,oBAAoB,CAACC,sBAAsB,CAACgB,KAAK,CAAC,CAAC,GAAGH,IAAI,CAAC;AACpE","ignoreList":[]} |
| import gensync from "gensync"; | ||
| import loadConfig from "./config/index.js"; | ||
| import { run } from "./transformation/index.js"; | ||
| import { beginHiddenCallStack } from "./errors/rewrite-stack-trace.js"; | ||
| const transformRunner = gensync(function* transform(code, opts) { | ||
| const config = yield* loadConfig(opts); | ||
| if (config === null) return null; | ||
| return yield* run(config, code); | ||
| }); | ||
| export const transform = function transform(code, optsOrCallback, maybeCallback) { | ||
| let opts; | ||
| let callback; | ||
| if (typeof optsOrCallback === "function") { | ||
| callback = optsOrCallback; | ||
| opts = undefined; | ||
| } else { | ||
| opts = optsOrCallback; | ||
| callback = maybeCallback; | ||
| } | ||
| if (callback === undefined) { | ||
| throw new Error("Starting from Babel 8.0.0, the 'transform' function expects a callback. If you need to call it synchronously, please use 'transformSync'."); | ||
| } | ||
| beginHiddenCallStack(transformRunner.errback)(code, opts, callback); | ||
| }; | ||
| export function transformSync(...args) { | ||
| return beginHiddenCallStack(transformRunner.sync)(...args); | ||
| } | ||
| export function transformAsync(...args) { | ||
| return beginHiddenCallStack(transformRunner.async)(...args); | ||
| } | ||
| //# sourceMappingURL=transform.js.map |
| {"version":3,"names":["gensync","loadConfig","run","beginHiddenCallStack","transformRunner","transform","code","opts","config","optsOrCallback","maybeCallback","callback","undefined","Error","errback","transformSync","args","sync","transformAsync","async"],"sources":["../src/transform.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config/index.ts\";\nimport type { InputOptions, ResolvedConfig } from \"./config/index.ts\";\nimport { run } from \"./transformation/index.ts\";\n\nimport type { FileResult, FileResultCallback } from \"./transformation/index.ts\";\nimport { beginHiddenCallStack } from \"./errors/rewrite-stack-trace.ts\";\n\nexport type { FileResult } from \"./transformation/index.ts\";\n\ntype Transform = {\n (code: string, callback: FileResultCallback): void;\n (\n code: string,\n opts: InputOptions | undefined | null,\n callback: FileResultCallback,\n ): void;\n};\n\nconst transformRunner = gensync(function* transform(\n code: string,\n opts?: InputOptions,\n): Handler<FileResult | null> {\n const config: ResolvedConfig | null = yield* loadConfig(opts);\n if (config === null) return null;\n\n return yield* run(config, code);\n});\n\nexport const transform: Transform = function transform(\n code,\n optsOrCallback?: InputOptions | null | undefined | FileResultCallback,\n maybeCallback?: FileResultCallback,\n) {\n let opts: InputOptions | undefined | null;\n let callback: FileResultCallback | undefined;\n if (typeof optsOrCallback === \"function\") {\n callback = optsOrCallback;\n opts = undefined;\n } else {\n opts = optsOrCallback;\n callback = maybeCallback;\n }\n\n if (callback === undefined) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'transform' function expects a callback. If you need to call it synchronously, please use 'transformSync'.\",\n );\n }\n\n beginHiddenCallStack(transformRunner.errback)(code, opts, callback);\n};\n\nexport function transformSync(\n ...args: Parameters<typeof transformRunner.sync>\n) {\n return beginHiddenCallStack(transformRunner.sync)(...args);\n}\nexport function transformAsync(\n ...args: Parameters<typeof transformRunner.async>\n) {\n return beginHiddenCallStack(transformRunner.async)(...args);\n}\n"],"mappings":"AAAA,OAAOA,OAAO,MAAwB,SAAS;AAE/C,OAAOC,UAAU,MAAM,mBAAmB;AAE1C,SAASC,GAAG,QAAQ,2BAA2B;AAG/C,SAASC,oBAAoB,QAAQ,iCAAiC;AAatE,MAAMC,eAAe,GAAGJ,OAAO,CAAC,UAAUK,SAASA,CACjDC,IAAY,EACZC,IAAmB,EACS;EAC5B,MAAMC,MAA6B,GAAG,OAAOP,UAAU,CAACM,IAAI,CAAC;EAC7D,IAAIC,MAAM,KAAK,IAAI,EAAE,OAAO,IAAI;EAEhC,OAAO,OAAON,GAAG,CAACM,MAAM,EAAEF,IAAI,CAAC;AACjC,CAAC,CAAC;AAEF,OAAO,MAAMD,SAAoB,GAAG,SAASA,SAASA,CACpDC,IAAI,EACJG,cAAqE,EACrEC,aAAkC,EAClC;EACA,IAAIH,IAAqC;EACzC,IAAII,QAAwC;EAC5C,IAAI,OAAOF,cAAc,KAAK,UAAU,EAAE;IACxCE,QAAQ,GAAGF,cAAc;IACzBF,IAAI,GAAGK,SAAS;EAClB,CAAC,MAAM;IACLL,IAAI,GAAGE,cAAc;IACrBE,QAAQ,GAAGD,aAAa;EAC1B;EAEA,IAAIC,QAAQ,KAAKC,SAAS,EAAE;IAC1B,MAAM,IAAIC,KAAK,CACb,2IACF,CAAC;EACH;EAEAV,oBAAoB,CAACC,eAAe,CAACU,OAAO,CAAC,CAACR,IAAI,EAAEC,IAAI,EAAEI,QAAQ,CAAC;AACrE,CAAC;AAED,OAAO,SAASI,aAAaA,CAC3B,GAAGC,IAA6C,EAChD;EACA,OAAOb,oBAAoB,CAACC,eAAe,CAACa,IAAI,CAAC,CAAC,GAAGD,IAAI,CAAC;AAC5D;AACA,OAAO,SAASE,cAAcA,CAC5B,GAAGF,IAA8C,EACjD;EACA,OAAOb,oBAAoB,CAACC,eAAe,CAACe,KAAK,CAAC,CAAC,GAAGH,IAAI,CAAC;AAC7D","ignoreList":[]} |
| import traverse from "@babel/traverse"; | ||
| import Plugin from "../config/plugin.js"; | ||
| let LOADED_PLUGIN; | ||
| const blockHoistPlugin = { | ||
| name: "internal.blockHoist", | ||
| visitor: { | ||
| Block: { | ||
| exit({ | ||
| node | ||
| }) { | ||
| node.body = performHoisting(node.body); | ||
| } | ||
| }, | ||
| SwitchCase: { | ||
| exit({ | ||
| node | ||
| }) { | ||
| node.consequent = performHoisting(node.consequent); | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| function performHoisting(body) { | ||
| let max = 2 ** 30 - 1; | ||
| let hasChange = false; | ||
| for (let i = 0; i < body.length; i++) { | ||
| const n = body[i]; | ||
| const p = priority(n); | ||
| if (p > max) { | ||
| hasChange = true; | ||
| break; | ||
| } | ||
| max = p; | ||
| } | ||
| if (!hasChange) return body; | ||
| return stableSort(body.slice()); | ||
| } | ||
| export default function loadBlockHoistPlugin() { | ||
| if (!LOADED_PLUGIN) { | ||
| LOADED_PLUGIN = new Plugin({ | ||
| ...blockHoistPlugin, | ||
| visitor: traverse.explode(blockHoistPlugin.visitor) | ||
| }, {}); | ||
| } | ||
| return LOADED_PLUGIN; | ||
| } | ||
| function priority(bodyNode) { | ||
| const priority = bodyNode?._blockHoist; | ||
| if (priority == null) return 1; | ||
| if (priority === true) return 2; | ||
| return priority; | ||
| } | ||
| function stableSort(body) { | ||
| const buckets = Object.create(null); | ||
| for (let i = 0; i < body.length; i++) { | ||
| const n = body[i]; | ||
| const p = priority(n); | ||
| const bucket = buckets[p] || (buckets[p] = []); | ||
| bucket.push(n); | ||
| } | ||
| const keys = Object.keys(buckets).map(k => +k).sort((a, b) => b - a); | ||
| let index = 0; | ||
| for (const key of keys) { | ||
| const bucket = buckets[key]; | ||
| for (const n of bucket) { | ||
| body[index++] = n; | ||
| } | ||
| } | ||
| return body; | ||
| } | ||
| //# sourceMappingURL=block-hoist-plugin.js.map |
| {"version":3,"names":["traverse","Plugin","LOADED_PLUGIN","blockHoistPlugin","name","visitor","Block","exit","node","body","performHoisting","SwitchCase","consequent","max","hasChange","i","length","n","p","priority","stableSort","slice","loadBlockHoistPlugin","explode","bodyNode","_blockHoist","buckets","Object","create","bucket","push","keys","map","k","sort","a","b","index","key"],"sources":["../../src/transformation/block-hoist-plugin.ts"],"sourcesContent":["import traverse from \"@babel/traverse\";\nimport type { Statement } from \"@babel/types\";\nimport type { PluginObject } from \"../config/index.ts\";\nimport Plugin from \"../config/plugin.ts\";\n\nlet LOADED_PLUGIN: Plugin | void;\n\nconst blockHoistPlugin: PluginObject = {\n /**\n * [Please add a description.]\n *\n * Priority:\n *\n * - 0 We want this to be at the **very** bottom\n * - 1 Default node position\n * - 2 Priority over normal nodes\n * - 3 We want this to be at the **very** top\n * - 4 Reserved for the helpers used to implement module imports.\n */\n\n name: \"internal.blockHoist\",\n\n visitor: {\n Block: {\n exit({ node }) {\n node.body = performHoisting(node.body);\n },\n },\n SwitchCase: {\n exit({ node }) {\n // In case statements, hoisting is difficult to perform correctly due to\n // functions that are declared and referenced in different blocks.\n // Nevertheless, hoisting the statements *inside* of each case should at\n // least mitigate the failure cases.\n node.consequent = performHoisting(node.consequent);\n },\n },\n },\n};\n\nfunction performHoisting(body: Statement[]): Statement[] {\n // Largest SMI\n let max = 2 ** 30 - 1;\n let hasChange = false;\n for (let i = 0; i < body.length; i++) {\n const n = body[i];\n const p = priority(n);\n if (p > max) {\n hasChange = true;\n break;\n }\n max = p;\n }\n if (!hasChange) return body;\n\n // My kingdom for a stable sort!\n return stableSort(body.slice());\n}\n\nexport default function loadBlockHoistPlugin(): Plugin {\n if (!LOADED_PLUGIN) {\n // cache the loaded blockHoist plugin plugin\n LOADED_PLUGIN = new Plugin(\n {\n ...blockHoistPlugin,\n visitor: traverse.explode(blockHoistPlugin.visitor),\n },\n {},\n );\n }\n\n return LOADED_PLUGIN;\n}\n\nfunction priority(bodyNode: Statement & { _blockHoist?: number | true }) {\n const priority = bodyNode?._blockHoist;\n if (priority == null) return 1;\n if (priority === true) return 2;\n return priority;\n}\n\nfunction stableSort(body: Statement[]) {\n // By default, we use priorities of 0-4.\n const buckets = Object.create(null);\n\n // By collecting into buckets, we can guarantee a stable sort.\n for (let i = 0; i < body.length; i++) {\n const n = body[i];\n const p = priority(n);\n\n // In case some plugin is setting an unexpected priority.\n const bucket = buckets[p] || (buckets[p] = []);\n bucket.push(n);\n }\n\n // Sort our keys in descending order. Keys are unique, so we don't have to\n // worry about stability.\n const keys = Object.keys(buckets)\n .map(k => +k)\n .sort((a, b) => b - a);\n\n let index = 0;\n for (const key of keys) {\n const bucket = buckets[key];\n for (const n of bucket) {\n body[index++] = n;\n }\n }\n return body;\n}\n"],"mappings":"AAAA,OAAOA,QAAQ,MAAM,iBAAiB;AAGtC,OAAOC,MAAM,MAAM,qBAAqB;AAExC,IAAIC,aAA4B;AAEhC,MAAMC,gBAA8B,GAAG;EAarCC,IAAI,EAAE,qBAAqB;EAE3BC,OAAO,EAAE;IACPC,KAAK,EAAE;MACLC,IAAIA,CAAC;QAAEC;MAAK,CAAC,EAAE;QACbA,IAAI,CAACC,IAAI,GAAGC,eAAe,CAACF,IAAI,CAACC,IAAI,CAAC;MACxC;IACF,CAAC;IACDE,UAAU,EAAE;MACVJ,IAAIA,CAAC;QAAEC;MAAK,CAAC,EAAE;QAKbA,IAAI,CAACI,UAAU,GAAGF,eAAe,CAACF,IAAI,CAACI,UAAU,CAAC;MACpD;IACF;EACF;AACF,CAAC;AAED,SAASF,eAAeA,CAACD,IAAiB,EAAe;EAEvD,IAAII,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC;EACrB,IAAIC,SAAS,GAAG,KAAK;EACrB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGN,IAAI,CAACO,MAAM,EAAED,CAAC,EAAE,EAAE;IACpC,MAAME,CAAC,GAAGR,IAAI,CAACM,CAAC,CAAC;IACjB,MAAMG,CAAC,GAAGC,QAAQ,CAACF,CAAC,CAAC;IACrB,IAAIC,CAAC,GAAGL,GAAG,EAAE;MACXC,SAAS,GAAG,IAAI;MAChB;IACF;IACAD,GAAG,GAAGK,CAAC;EACT;EACA,IAAI,CAACJ,SAAS,EAAE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,CAAC;EACb,KAAK,MAAMC,GAAG,IAAIP,IAAI,EAAE;IACtB,MAAMF,MAAM,GAAGH,OAAO,CAACY,GAAG,CAAC;IAC3B,KAAK,MAAMrB,CAAC,IAAIY,MAAM,EAAE;MACtBpB,IAAI,CAAC4B,KAAK,EAAE,CAAC,GAAGpB,CAAC;IACnB;EACF;EACA,OAAOR,IAAI;AACb","ignoreList":[]} |
| import * as helpers from "@babel/helpers"; | ||
| import { NodePath } from "@babel/traverse"; | ||
| import { codeFrameColumns } from "@babel/code-frame"; | ||
| import * as _t from "@babel/types"; | ||
| const { | ||
| cloneNode, | ||
| interpreterDirective, | ||
| traverseFast | ||
| } = _t; | ||
| import semver from "semver"; | ||
| export default class File { | ||
| _map = new Map(); | ||
| opts; | ||
| declarations = {}; | ||
| path; | ||
| ast; | ||
| scope; | ||
| metadata = {}; | ||
| code = ""; | ||
| inputMap; | ||
| hub = { | ||
| file: this, | ||
| getCode: () => this.code, | ||
| getScope: () => this.scope, | ||
| addHelper: this.addHelper.bind(this), | ||
| buildError: this.buildCodeFrameError.bind(this) | ||
| }; | ||
| constructor(options, { | ||
| code, | ||
| ast, | ||
| inputMap | ||
| }) { | ||
| this.opts = options; | ||
| this.code = code; | ||
| this.ast = ast; | ||
| this.inputMap = inputMap; | ||
| this.path = NodePath.get({ | ||
| hub: this.hub, | ||
| parentPath: null, | ||
| parent: this.ast, | ||
| container: this.ast, | ||
| key: "program" | ||
| }).setContext(); | ||
| this.scope = this.path.scope; | ||
| } | ||
| get shebang() { | ||
| const { | ||
| interpreter | ||
| } = this.path.node; | ||
| return interpreter ? interpreter.value : ""; | ||
| } | ||
| set shebang(value) { | ||
| if (value) { | ||
| this.path.get("interpreter").replaceWith(interpreterDirective(value)); | ||
| } else { | ||
| this.path.get("interpreter").remove(); | ||
| } | ||
| } | ||
| set(key, val) { | ||
| this._map.set(key, val); | ||
| } | ||
| get(key) { | ||
| return this._map.get(key); | ||
| } | ||
| has(key) { | ||
| return this._map.has(key); | ||
| } | ||
| availableHelper(name, versionRange) { | ||
| if (helpers.isInternal(name)) return false; | ||
| let minVersion; | ||
| try { | ||
| minVersion = helpers.minVersion(name); | ||
| } catch (err) { | ||
| if (err.code !== "BABEL_HELPER_UNKNOWN") throw err; | ||
| return false; | ||
| } | ||
| if (typeof versionRange !== "string") return true; | ||
| if (semver.valid(versionRange)) versionRange = `^${versionRange}`; | ||
| return !semver.intersects(`<${minVersion}`, versionRange) && !semver.intersects(`>=9.0.0`, versionRange); | ||
| } | ||
| addHelper(name) { | ||
| if (helpers.isInternal(name)) { | ||
| throw new Error("Cannot use internal helper " + name); | ||
| } | ||
| return this._addHelper(name); | ||
| } | ||
| _addHelper(name) { | ||
| const declar = this.declarations[name]; | ||
| if (declar) return cloneNode(declar); | ||
| const generator = this.get("helperGenerator"); | ||
| if (generator) { | ||
| const res = generator(name); | ||
| if (res) return res; | ||
| } | ||
| helpers.minVersion(name); | ||
| const uid = this.declarations[name] = this.scope.generateUidIdentifier(name); | ||
| const dependencies = {}; | ||
| for (const dep of helpers.getDependencies(name)) { | ||
| dependencies[dep] = this._addHelper(dep); | ||
| } | ||
| const { | ||
| nodes, | ||
| globals | ||
| } = helpers.get(name, dep => dependencies[dep], uid.name, Object.keys(this.scope.getAllBindings())); | ||
| globals.forEach(name => { | ||
| if (this.path.scope.hasBinding(name, true)) { | ||
| this.path.scope.rename(name); | ||
| } | ||
| }); | ||
| nodes.forEach(node => { | ||
| node._compact = true; | ||
| }); | ||
| const added = this.path.unshiftContainer("body", nodes); | ||
| for (const path of added) { | ||
| if (path.isVariableDeclaration()) this.scope.registerDeclaration(path); | ||
| } | ||
| return uid; | ||
| } | ||
| buildCodeFrameError(node, msg, _Error = SyntaxError) { | ||
| let loc = node?.loc; | ||
| if (!loc && node) { | ||
| traverseFast(node, function (node) { | ||
| if (node.loc) { | ||
| loc = node.loc; | ||
| return traverseFast.stop; | ||
| } | ||
| }); | ||
| let txt = "This is an error on an internal node. Probably an internal error."; | ||
| if (loc) txt += " Location has been estimated."; | ||
| msg += ` (${txt})`; | ||
| } | ||
| if (loc) { | ||
| const { | ||
| highlightCode = true | ||
| } = this.opts; | ||
| msg += "\n" + codeFrameColumns(this.code, { | ||
| start: { | ||
| line: loc.start.line, | ||
| column: loc.start.column + 1 | ||
| }, | ||
| end: loc.end && loc.start.line === loc.end.line ? { | ||
| line: loc.end.line, | ||
| column: loc.end.column + 1 | ||
| } : undefined | ||
| }, { | ||
| highlightCode | ||
| }); | ||
| } | ||
| return new _Error(msg); | ||
| } | ||
| } | ||
| //# sourceMappingURL=file.js.map |
| {"version":3,"names":["helpers","NodePath","codeFrameColumns","_t","cloneNode","interpreterDirective","traverseFast","semver","File","_map","Map","opts","declarations","path","ast","scope","metadata","code","inputMap","hub","file","getCode","getScope","addHelper","bind","buildError","buildCodeFrameError","constructor","options","get","parentPath","parent","container","key","setContext","shebang","interpreter","node","value","replaceWith","remove","set","val","has","availableHelper","name","versionRange","isInternal","minVersion","err","valid","intersects","Error","_addHelper","declar","generator","res","uid","generateUidIdentifier","dependencies","dep","getDependencies","nodes","globals","Object","keys","getAllBindings","forEach","hasBinding","rename","_compact","added","unshiftContainer","isVariableDeclaration","registerDeclaration","msg","_Error","SyntaxError","loc","stop","txt","highlightCode","start","line","column","end","undefined"],"sources":["../../../src/transformation/file/file.ts"],"sourcesContent":["import * as helpers from \"@babel/helpers\";\nimport { NodePath } from \"@babel/traverse\";\nimport type { HubInterface, Scope } from \"@babel/traverse\";\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport { cloneNode, interpreterDirective, traverseFast } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport semver from \"semver\";\n\nimport type { NormalizedFile } from \"../normalize-file.ts\";\n\nimport type { ResolvedOptions } from \"../../config/validation/options.ts\";\nimport type { SourceMapConverter } from \"convert-source-map\";\n\nexport default class File {\n _map = new Map<unknown, unknown>();\n opts: ResolvedOptions;\n declarations: Record<string, t.Identifier> = {};\n path: NodePath<t.Program>;\n ast: t.File;\n scope: Scope;\n metadata: Record<string, any> = {};\n code: string = \"\";\n inputMap: SourceMapConverter;\n\n hub: HubInterface & { file: File } = {\n // keep it for the usage in babel-core, ex: path.hub.file.opts.filename\n file: this,\n getCode: () => this.code,\n getScope: () => this.scope,\n addHelper: this.addHelper.bind(this),\n buildError: this.buildCodeFrameError.bind(this),\n };\n\n constructor(\n options: ResolvedOptions,\n { code, ast, inputMap }: NormalizedFile,\n ) {\n this.opts = options;\n this.code = code;\n this.ast = ast;\n this.inputMap = inputMap;\n\n this.path = NodePath.get({\n hub: this.hub,\n parentPath: null,\n parent: this.ast,\n container: this.ast,\n key: \"program\",\n }).setContext() as NodePath<t.Program>;\n this.scope = this.path.scope;\n }\n\n /**\n * Provide backward-compatible access to the interpreter directive handling\n * in Babel 6.x. If you are writing a plugin for Babel 7.x or higher, it would be\n * best to use 'program.interpreter' directly.\n */\n get shebang(): string {\n const { interpreter } = this.path.node;\n return interpreter ? interpreter.value : \"\";\n }\n set shebang(value: string) {\n if (value) {\n this.path.get(\"interpreter\").replaceWith(interpreterDirective(value));\n } else {\n this.path.get(\"interpreter\").remove();\n }\n }\n\n set(key: unknown, val: unknown) {\n this._map.set(key, val);\n }\n\n get(key: unknown): any {\n return this._map.get(key);\n }\n\n has(key: unknown): boolean {\n return this._map.has(key);\n }\n\n /**\n * Check if a given helper is available in @babel/core's helper list.\n *\n * This _also_ allows you to pass a Babel version specifically. If the\n * helper exists, but was not available for the full given range, it will be\n * considered unavailable.\n */\n availableHelper(name: string, versionRange?: string | null): boolean {\n if (helpers.isInternal(name)) return false;\n\n let minVersion;\n try {\n minVersion = helpers.minVersion(name);\n } catch (err) {\n if (err.code !== \"BABEL_HELPER_UNKNOWN\") throw err;\n\n return false;\n }\n\n if (typeof versionRange !== \"string\") return true;\n\n // semver.intersects() has some surprising behavior with comparing ranges\n // with pre-release versions. We add '^' to ensure that we are always\n // comparing ranges with ranges, which sidesteps this logic.\n // For example:\n //\n // semver.intersects(`<7.0.1`, \"7.0.0-beta.0\") // false - surprising\n // semver.intersects(`<7.0.1`, \"^7.0.0-beta.0\") // true - expected\n //\n // This is because the first falls back to\n //\n // semver.satisfies(\"7.0.0-beta.0\", `<7.0.1`) // false - surprising\n //\n // and this fails because a prerelease version can only satisfy a range\n // if it is a prerelease within the same major/minor/patch range.\n //\n // Note: If this is found to have issues, please also revisit the logic in\n // transform-runtime's definitions.js file.\n if (semver.valid(versionRange)) versionRange = `^${versionRange}`;\n\n return (\n !semver.intersects(`<${minVersion}`, versionRange) &&\n !semver.intersects(`>=9.0.0`, versionRange)\n );\n }\n\n addHelper(name: string): t.Identifier {\n if (helpers.isInternal(name)) {\n throw new Error(\"Cannot use internal helper \" + name);\n }\n return this._addHelper(name);\n }\n\n _addHelper(name: string): t.Identifier {\n const declar = this.declarations[name];\n if (declar) return cloneNode(declar);\n\n const generator = this.get(\"helperGenerator\");\n if (generator) {\n const res = generator(name);\n if (res) return res;\n }\n\n // make sure that the helper exists\n helpers.minVersion(name);\n\n const uid = (this.declarations[name] =\n this.scope.generateUidIdentifier(name));\n\n const dependencies: Record<string, t.Identifier> = {};\n for (const dep of helpers.getDependencies(name)) {\n dependencies[dep] = this._addHelper(dep);\n }\n\n const { nodes, globals } = helpers.get(\n name,\n dep => dependencies[dep],\n uid.name,\n Object.keys(this.scope.getAllBindings()),\n );\n\n globals.forEach(name => {\n if (this.path.scope.hasBinding(name, true /* noGlobals */)) {\n this.path.scope.rename(name);\n }\n });\n\n nodes.forEach(node => {\n // @ts-expect-error Fixme: document _compact node property\n node._compact = true;\n });\n\n const added = this.path.unshiftContainer(\"body\", nodes);\n // TODO: NodePath#unshiftContainer should automatically register new\n // bindings.\n for (const path of added) {\n if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);\n }\n\n return uid;\n }\n\n buildCodeFrameError(\n node: t.Node | undefined | null,\n msg: string,\n _Error: typeof Error = SyntaxError,\n ): Error {\n let loc = node?.loc;\n\n if (!loc && node) {\n traverseFast(node, function (node) {\n if (node.loc) {\n loc = node.loc;\n return traverseFast.stop;\n }\n });\n\n let txt =\n \"This is an error on an internal node. Probably an internal error.\";\n if (loc) txt += \" Location has been estimated.\";\n\n msg += ` (${txt})`;\n }\n\n if (loc) {\n const { highlightCode = true } = this.opts;\n\n msg +=\n \"\\n\" +\n codeFrameColumns(\n this.code,\n {\n start: {\n line: loc.start.line,\n column: loc.start.column + 1,\n },\n end:\n loc.end && loc.start.line === loc.end.line\n ? {\n line: loc.end.line,\n column: loc.end.column + 1,\n }\n : undefined,\n },\n { highlightCode },\n );\n }\n\n return new _Error(msg);\n }\n}\n"],"mappings":"AAAA,OAAO,KAAKA,OAAO,MAAM,gBAAgB;AACzC,SAASC,QAAQ,QAAQ,iBAAiB;AAE1C,SAASC,gBAAgB,QAAQ,mBAAmB;AACpD,YAAAC,EAAA,MAA8D,cAAc;AAAC;EAApEC,SAAS;EAAEC,oBAAoB;EAAEC;AAAY,IAAAH,EAAA;AAEtD,OAAOI,MAAM,MAAM,QAAQ;AAO3B,eAAe,MAAMC,IAAI,CAAC;EACxBC,IAAI,GAAG,IAAIC,GAAG,CAAmB,CAAC;EAClCC,IAAI;EACJC,YAAY,GAAiC,CAAC,CAAC;EAC/CC,IAAI;EACJC,GAAG;EACHC,KAAK;EACLC,QAAQ,GAAwB,CAAC,CAAC;EAClCC,IAAI,GAAW,EAAE;EACjBC,QAAQ;EAERC,GAAG,GAAkC;IAEnCC,IAAI,EAAE,IAAI;IACVC,OAAO,EAAEA,CAAA,KAAM,IAAI,CAACJ,IAAI;IACxBK,QAAQ,EAAEA,CAAA,KAAM,IAAI,CAACP,KAAK;IAC1BQ,SAAS,EAAE,IAAI,CAACA,SAAS,CAACC,IAAI,CAAC,IAAI,CAAC;IACpCC,UAAU,EAAE,IAAI,CAACC,mBAAmB,CAACF,IAAI,CAAC,IAAI;EAChD,CAAC;EAEDG,WAAWA,CACTC,OAAwB,EACxB;IAAEX,IAAI;IAAEH,GAAG;IAAEI;EAAyB,CAAC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O4C,GAAG;EACZ;EAEA/B,mBAAmBA,CACjBW,IAA+B,EAC/BsC,GAAW,EACXC,MAAoB,GAAGC,WAAW,EAC3B;IACP,IAAIC,GAAG,GAAGzC,IAAI,EAAEyC,GAAG;IAEnB,IAAI,CAACA,GAAG,IAAIzC,IAAI,EAAE;MAChB/B,YAAY,CAAC+B,IAAI,EAAE,UAAUA,IAAI,EAAE;QACjC,IAAIA,IAAI,CAACyC,GAAG,EAAE;UACZA,GAAG,GAAGzC,IAAI,CAACyC,GAAG;UACd,OAAOxE,YAAY,CAACyE,IAAI;QAC1B;MACF,CAAC,CAAC;MAEF,IAAIC,GAAG,GACL,mEAAmE;MACrE,IAAIF,GAAG,EAAEE,GAAG,IAAI,+BAA+B;MAE/CL,GAAG,IAAI,KAAKK,GAAG,GAAG;IACpB;IAEA,IAAIF,GAAG,EAAE;MACP,MAAM;QAAEG,aAAa,GAAG;MAAK,CAAC,GAAG,IAAI,CAACtE,IAAI;MAE1CgE,GAAG,IACD,IAAI,GACJzE,gBAAgB,CACd,IAAI,CAACe,IAAI,EACT;QACEiE,KAAK,EAAE;UACLC,IAAI,EAAEL,GAAG,CAACI,KAAK,CAACC,IAAI;UACpBC,MAAM,EAAEN,GAAG,CAACI,KAAK,CAACE,MAAM,GAAG;QAC7B,CAAC;QACDC,GAAG,EACDP,GAAG,CAACO,GAAG,IAAIP,GAAG,CAACI,KAAK,CAACC,IAAI,KAAKL,GAAG,CAACO,GAAG,CAACF,IAAI,GACtC;UACEA,IAAI,EAAEL,GAAG,CAACO,GAAG,CAACF,IAAI;UAClBC,MAAM,EAAEN,GAAG,CAACO,GAAG,CAACD,MAAM,GAAG;QAC3B,CAAC,GACDE;MACR,CAAC,EACD;QAAEL;MAAc,CAClB,CAAC;IACL;IAEA,OAAO,IAAIL,MAAM,CAACD,GAAG,CAAC;EACxB;AACF","ignoreList":[]} |
| import convertSourceMap from "convert-source-map"; | ||
| import generate from "@babel/generator"; | ||
| import mergeSourceMap from "./merge-map.js"; | ||
| export default function generateCode(pluginPasses, file) { | ||
| const { | ||
| opts, | ||
| ast, | ||
| code, | ||
| inputMap | ||
| } = file; | ||
| const { | ||
| generatorOpts | ||
| } = opts; | ||
| generatorOpts.inputSourceMap = inputMap?.toObject(); | ||
| const results = []; | ||
| for (const plugins of pluginPasses) { | ||
| for (const plugin of plugins) { | ||
| const { | ||
| generatorOverride | ||
| } = plugin; | ||
| if (generatorOverride) { | ||
| const result = generatorOverride(ast, generatorOpts, code, generate); | ||
| if (result !== undefined) results.push(result); | ||
| } | ||
| } | ||
| } | ||
| let result; | ||
| if (results.length === 0) { | ||
| result = generate(ast, generatorOpts, code); | ||
| } else if (results.length === 1) { | ||
| result = results[0]; | ||
| if (typeof result.then === "function") { | ||
| throw new Error(`You appear to be using an async codegen plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`); | ||
| } | ||
| } else { | ||
| throw new Error("More than one plugin attempted to override codegen."); | ||
| } | ||
| let { | ||
| code: outputCode, | ||
| decodedMap: outputMap = result.map | ||
| } = result; | ||
| if (result.__mergedMap) { | ||
| outputMap = { | ||
| ...result.map | ||
| }; | ||
| } else { | ||
| if (outputMap) { | ||
| if (inputMap) { | ||
| outputMap = mergeSourceMap(inputMap.toObject(), outputMap, generatorOpts.sourceFileName); | ||
| } else { | ||
| outputMap = result.map; | ||
| } | ||
| } | ||
| } | ||
| if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { | ||
| outputCode += "\n" + convertSourceMap.fromObject(outputMap).toComment(); | ||
| } | ||
| if (opts.sourceMaps === "inline") { | ||
| outputMap = null; | ||
| } | ||
| return { | ||
| outputCode, | ||
| outputMap | ||
| }; | ||
| } | ||
| //# sourceMappingURL=generate.js.map |
| {"version":3,"names":["convertSourceMap","generate","mergeSourceMap","generateCode","pluginPasses","file","opts","ast","code","inputMap","generatorOpts","inputSourceMap","toObject","results","plugins","plugin","generatorOverride","result","undefined","push","length","then","Error","outputCode","decodedMap","outputMap","map","__mergedMap","sourceFileName","sourceMaps","fromObject","toComment"],"sources":["../../../src/transformation/file/generate.ts"],"sourcesContent":["import type { PluginPasses } from \"../../config/index.ts\";\nimport convertSourceMap from \"convert-source-map\";\nimport type { GeneratorResult } from \"@babel/generator\";\nimport generate from \"@babel/generator\";\n\nimport type File from \"./file.ts\";\nimport mergeSourceMap from \"./merge-map.ts\";\n\nexport default function generateCode(\n pluginPasses: PluginPasses,\n file: File,\n): {\n outputCode: string;\n outputMap: GeneratorResult[\"map\"] | null;\n} {\n const { opts, ast, code, inputMap } = file;\n const { generatorOpts } = opts;\n\n generatorOpts.inputSourceMap = inputMap?.toObject();\n\n const results = [];\n for (const plugins of pluginPasses) {\n for (const plugin of plugins) {\n const { generatorOverride } = plugin;\n if (generatorOverride) {\n const result = generatorOverride(ast, generatorOpts, code, generate);\n\n if (result !== undefined) results.push(result);\n }\n }\n }\n\n let result;\n if (results.length === 0) {\n result = generate(ast, generatorOpts, code);\n } else if (results.length === 1) {\n result = results[0];\n\n // @ts-expect-error check if generatorOverride returned a promise\n if (typeof result.then === \"function\") {\n throw new Error(\n `You appear to be using an async codegen plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, ` +\n `you may need to upgrade your @babel/core version.`,\n );\n }\n } else {\n throw new Error(\"More than one plugin attempted to override codegen.\");\n }\n\n // Decoded maps are faster to merge, so we attempt to get use the decodedMap\n // first. But to preserve backwards compat with older Generator, we'll fall\n // back to the encoded map.\n let { code: outputCode, decodedMap: outputMap = result.map } = result;\n\n // @ts-expect-error For backwards compat.\n if (result.__mergedMap) {\n /**\n * @see mergeSourceMap\n */\n outputMap = { ...result.map };\n } else {\n if (outputMap) {\n if (inputMap) {\n // mergeSourceMap returns an encoded map\n outputMap = mergeSourceMap(\n inputMap.toObject(),\n outputMap,\n generatorOpts.sourceFileName,\n );\n } else {\n // We cannot output a decoded map, so retrieve the encoded form. Because\n // the decoded form is free, it's fine to prioritize decoded first.\n outputMap = result.map;\n }\n }\n }\n\n if (opts.sourceMaps === \"inline\" || opts.sourceMaps === \"both\") {\n outputCode += \"\\n\" + convertSourceMap.fromObject(outputMap).toComment();\n }\n\n if (opts.sourceMaps === \"inline\") {\n outputMap = null;\n }\n\n // @ts-expect-error outputMap must be an EncodedSourceMap or null\n return { outputCode, outputMap };\n}\n"],"mappings":"AACA,OAAOA,gBAAgB,MAAM,oBAAoB;AAEjD,OAAOC,QAAQ,MAAM,kBAAkB;AAGvC,OAAOC,cAAc,MAAM,gBAAgB;AAE3C,eAAe,SAASC,YAAYA,CAClCC,YAA0B,EAC1BC,IAAU,EAIV;EACA,MAAM;IAAEC,IAAI;IAAEC,GAAG;IAAEC,IAAI;IAAEC;EAAS,CAAC,GAAGJ,IAAI;EAC1C,MAAM;IAAEK;EAAc,CAAC,GAAGJ,IAAI;EAE9BI,aAAa,CAACC,cAAc,GAAGF,QAAQ,EAAEG,QAAQ,CAAC,CAAC;EAEnD,MAAMC,OAAO,GAAG,EAAE;EAClB,KAAK,MAAMC,OAAO,IAAIV,YAAY,EAAE;IAClC,KAAK,MAAMW,MAAM,IAAID,OAAO,EAAE;MAC5B,MAAM;QAAEE;MAAkB,CAAC,GAAGD,MAAM;MACpC,IAAIC,iBAAiB,EAAE;QACrB,MAAMC,MAAM,GAAGD,iBAAiB,CAACT,GAAG,EAAEG,aAAa,EAAEF,IAAI,EAAEP,QAAQ,CAAC;QAEpE,IAAIgB,MAAM,KAAKC,SAAS,EAAEL,OAAO,CAACM,IAAI,CAACF,MAAM,CAAC;MAChD;IACF;EACF;EAEA,IAAIA,MAAM;EACV,IAAIJ,OAAO,CAACO,MAAM,KAAK,CAAC,EAAE;IACxBH,MAAM,GAAGhB,QAAQ,CAACM,GAAG,EAAEG,aAAa,EAAEF,IAAI,CAAC;EAC7C,CAAC,MAAM,IAAIK,OAAO,CAACO,MAAM,KAAK,CAAC,EAAE;IAC/BH,MAAM,GAAGJ,OAAO,CAAC,CAAC,CAAC;IAGnB,IAAI,OAAOI,MAAM,CAACI,IAAI,KAAK,UAAU,EAAE;MACrC,MAAM,IAAIC,KAAK,CACb,kDAAkD,GAChD,wDAAwD,GACxD,sCAAsC,GACtC,mDACJ,CAAC;IACH;EACF,CAAC,MAAM;IACL,MAAM,IAAIA,KAAK,CAAC,qDAAqD,CAAC;EACxE;EAKA,IAAI;IAAEd,IAAI,EAAEe,UAAU;IAAEC,UAAU,EAAEC,SAAS,GAAGR,MAAM,CAACS;EAAI,CAAC,GAAGT,MAAM;EAGrE,IAAIA,MAAM,CAACU,WAAW,EAAE;IAItBF,SAAS,GAAG;MAAE,GAAGR,MAAM,CAACS;IAAI,CAAC;EAC/B,CAAC,MAAM;IACL,IAAID,SAAS,EAAE;MACb,IAAIhB,QAAQ,EAAE;QAEZgB,SAAS,GAAGvB,cAAc,CACxBO,QAAQ,CAACG,QAAQ,CAAC,CAAC,EACnBa,SAAS,EACTf,aAAa,CAACkB,cAChB,CAAC;MACH,CAAC,MAAM;QAGLH,SAAS,GAAGR,MAAM,CAACS,GAAG;MACxB;IACF;EACF;EAEA,IAAIpB,IAAI,CAACuB,UAAU,KAAK,QAAQ,IAAIvB,IAAI,CAACuB,UAAU,KAAK,MAAM,EAAE;IAC9DN,UAAU,IAAI,IAAI,GAAGvB,gBAAgB,CAAC8B,UAAU,CAACL,SAAS,CAAC,CAACM,SAAS,CAAC,CAAC;EACzE;EAEA,IAAIzB,IAAI,CAACuB,UAAU,KAAK,QAAQ,EAAE;IAChCJ,SAAS,GAAG,IAAI;EAClB;EAGA,OAAO;IAAEF,UAAU;IAAEE;EAAU,CAAC;AAClC","ignoreList":[]} |
| import remapping from "@jridgewell/remapping"; | ||
| export default function mergeSourceMap(inputMap, map, sourceFileName) { | ||
| const source = sourceFileName.replace(/\\/g, "/"); | ||
| let found = false; | ||
| const result = remapping(rootless(map), (s, ctx) => { | ||
| if (s === source && !found) { | ||
| found = true; | ||
| ctx.source = ""; | ||
| return rootless(inputMap); | ||
| } | ||
| return null; | ||
| }); | ||
| if (typeof inputMap.sourceRoot === "string") { | ||
| result.sourceRoot = inputMap.sourceRoot; | ||
| } | ||
| return { | ||
| ...result | ||
| }; | ||
| } | ||
| function rootless(map) { | ||
| return { | ||
| ...map, | ||
| sourceRoot: null | ||
| }; | ||
| } | ||
| //# sourceMappingURL=merge-map.js.map |
| {"version":3,"names":["remapping","mergeSourceMap","inputMap","map","sourceFileName","source","replace","found","result","rootless","s","ctx","sourceRoot"],"sources":["../../../src/transformation/file/merge-map.ts"],"sourcesContent":["type SourceMap = any;\nimport remapping from \"@jridgewell/remapping\";\n\nexport default function mergeSourceMap(\n inputMap: SourceMap,\n map: SourceMap,\n sourceFileName: string,\n): SourceMap {\n // On win32 machines, the sourceFileName uses backslash paths like\n // `C:\\foo\\bar.js`. But sourcemaps are always posix paths, so we need to\n // normalize to regular slashes before we can merge (else we won't find the\n // source associated with our input map).\n // This mirrors code done while generating the output map at\n // https://github.com/babel/babel/blob/5c2fcadc9ae34fd20dd72b1111d5cf50476d700d/packages/babel-generator/src/source-map.ts#L102\n const source = sourceFileName.replace(/\\\\/g, \"/\");\n\n // Prevent an infinite recursion if one of the input map's sources has the\n // same resolved path as the input map. In the case, it would keep find the\n // input map, then get it's sources which will include a path like the input\n // map, on and on.\n let found = false;\n const result = remapping(rootless(map), (s, ctx) => {\n if (s === source && !found) {\n found = true;\n // We empty the source location, which will prevent the sourcemap from\n // becoming relative to the input's location. Eg, if we're transforming a\n // file 'foo/bar.js', and it is a transformation of a `baz.js` file in the\n // same directory, the expected output is just `baz.js`. Without this step,\n // it would become `foo/baz.js`.\n ctx.source = \"\";\n\n return rootless(inputMap);\n }\n\n return null;\n });\n\n if (typeof inputMap.sourceRoot === \"string\") {\n result.sourceRoot = inputMap.sourceRoot;\n }\n\n // remapping returns a SourceMap class type, but this breaks code downstream in\n // @babel/traverse and @babel/types that relies on data being plain objects.\n // When it encounters the sourcemap type it outputs a \"don't know how to turn\n // this value into a node\" error. As a result, we are converting the merged\n // sourcemap to a plain js object.\n return { ...result };\n}\n\nfunction rootless(map: SourceMap): SourceMap {\n return {\n ...map,\n\n // This is a bit hack. Remapping will create absolute sources in our\n // sourcemap, but we want to maintain sources relative to the sourceRoot.\n // We'll re-add the sourceRoot after remapping.\n sourceRoot: null,\n };\n}\n"],"mappings":"AACA,OAAOA,SAAS,MAAM,uBAAuB;AAE7C,eAAe,SAASC,cAAcA,CACpCC,QAAmB,EACnBC,GAAc,EACdC,cAAsB,EACX;EAOX,MAAMC,MAAM,GAAGD,cAAc,CAACE,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;EAMjD,IAAIC,KAAK,GAAG,KAAK;EACjB,MAAMC,MAAM,GAAGR,SAAS,CAACS,QAAQ,CAACN,GAAG,CAAC,EAAE,CAACO,CAAC,EAAEC,GAAG,KAAK;IAClD,IAAID,CAAC,KAAKL,MAAM,IAAI,CAACE,KAAK,EAAE;MAC1BA,KAAK,GAAG,IAAI;MAMZI,GAAG,CAACN,MAAM,GAAG,EAAE;MAEf,OAAOI,QAAQ,CAACP,QAAQ,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb,CAAC,CAAC;EAEF,IAAI,OAAOA,QAAQ,CAACU,UAAU,KAAK,QAAQ,EAAE;IAC3CJ,MAAM,CAACI,UAAU,GAAGV,QAAQ,CAACU,UAAU;EACzC;EAOA,OAAO;IAAE,GAAGJ;EAAO,CAAC;AACtB;AAEA,SAASC,QAAQA,CAACN,GAAc,EAAa;EAC3C,OAAO;IACL,GAAGA,GAAG;IAKNS,UAAU,EAAE;EACd,CAAC;AACH","ignoreList":[]} |
| import traverse from "@babel/traverse"; | ||
| import PluginPass from "./plugin-pass.js"; | ||
| import loadBlockHoistPlugin from "./block-hoist-plugin.js"; | ||
| import normalizeOptions from "./normalize-opts.js"; | ||
| import normalizeFile from "./normalize-file.js"; | ||
| import generateCode from "./file/generate.js"; | ||
| import { flattenToSet } from "../config/helpers/deep-array.js"; | ||
| import { isAsync, maybeAsync } from "../gensync-utils/async.js"; | ||
| export function* run(config, code, ast) { | ||
| const file = yield* normalizeFile(config.passes, normalizeOptions(config), code, ast); | ||
| const opts = file.opts; | ||
| try { | ||
| yield* transformFile(file, config.passes); | ||
| } catch (e) { | ||
| e.message = `${opts.filename ?? "unknown file"}: ${e.message}`; | ||
| if (!e.code) { | ||
| e.code = "BABEL_TRANSFORM_ERROR"; | ||
| } | ||
| throw e; | ||
| } | ||
| let outputCode, outputMap; | ||
| try { | ||
| if (opts.code !== false) { | ||
| ({ | ||
| outputCode, | ||
| outputMap | ||
| } = generateCode(config.passes, file)); | ||
| } | ||
| } catch (e) { | ||
| e.message = `${opts.filename ?? "unknown file"}: ${e.message}`; | ||
| if (!e.code) { | ||
| e.code = "BABEL_GENERATE_ERROR"; | ||
| } | ||
| throw e; | ||
| } | ||
| return { | ||
| metadata: file.metadata, | ||
| options: opts, | ||
| ast: opts.ast === true ? file.ast : null, | ||
| code: outputCode === undefined ? null : outputCode, | ||
| map: outputMap === undefined ? null : outputMap, | ||
| sourceType: file.ast.program.sourceType, | ||
| externalDependencies: flattenToSet(config.externalDependencies) | ||
| }; | ||
| } | ||
| function* transformFile(file, pluginPasses) { | ||
| const async = yield* isAsync(); | ||
| for (const pluginPairs of pluginPasses) { | ||
| const passPairs = []; | ||
| const passes = []; | ||
| const visitors = []; | ||
| for (const plugin of pluginPairs.concat([loadBlockHoistPlugin()])) { | ||
| const pass = new PluginPass(file, plugin.key, plugin.options, async); | ||
| passPairs.push([plugin, pass]); | ||
| passes.push(pass); | ||
| visitors.push(plugin.visitor); | ||
| } | ||
| for (const [plugin, pass] of passPairs) { | ||
| if (plugin.pre) { | ||
| const fn = maybeAsync(plugin.pre, `You appear to be using an async plugin/preset, but Babel has been called synchronously`); | ||
| yield* fn.call(pass, file); | ||
| } | ||
| } | ||
| const visitor = traverse.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod); | ||
| traverse(file.ast.program, visitor, file.scope, null, file.path, true); | ||
| for (const [plugin, pass] of passPairs) { | ||
| if (plugin.post) { | ||
| const fn = maybeAsync(plugin.post, `You appear to be using an async plugin/preset, but Babel has been called synchronously`); | ||
| yield* fn.call(pass, file); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| //# sourceMappingURL=index.js.map |
| {"version":3,"names":["traverse","PluginPass","loadBlockHoistPlugin","normalizeOptions","normalizeFile","generateCode","flattenToSet","isAsync","maybeAsync","run","config","code","ast","file","passes","opts","transformFile","e","message","filename","outputCode","outputMap","metadata","options","undefined","map","sourceType","program","externalDependencies","pluginPasses","async","pluginPairs","passPairs","visitors","plugin","concat","pass","key","push","visitor","pre","fn","call","merge","wrapPluginVisitorMethod","scope","path","post"],"sources":["../../src/transformation/index.ts"],"sourcesContent":["import traverse from \"@babel/traverse\";\nimport type * as t from \"@babel/types\";\nimport type { GeneratorResult } from \"@babel/generator\";\n\nimport type { Handler } from \"gensync\";\n\nimport type { ResolvedConfig, Plugin, PluginPasses } from \"../config/index.ts\";\n\nimport PluginPass from \"./plugin-pass.ts\";\nimport loadBlockHoistPlugin from \"./block-hoist-plugin.ts\";\nimport normalizeOptions from \"./normalize-opts.ts\";\nimport normalizeFile from \"./normalize-file.ts\";\n\nimport generateCode from \"./file/generate.ts\";\nimport type File from \"./file/file.ts\";\n\nimport { flattenToSet } from \"../config/helpers/deep-array.ts\";\nimport { isAsync, maybeAsync } from \"../gensync-utils/async.ts\";\nimport type { SourceTypeOption } from \"../config/validation/options.ts\";\n\nexport type FileResultCallback = {\n (err: Error, file: null): void;\n (err: null, file: FileResult | null): void;\n};\n\nexport type FileResult = {\n metadata: Record<string, any>;\n options: Record<string, any>;\n ast: t.File | null;\n code: string | null;\n map: GeneratorResult[\"map\"];\n sourceType: Exclude<SourceTypeOption, \"unambiguous\">;\n externalDependencies: Set<string>;\n};\n\nexport function* run(\n config: ResolvedConfig,\n code: string,\n ast?: t.File | t.Program | null,\n): Handler<FileResult> {\n const file = yield* normalizeFile(\n config.passes,\n normalizeOptions(config),\n code,\n ast,\n );\n\n const opts = file.opts;\n try {\n yield* transformFile(file, config.passes);\n } catch (e) {\n e.message = `${opts.filename ?? \"unknown file\"}: ${e.message}`;\n if (!e.code) {\n e.code = \"BABEL_TRANSFORM_ERROR\";\n }\n throw e;\n }\n\n let outputCode, outputMap;\n try {\n if (opts.code !== false) {\n ({ outputCode, outputMap } = generateCode(config.passes, file));\n }\n } catch (e) {\n e.message = `${opts.filename ?? \"unknown file\"}: ${e.message}`;\n if (!e.code) {\n e.code = \"BABEL_GENERATE_ERROR\";\n }\n throw e;\n }\n\n return {\n metadata: file.metadata,\n options: opts,\n ast: opts.ast === true ? file.ast : null,\n code: outputCode === undefined ? null : outputCode,\n map: outputMap === undefined ? null : outputMap,\n sourceType: file.ast.program.sourceType,\n externalDependencies: flattenToSet(config.externalDependencies),\n };\n}\n\nfunction* transformFile(file: File, pluginPasses: PluginPasses): Handler<void> {\n const async = yield* isAsync();\n\n for (const pluginPairs of pluginPasses) {\n const passPairs: [Plugin, PluginPass][] = [];\n const passes = [];\n const visitors = [];\n\n for (const plugin of pluginPairs.concat([loadBlockHoistPlugin()])) {\n const pass = new PluginPass(file, plugin.key, plugin.options, async);\n\n passPairs.push([plugin, pass]);\n passes.push(pass);\n visitors.push(plugin.visitor);\n }\n\n for (const [plugin, pass] of passPairs) {\n if (plugin.pre) {\n const fn = maybeAsync(\n plugin.pre,\n `You appear to be using an async plugin/preset, but Babel has been called synchronously`,\n );\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n yield* fn.call(pass, file);\n }\n }\n\n // merge all plugin visitors into a single visitor\n const visitor = traverse.visitors.merge(\n visitors,\n passes,\n file.opts.wrapPluginVisitorMethod,\n );\n\n traverse(file.ast.program, visitor, file.scope, null, file.path, true);\n\n for (const [plugin, pass] of passPairs) {\n if (plugin.post) {\n const fn = maybeAsync(\n plugin.post,\n `You appear to be using an async plugin/preset, but Babel has been called synchronously`,\n );\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n yield* fn.call(pass, file);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AAEE,IAAI,CAAC,IAAIJ,SAAS,EAAE;MACtC,IAAIE,MAAM,CAACM,GAAG,EAAE;QACd,MAAMC,EAAE,GAAGjC,UAAU,CACnB0B,MAAM,CAACM,GAAG,EACV,wFACF,CAAC;QAGD,OAAOC,EAAE,CAACC,IAAI,CAACN,IAAI,EAAEvB,IAAI,CAAC;MAC5B;IACF;IAGA,MAAM0B,OAAO,GAAGvC,QAAQ,CAACiC,QAAQ,CAACU,KAAK,CACrCV,QAAQ,EACRnB,MAAM,EACND,IAAI,CAACE,IAAI,CAAC6B,uBACZ,CAAC;IAED5C,QAAQ,CAACa,IAAI,CAACD,GAAG,CAACe,OAAO,EAAEY,OAAO,EAAE1B,IAAI,CAACgC,KAAK,EAAE,IAAI,EAAEhC,IAAI,CAACiC,IAAI,EAAE,IAAI,CAAC;IAEtE,KAAK,MAAM,CAACZ,MAAM,EAAEE,IAAI,CAAC,IAAIJ,SAAS,EAAE;MACtC,IAAIE,MAAM,CAACa,IAAI,EAAE;QACf,MAAMN,EAAE,GAAGjC,UAAU,CACnB0B,MAAM,CAACa,IAAI,EACX,wFACF,CAAC;QAGD,OAAON,EAAE,CAACC,IAAI,CAACN,IAAI,EAAEvB,IAAI,CAAC;MAC5B;IACF;EACF;AACF","ignoreList":[]} |
| import fs from "node:fs"; | ||
| import path from "node:path"; | ||
| import { createDebug } from "obug"; | ||
| import * as _t from "@babel/types"; | ||
| const { | ||
| file, | ||
| traverseFast | ||
| } = _t; | ||
| import convertSourceMap from "convert-source-map"; | ||
| import File from "./file/file.js"; | ||
| import parser from "../parser/index.js"; | ||
| import cloneDeep from "./util/clone-deep.js"; | ||
| const debug = createDebug("babel:transform:file"); | ||
| const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,.*$/; | ||
| const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/; | ||
| export default function* normalizeFile(pluginPasses, options, code, ast) { | ||
| code = `${code || ""}`; | ||
| if (ast) { | ||
| if (ast.type === "Program") { | ||
| ast = file(ast, [], []); | ||
| } else if (ast.type !== "File") { | ||
| throw new Error("AST root must be a Program or File node"); | ||
| } | ||
| if (options.cloneInputAst) { | ||
| ast = cloneDeep(ast); | ||
| } | ||
| } else { | ||
| ast = yield* parser(pluginPasses, options, code); | ||
| } | ||
| let inputMap = null; | ||
| if (options.inputSourceMap !== false) { | ||
| if (typeof options.inputSourceMap === "object") { | ||
| inputMap = convertSourceMap.fromObject(options.inputSourceMap); | ||
| } | ||
| if (!inputMap) { | ||
| const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast); | ||
| if (lastComment) { | ||
| try { | ||
| inputMap = convertSourceMap.fromComment("//" + lastComment); | ||
| } catch (err) { | ||
| console.warn("discarding unknown inline input sourcemap", options.filename, err); | ||
| } | ||
| } | ||
| } | ||
| if (!inputMap) { | ||
| const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast); | ||
| if (typeof options.filename === "string" && lastComment) { | ||
| try { | ||
| const match = EXTERNAL_SOURCEMAP_REGEX.exec(lastComment); | ||
| const inputMapContent = fs.readFileSync(path.resolve(path.dirname(options.filename), match[1]), "utf8"); | ||
| inputMap = convertSourceMap.fromJSON(inputMapContent); | ||
| } catch (err) { | ||
| debug("discarding unknown file input sourcemap", err); | ||
| } | ||
| } else if (lastComment) { | ||
| debug("discarding un-loadable file input sourcemap"); | ||
| } | ||
| } | ||
| } | ||
| return new File(options, { | ||
| code, | ||
| ast: ast, | ||
| inputMap | ||
| }); | ||
| } | ||
| function extractCommentsFromList(regex, comments, lastComment) { | ||
| if (comments) { | ||
| comments = comments.filter(({ | ||
| value | ||
| }) => { | ||
| if (regex.test(value)) { | ||
| lastComment = value; | ||
| return false; | ||
| } | ||
| return true; | ||
| }); | ||
| } | ||
| return [comments, lastComment]; | ||
| } | ||
| function extractComments(regex, ast) { | ||
| let lastComment = null; | ||
| traverseFast(ast, node => { | ||
| [node.leadingComments, lastComment] = extractCommentsFromList(regex, node.leadingComments, lastComment); | ||
| [node.innerComments, lastComment] = extractCommentsFromList(regex, node.innerComments, lastComment); | ||
| [node.trailingComments, lastComment] = extractCommentsFromList(regex, node.trailingComments, lastComment); | ||
| }); | ||
| return lastComment; | ||
| } | ||
| //# sourceMappingURL=normalize-file.js.map |
| {"version":3,"names":["fs","path","createDebug","_t","file","traverseFast","convertSourceMap","File","parser","cloneDeep","debug","INLINE_SOURCEMAP_REGEX","EXTERNAL_SOURCEMAP_REGEX","normalizeFile","pluginPasses","options","code","ast","type","Error","cloneInputAst","inputMap","inputSourceMap","fromObject","lastComment","extractComments","fromComment","err","console","warn","filename","match","exec","inputMapContent","readFileSync","resolve","dirname","fromJSON","extractCommentsFromList","regex","comments","filter","value","test","node","leadingComments","innerComments","trailingComments"],"sources":["../../src/transformation/normalize-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { createDebug } from \"obug\";\nimport type { Handler } from \"gensync\";\nimport { file, traverseFast } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport type { PluginPasses } from \"../config/index.ts\";\nimport convertSourceMap from \"convert-source-map\";\nimport type { SourceMapConverter as Converter } from \"convert-source-map\";\nimport File from \"./file/file.ts\";\nimport parser from \"../parser/index.ts\";\nimport cloneDeep from \"./util/clone-deep.ts\";\nimport type { ResolvedOptions } from \"../config/validation/options.ts\";\n\nconst debug = createDebug(\"babel:transform:file\");\n\n// These regexps are copied from the convert-source-map package,\n// but without // or /* at the beginning of the comment.\n\nconst INLINE_SOURCEMAP_REGEX =\n /^[@#]\\s+sourceMappingURL=data:(?:application|text)\\/json;(?:charset[:=]\\S+?;)?base64,.*$/;\nconst EXTERNAL_SOURCEMAP_REGEX =\n /^[@#][ \\t]+sourceMappingURL=([^\\s'\"`]+)[ \\t]*$/;\n\nexport type NormalizedFile = {\n code: string;\n ast: t.File;\n inputMap: Converter | null;\n};\n\nexport default function* normalizeFile(\n pluginPasses: PluginPasses,\n options: ResolvedOptions,\n code: string,\n ast?: t.File | t.Program | null,\n): Handler<File> {\n code = `${code || \"\"}`;\n\n if (ast) {\n if (ast.type === \"Program\") {\n ast = file(ast, [], []);\n } else if (ast.type !== \"File\") {\n throw new Error(\"AST root must be a Program or File node\");\n }\n\n if (options.cloneInputAst) {\n ast = cloneDeep(ast);\n }\n } else {\n ast = yield* parser(pluginPasses, options, code);\n }\n\n let inputMap = null;\n if (options.inputSourceMap !== false) {\n // If an explicit object is passed in, it overrides the processing of\n // source maps that may be in the file itself.\n if (typeof options.inputSourceMap === \"object\") {\n inputMap = convertSourceMap.fromObject(options.inputSourceMap);\n }\n\n if (!inputMap) {\n const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast);\n if (lastComment) {\n try {\n inputMap = convertSourceMap.fromComment(\"//\" + lastComment);\n } catch (err) {\n console.warn(\n \"discarding unknown inline input sourcemap\",\n options.filename,\n err,\n );\n }\n }\n }\n\n if (!inputMap) {\n const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast);\n if (typeof options.filename === \"string\" && lastComment) {\n try {\n // when `lastComment` is non-null, EXTERNAL_SOURCEMAP_REGEX must have matches\n const match: [string, string] = EXTERNAL_SOURCEMAP_REGEX.exec(\n lastComment,\n ) as any;\n const inputMapContent = fs.readFileSync(\n path.resolve(path.dirname(options.filename), match[1]),\n \"utf8\",\n );\n inputMap = convertSourceMap.fromJSON(inputMapContent);\n } catch (err) {\n debug(\"discarding unknown file input sourcemap\", err);\n }\n } else if (lastComment) {\n debug(\"discarding un-loadable file input sourcemap\");\n }\n }\n }\n\n return new File(options, {\n code,\n ast: ast,\n inputMap,\n });\n}\n\nfunction extractCommentsFromList(\n regex: RegExp,\n comments: t.Comment[],\n lastComment: string | null,\n): [t.Comment[], string | null] {\n if (comments) {\n comments = comments.filter(({ value }) => {\n if (regex.test(value)) {\n lastComment = value;\n return false;\n }\n return true;\n });\n }\n return [comments, lastComment];\n}\n\nfunction extractComments(regex: RegExp, ast: t.Node) {\n let lastComment: string = null;\n traverseFast(ast, node => {\n [node.leadingComments, lastComment] = extractCommentsFromList(\n regex,\n node.leadingComments,\n lastComment,\n );\n [node.innerComments, lastComment] = extractCommentsFromList(\n regex,\n node.innerComments,\n lastComment,\n );\n [node.trailingComments, lastComment] = extractCommentsFromList(\n regex,\n node.trailingComments,\n lastComment,\n );\n });\n return lastComment;\n}\n"],"mappings":"AAAA,OAAOA,EAAE,MAAM,SAAS;AACxB,OAAOC,IAAI,MAAM,WAAW;AAC5B,SAASC,WAAW,QAAQ,MAAM;AAElC,YAAAC,EAAA,MAAmC,cAAc;AAAC;EAAzCC,IAAI;EAAEC;AAAY,IAAAF,EAAA;AAG3B,OAAOG,gBAAgB,MAAM,oBAAoB;AAEjD,OAAOC,IAAI,MAAM,gBAAgB;AACjC,OAAOC,MAAM,MAAM,oBAAoB;AACvC,OAAOC,SAAS,MAAM,sBAAsB;AAG5C,MAAMC,KAAK,GAAGR,WAAW,CAAC,sBAAsB,CAAC;AAKjD,MAAMS,sBAAsB,GAC1B,0FAA0F;AAC5F,MAAMC,wBAAwB,GAC5B,gDAAgD;AAQlD,eAAe,UAAUC,aAAaA,CACpCC,YAA0B,EAC1BC,OAAwB,EACxBC,IAAY,EACZC,GAA+B,EAChB;EACfD,IAAI,GAAG,GAAGA,IAAI,IAAI,EAAE,EAAE;EAEtB,IAAIC,GAAG,EAAE;IACP,IAAIA,GAAG,CAACC,IAAI,KAAK,SAAS,EAAE;MAC1BD,GAAG,GAAGb,IAAI,CAACa,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC;IACzB,CAAC,MAAM,IAAIA,GAAG,CAACC,IAAI,KAAK,MAAM,EAAE;MAC9B,MAAM,IAAIC,KAAK,CAAC,yCAAyC,CAAC;IAC5D;IAEA,IAAIJ,OAAO,CAACK,aAAa,EAAE;MACzBH,GAAG,GAAGR,SAAS,CAACQ,GAAG,CAAC;IACtB;EACF,CAAC,MAAM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ACvD;MACF,CAAC,MAAM,IAAIH,WAAW,EAAE;QACtBd,KAAK,CAAC,6CAA6C,CAAC;MACtD;IACF;EACF;EAEA,OAAO,IAAIH,IAAI,CAACQ,OAAO,EAAE;IACvBC,IAAI;IACJC,GAAG,EAAEA,GAAG;IACRI;EACF,CAAC,CAAC;AACJ;AAEA,SAASiB,uBAAuBA,CAC9BC,KAAa,EACbC,QAAqB,EACrBhB,WAA0B,EACI;EAC9B,IAAIgB,QAAQ,EAAE;IACZA,QAAQ,GAAGA,QAAQ,CAACC,MAAM,CAAC,CAAC;MAAEC;IAAM,CAAC,KAAK;MACxC,IAAIH,KAAK,CAACI,IAAI,CAACD,KAAK,CAAC,EAAE;QACrBlB,WAAW,GAAGkB,KAAK;QACnB,OAAO,KAAK;MACd;MACA,OAAO,IAAI;IACb,CAAC,CAAC;EACJ;EACA,OAAO,CAACF,QAAQ,EAAEhB,WAAW,CAAC;AAChC;AAEA,SAASC,eAAeA,CAACc,KAAa,EAAEtB,GAAW,EAAE;EACnD,IAAIO,WAAmB,GAAG,IAAI;EAC9BnB,YAAY,CAACY,GAAG,EAAE2B,IAAI,IAAI;IACxB,CAACA,IAAI,CAACC,eAAe,EAAErB,WAAW,CAAC,GAAGc,uBAAuB,CAC3DC,KAAK,EACLK,IAAI,CAACC,eAAe,EACpBrB,WACF,CAAC;IACD,CAACoB,IAAI,CAACE,aAAa,EAAEtB,WAAW,CAAC,GAAGc,uBAAuB,CACzDC,KAAK,EACLK,IAAI,CAACE,aAAa,EAClBtB,WACF,CAAC;IACD,CAACoB,IAAI,CAACG,gBAAgB,EAAEvB,WAAW,CAAC,GAAGc,uBAAuB,CAC5DC,KAAK,EACLK,IAAI,CAACG,gBAAgB,EACrBvB,WACF,CAAC;EACH,CAAC,CAAC;EACF,OAAOA,WAAW;AACpB","ignoreList":[]} |
| import path from "node:path"; | ||
| export default function normalizeOptions(config) { | ||
| const { | ||
| filename, | ||
| cwd, | ||
| filenameRelative = typeof filename === "string" ? path.relative(cwd, filename) : "unknown", | ||
| sourceType = "module", | ||
| inputSourceMap, | ||
| sourceMaps = !!inputSourceMap, | ||
| sourceRoot = undefined, | ||
| sourceFileName = path.basename(filenameRelative), | ||
| comments = true, | ||
| compact = "auto" | ||
| } = config.options; | ||
| const opts = config.options; | ||
| const options = { | ||
| ...opts, | ||
| parserOpts: { | ||
| sourceType: path.extname(filenameRelative) === ".mjs" ? "module" : sourceType, | ||
| sourceFileName: filename, | ||
| plugins: [], | ||
| ...opts.parserOpts | ||
| }, | ||
| generatorOpts: { | ||
| filename, | ||
| auxiliaryCommentBefore: opts.auxiliaryCommentBefore, | ||
| auxiliaryCommentAfter: opts.auxiliaryCommentAfter, | ||
| retainLines: opts.retainLines, | ||
| comments, | ||
| shouldPrintComment: opts.shouldPrintComment, | ||
| compact, | ||
| minified: opts.minified, | ||
| sourceMaps: !!sourceMaps, | ||
| sourceRoot, | ||
| sourceFileName, | ||
| ...opts.generatorOpts | ||
| } | ||
| }; | ||
| for (const plugins of config.passes) { | ||
| for (const plugin of plugins) { | ||
| if (plugin.manipulateOptions) { | ||
| plugin.manipulateOptions(options, options.parserOpts); | ||
| } | ||
| } | ||
| } | ||
| return options; | ||
| } | ||
| //# sourceMappingURL=normalize-opts.js.map |
| {"version":3,"names":["path","normalizeOptions","config","filename","cwd","filenameRelative","relative","sourceType","inputSourceMap","sourceMaps","sourceRoot","undefined","sourceFileName","basename","comments","compact","options","opts","parserOpts","extname","plugins","generatorOpts","auxiliaryCommentBefore","auxiliaryCommentAfter","retainLines","shouldPrintComment","minified","passes","plugin","manipulateOptions"],"sources":["../../src/transformation/normalize-opts.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { ResolvedConfig } from \"../config/index.ts\";\nimport type { ResolvedOptions } from \"../config/validation/options.ts\";\n\nexport default function normalizeOptions(\n config: ResolvedConfig,\n): ResolvedOptions {\n const {\n filename,\n cwd,\n filenameRelative = typeof filename === \"string\"\n ? path.relative(cwd, filename)\n : \"unknown\",\n sourceType = \"module\",\n inputSourceMap,\n sourceMaps = !!inputSourceMap,\n sourceRoot = undefined,\n\n sourceFileName = path.basename(filenameRelative),\n\n comments = true,\n compact = \"auto\",\n } = config.options;\n\n const opts = config.options;\n\n const options: ResolvedOptions = {\n ...opts,\n\n parserOpts: {\n sourceType:\n path.extname(filenameRelative) === \".mjs\" ? \"module\" : sourceType,\n\n // @ts-expect-error We should have passed `sourceFilename` here\n // pending https://github.com/babel/babel/issues/15917#issuecomment-2789278964\n sourceFileName: filename,\n plugins: [],\n ...opts.parserOpts,\n },\n\n generatorOpts: {\n // General generator flags.\n filename,\n\n auxiliaryCommentBefore: opts.auxiliaryCommentBefore,\n auxiliaryCommentAfter: opts.auxiliaryCommentAfter,\n retainLines: opts.retainLines,\n comments,\n shouldPrintComment: opts.shouldPrintComment,\n compact,\n minified: opts.minified,\n\n // Source-map generation flags.\n // babel-generator does not differentiate between `true`, `\"inline\"` or `\"both\"`\n sourceMaps: !!sourceMaps,\n sourceRoot,\n sourceFileName,\n\n ...opts.generatorOpts,\n },\n };\n\n for (const plugins of config.passes) {\n for (const plugin of plugins) {\n if (plugin.manipulateOptions) {\n plugin.manipulateOptions(options, options.parserOpts);\n }\n }\n }\n\n return options;\n}\n"],"mappings":"AAAA,OAAOA,IAAI,MAAM,WAAW;AAI5B,eAAe,SAASC,gBAAgBA,CACtCC,MAAsB,EACL;EACjB,MAAM;IACJC,QAAQ;IACRC,GAAG;IACHC,gBAAgB,GAAG,OAAOF,QAAQ,KAAK,QAAQ,GAC3CH,IAAI,CAACM,QAAQ,CAACF,GAAG,EAAED,QAAQ,CAAC,GAC5B,SAAS;IACbI,UAAU,GAAG,QAAQ;IACrBC,cAAc;IACdC,UAAU,GAAG,CAAC,CAACD,cAAc;IAC7BE,UAAU,GAAGC,SAAS;IAEtBC,cAAc,GAAGZ,IAAI,CAACa,QAAQ,CAACR,gBAAgB,CAAC;IAEhDS,QAAQ,GAAG,IAAI;IACfC,OAAO,GAAG;EACZ,CAAC,GAAGb,MAAM,CAACc,OAAO;EAElB,MAAMC,IAAI,GAAGf,MAAM,CAACc,OAAO;EAE3B,MAAMA,OAAwB,GAAG;IAC/B,GAAGC,IAAI;IAEPC,UAAU,EAAE;MACVX,UAAU,EACRP,IAAI,CAACmB,OAAO,CAACd,gBAAgB,CAAC,KAAK,MAAM,GAAG,QAAQ,GAAGE,UAAU;MAInEK,cAAc,EAAET,QAAQ;MACxBiB,OAAO,EAAE,EAAE;MACX,GAAGH,IAAI,CAACC;IACV,CAAC;IAEDG,aAAa,EAAE;MAEblB,QAAQ;MAERmB,sBAAsB,EAAEL,IAAI,CAACK,sBAAsB;MACnDC,qBAAqB,EAAEN,IAAI,CAACM,qBAAqB;MACjDC,WAAW,EAAEP,IAAI,CAACO,WAAW;MAC7BV,QAAQ;MACRW,kBAAkB,EAAER,IAAI,CAACQ,kBAAkB;MAC3CV,OAAO;MACPW,QAAQ,EAAET,IAAI,CAACS,QAAQ;MAIvBjB,UAAU,EAAE,CAAC,CAACA,UAAU;MACxBC,UAAU;MACVE,cAAc;MAEd,GAAGK,IAAI,CAACI;IACV;EACF,CAAC;EAED,KAAK,MAAMD,OAAO,IAAIlB,MAAM,CAACyB,MAAM,EAAE;IACnC,KAAK,MAAMC,MAAM,IAAIR,OAAO,EAAE;MAC5B,IAAIQ,MAAM,CAACC,iBAAiB,EAAE;QAC5BD,MAAM,CAACC,iBAAiB,CAACb,OAAO,EAAEA,OAAO,CAACE,UAAU,CAAC;MACvD;IACF;EACF;EAEA,OAAOF,OAAO;AAChB","ignoreList":[]} |
| export default class PluginPass { | ||
| _map = new Map(); | ||
| key; | ||
| file; | ||
| opts; | ||
| cwd; | ||
| filename; | ||
| isAsync; | ||
| constructor(file, key, options, isAsync) { | ||
| this.key = key; | ||
| this.file = file; | ||
| this.opts = options || {}; | ||
| this.cwd = file.opts.cwd; | ||
| this.filename = file.opts.filename; | ||
| this.isAsync = isAsync; | ||
| } | ||
| set(key, val) { | ||
| this._map.set(key, val); | ||
| } | ||
| get(key) { | ||
| return this._map.get(key); | ||
| } | ||
| availableHelper(name, versionRange) { | ||
| return this.file.availableHelper(name, versionRange); | ||
| } | ||
| addHelper(name) { | ||
| return this.file.addHelper(name); | ||
| } | ||
| buildCodeFrameError(node, msg, _Error) { | ||
| return this.file.buildCodeFrameError(node, msg, _Error); | ||
| } | ||
| } | ||
| //# sourceMappingURL=plugin-pass.js.map |
| {"version":3,"names":["PluginPass","_map","Map","key","file","opts","cwd","filename","isAsync","constructor","options","set","val","get","availableHelper","name","versionRange","addHelper","buildCodeFrameError","node","msg","_Error"],"sources":["../../src/transformation/plugin-pass.ts"],"sourcesContent":["import type * as t from \"@babel/types\";\nimport type File from \"./file/file.ts\";\n\nexport default class PluginPass<Options = object> {\n _map = new Map<unknown, unknown>();\n key: string | undefined | null;\n file: File;\n opts: Partial<Options>;\n\n /**\n * The working directory that Babel's programmatic options are loaded\n * relative to.\n */\n cwd: string;\n\n /** The absolute path of the file being compiled. */\n filename: string | void;\n\n /**\n * Is Babel executed in async mode or not.\n */\n isAsync: boolean;\n\n constructor(\n file: File,\n key: string | null,\n options: Options | undefined,\n isAsync: boolean,\n ) {\n this.key = key;\n this.file = file;\n this.opts = options || {};\n this.cwd = file.opts.cwd;\n this.filename = file.opts.filename;\n this.isAsync = isAsync;\n }\n\n set(key: unknown, val: unknown) {\n this._map.set(key, val);\n }\n\n get(key: unknown): any {\n return this._map.get(key);\n }\n\n availableHelper(name: string, versionRange?: string | null) {\n return this.file.availableHelper(name, versionRange);\n }\n\n addHelper(name: string) {\n return this.file.addHelper(name);\n }\n\n buildCodeFrameError(\n node: t.Node | undefined | null,\n msg: string,\n _Error?: typeof Error,\n ) {\n return this.file.buildCodeFrameError(node, msg, _Error);\n }\n}\n"],"mappings":"AAGA,eAAe,MAAMA,UAAU,CAAmB;EAChDC,IAAI,GAAG,IAAIC,GAAG,CAAmB,CAAC;EAClCC,GAAG;EACHC,IAAI;EACJC,IAAI;EAMJC,GAAG;EAGHC,QAAQ;EAKRC,OAAO;EAEPC,WAAWA,CACTL,IAAU,EACVD,GAAkB,EAClBO,OAA4B,EAC5BF,OAAgB,EAChB;IACA,IAAI,CAACL,GAAG,GAAGA,GAAG;IACd,IAAI,CAACC,IAAI,GAAGA,IAAI;IAChB,IAAI,CAACC,IAAI,GAAGK,OAAO,IAAI,CAAC,CAAC;IACzB,IAAI,CAACJ,GAAG,GAAGF,IAAI,CAACC,IAAI,CAACC,GAAG;IACxB,IAAI,CAACC,QAAQ,GAAGH,IAAI,CAACC,IAAI,CAACE,QAAQ;IAClC,IAAI,CAACC,OAAO,GAAGA,OAAO;EACxB;EAEAG,GAAGA,CAACR,GAAY,EAAES,GAAY,EAAE;IAC9B,IAAI,CAACX,IAAI,CAACU,GAAG,CAACR,GAAG,EAAES,GAAG,CAAC;EACzB;EAEAC,GAAGA,CAACV,GAAY,EAAO;IACrB,OAAO,IAAI,CAACF,IAAI,CAACY,GAAG,CAACV,GAAG,CAAC;EAC3B;EAEAW,eAAeA,CAACC,IAAY,EAAEC,YAA4B,EAAE;IAC1D,OAAO,IAAI,CAACZ,IAAI,CAACU,eAAe,CAACC,IAAI,EAAEC,YAAY,CAAC;EACtD;EAEAC,SAASA,CAACF,IAAY,EAAE;IACtB,OAAO,IAAI,CAACX,IAAI,CAACa,SAAS,CAACF,IAAI,CAAC;EAClC;EAEAG,mBAAmBA,CACjBC,IAA+B,EAC/BC,GAAW,EACXC,MAAqB,EACrB;IACA,OAAO,IAAI,CAACjB,IAAI,CAACc,mBAAmB,CAACC,IAAI,EAAEC,GAAG,EAAEC,MAAM,CAAC;EACzD;AACF","ignoreList":[]} |
| const circleSet = new Set(); | ||
| let depth = 0; | ||
| function deepClone(value, cache, allowCircle) { | ||
| if (value !== null) { | ||
| if (allowCircle) { | ||
| if (cache.has(value)) return cache.get(value); | ||
| } else if (++depth > 250) { | ||
| if (circleSet.has(value)) { | ||
| depth = 0; | ||
| circleSet.clear(); | ||
| throw new Error("Babel-deepClone: Cycles are not allowed in AST"); | ||
| } | ||
| circleSet.add(value); | ||
| } | ||
| let cloned; | ||
| if (Array.isArray(value)) { | ||
| cloned = new Array(value.length); | ||
| if (allowCircle) cache.set(value, cloned); | ||
| for (let i = 0; i < value.length; i++) { | ||
| cloned[i] = typeof value[i] !== "object" ? value[i] : deepClone(value[i], cache, allowCircle); | ||
| } | ||
| } else { | ||
| cloned = {}; | ||
| if (allowCircle) cache.set(value, cloned); | ||
| const keys = Object.keys(value); | ||
| for (let i = 0; i < keys.length; i++) { | ||
| const key = keys[i]; | ||
| cloned[key] = typeof value[key] !== "object" ? value[key] : deepClone(value[key], cache, allowCircle || key === "leadingComments" || key === "innerComments" || key === "trailingComments" || key === "extra"); | ||
| } | ||
| } | ||
| if (!allowCircle) { | ||
| if (depth-- > 250) circleSet.delete(value); | ||
| } | ||
| return cloned; | ||
| } | ||
| return value; | ||
| } | ||
| export default function (value) { | ||
| if (typeof value !== "object") return value; | ||
| return deepClone(value, new Map(), false); | ||
| } | ||
| //# sourceMappingURL=clone-deep.js.map |
| {"version":3,"names":["circleSet","Set","depth","deepClone","value","cache","allowCircle","has","get","clear","Error","add","cloned","Array","isArray","length","set","i","keys","Object","key","delete","Map"],"sources":["../../../src/transformation/util/clone-deep.ts"],"sourcesContent":["const circleSet = new Set();\nlet depth = 0;\n// https://github.com/babel/babel/pull/14583#discussion_r882828856\nfunction deepClone(\n value: any,\n cache: Map<any, any>,\n allowCircle: boolean,\n): any {\n if (value !== null) {\n if (allowCircle) {\n if (cache.has(value)) return cache.get(value);\n } else if (++depth > 250) {\n if (circleSet.has(value)) {\n depth = 0;\n circleSet.clear();\n throw new Error(\"Babel-deepClone: Cycles are not allowed in AST\");\n }\n circleSet.add(value);\n }\n let cloned: any;\n if (Array.isArray(value)) {\n cloned = new Array(value.length);\n if (allowCircle) cache.set(value, cloned);\n for (let i = 0; i < value.length; i++) {\n cloned[i] =\n typeof value[i] !== \"object\"\n ? value[i]\n : deepClone(value[i], cache, allowCircle);\n }\n } else {\n cloned = {};\n if (allowCircle) cache.set(value, cloned);\n const keys = Object.keys(value);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n cloned[key] =\n typeof value[key] !== \"object\"\n ? value[key]\n : deepClone(\n value[key],\n cache,\n allowCircle ||\n key === \"leadingComments\" ||\n key === \"innerComments\" ||\n key === \"trailingComments\" ||\n key === \"extra\",\n );\n }\n }\n if (!allowCircle) {\n if (depth-- > 250) circleSet.delete(value);\n }\n return cloned;\n }\n return value;\n}\n\nexport default function <T>(value: T): T {\n if (typeof value !== \"object\") return value;\n\n if (!process.env.IS_PUBLISH && depth > 0) {\n throw new Error(\"depth > 0\");\n }\n return deepClone(value, new Map(), false);\n}\n"],"mappings":"AAAA,MAAMA,SAAS,GAAG,IAAIC,GAAG,CAAC,CAAC;AAC3B,IAAIC,KAAK,GAAG,CAAC;AAEb,SAASC,SAASA,CAChBC,KAAU,EACVC,KAAoB,EACpBC,WAAoB,EACf;EACL,IAAIF,KAAK,KAAK,IAAI,EAAE;IAClB,IAAIE,WAAW,EAAE;MACf,IAAID,KAAK,CAACE,GAAG,CAACH,KAAK,CAAC,EAAE,OAAOC,KAAK,CAACG,GAAG,CAACJ,KAAK,CAAC;IAC/C,CAAC,MAAM,IAAI,EAAEF,KAAK,GAAG,GAAG,EAAE;MACxB,IAAIF,SAAS,CAACO,GAAG,CAACH,KAAK,CAAC,EAAE;QACxBF,KAAK,GAAG,CAAC;QACTF,SAAS,CAACS,KAAK,CAAC,CAAC;QACjB,MAAM,IAAIC,KAAK,CAAC,gDAAgD,CAAC;MACnE;MACAV,SAAS,CAACW,GAAG,CAACP,KAAK,CAAC;IACtB;IACA,IAAIQ,MAAW;IACf,IAAIC,KAAK,CAACC,OAAO,CAACV,KAAK,CAAC,EAAE;MACxBQ,MAAM,GAAG,IAAIC,KAAK,CAACT,KAAK,CAACW,MAAM,CAAC;MAChC,IAAIT,WAAW,EAAED,KAAK,CAACW,GAAG,CAACZ,KAAK,EAAEQ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S,CAACC,KAAK,EAAE,IAAIkB,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC;AAC3C","ignoreList":[]} |
| /* c8 ignore start */ | ||
| import type { Handler } from "gensync"; | ||
| import type { | ||
| ConfigFile, | ||
| IgnoreFile, | ||
| RelativeConfig, | ||
| FilePackageData, | ||
| } from "./types.ts"; | ||
| import type { CallerMetadata } from "../validation/options.ts"; | ||
| export type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData }; | ||
| export function findConfigUpwards( | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| rootDir: string, | ||
| ): string | null { | ||
| return null; | ||
| } | ||
| // eslint-disable-next-line require-yield | ||
| export function* findPackageData(filepath: string): Handler<FilePackageData> { | ||
| return { | ||
| filepath, | ||
| directories: [], | ||
| pkg: null, | ||
| isPackage: false, | ||
| }; | ||
| } | ||
| // eslint-disable-next-line require-yield | ||
| export function* findRelativeConfig( | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| pkgData: FilePackageData, | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| envName: string, | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| caller: CallerMetadata | undefined, | ||
| ): Handler<RelativeConfig> { | ||
| return { config: null, ignore: null }; | ||
| } | ||
| // eslint-disable-next-line require-yield | ||
| export function* findRootConfig( | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| dirname: string, | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| envName: string, | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| caller: CallerMetadata | undefined, | ||
| ): Handler<ConfigFile | null> { | ||
| return null; | ||
| } | ||
| // eslint-disable-next-line require-yield | ||
| export function* loadConfig( | ||
| name: string, | ||
| dirname: string, | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| envName: string, | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| caller: CallerMetadata | undefined, | ||
| ): Handler<ConfigFile> { | ||
| throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`); | ||
| } | ||
| // eslint-disable-next-line require-yield | ||
| export function* resolveShowConfigPath( | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| dirname: string, | ||
| ): Handler<string | null> { | ||
| return null; | ||
| } | ||
| export const ROOT_CONFIG_FILENAMES: string[] = []; | ||
| type Resolved = | ||
| | { loader: "require"; filepath: string } | ||
| | { loader: "import"; filepath: string }; | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| export function resolvePlugin(name: string, dirname: string): Resolved | null { | ||
| return null; | ||
| } | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| export function resolvePreset(name: string, dirname: string): Resolved | null { | ||
| return null; | ||
| } | ||
| export function loadPlugin( | ||
| name: string, | ||
| dirname: string, | ||
| ): Handler<{ | ||
| filepath: string; | ||
| value: unknown; | ||
| }> { | ||
| throw new Error( | ||
| `Cannot load plugin ${name} relative to ${dirname} in a browser`, | ||
| ); | ||
| } | ||
| export function loadPreset( | ||
| name: string, | ||
| dirname: string, | ||
| ): Handler<{ | ||
| filepath: string; | ||
| value: unknown; | ||
| }> { | ||
| throw new Error( | ||
| `Cannot load preset ${name} relative to ${dirname} in a browser`, | ||
| ); | ||
| } |
| type indexBrowserType = typeof import("./index-browser"); | ||
| type indexType = typeof import("./index"); | ||
| // Kind of gross, but essentially asserting that the exports of this module are the same as the | ||
| // exports of index-browser, since this file may be replaced at bundle time with index-browser. | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-expressions | ||
| ({}) as any as indexBrowserType as indexType; | ||
| export { findPackageData } from "./package.ts"; | ||
| export { | ||
| findConfigUpwards, | ||
| findRelativeConfig, | ||
| findRootConfig, | ||
| loadConfig, | ||
| resolveShowConfigPath, | ||
| ROOT_CONFIG_FILENAMES, | ||
| } from "./configuration.ts"; | ||
| export type { | ||
| ConfigFile, | ||
| IgnoreFile, | ||
| RelativeConfig, | ||
| FilePackageData, | ||
| } from "./types.ts"; | ||
| export { | ||
| loadPlugin, | ||
| loadPreset, | ||
| resolvePlugin, | ||
| resolvePreset, | ||
| } from "./plugins.ts"; |
| /* c8 ignore start */ | ||
| import type { InputOptions } from "./validation/options.ts"; | ||
| import getTargets, { | ||
| type InputTargets, | ||
| } from "@babel/helper-compilation-targets"; | ||
| import type { Targets } from "@babel/helper-compilation-targets"; | ||
| export function resolveBrowserslistConfigFile( | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| browserslistConfigFile: string, | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| configFilePath: string, | ||
| ): string | void { | ||
| return undefined; | ||
| } | ||
| export function resolveTargets( | ||
| options: InputOptions, | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| root: string, | ||
| ): Targets { | ||
| const optTargets = options.targets; | ||
| let targets: InputTargets; | ||
| if (typeof optTargets === "string" || Array.isArray(optTargets)) { | ||
| targets = { browsers: optTargets }; | ||
| } else if (optTargets) { | ||
| // https://github.com/microsoft/TypeScript/issues/17002 | ||
| targets = optTargets as InputTargets; | ||
| } | ||
| return getTargets(targets, { | ||
| ignoreBrowserslistConfig: true, | ||
| browserslistEnv: options.browserslistEnv, | ||
| }); | ||
| } |
| type browserType = typeof import("./resolve-targets-browser"); | ||
| type nodeType = typeof import("./resolve-targets"); | ||
| // Kind of gross, but essentially asserting that the exports of this module are the same as the | ||
| // exports of index-browser, since this file may be replaced at bundle time with index-browser. | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-expressions | ||
| ({}) as any as browserType as nodeType; | ||
| import type { InputOptions } from "./validation/options.ts"; | ||
| import path from "node:path"; | ||
| import getTargets, { | ||
| type InputTargets, | ||
| } from "@babel/helper-compilation-targets"; | ||
| import type { Targets } from "@babel/helper-compilation-targets"; | ||
| export function resolveBrowserslistConfigFile( | ||
| browserslistConfigFile: string, | ||
| configFileDir: string, | ||
| ): string | undefined { | ||
| return path.resolve(configFileDir, browserslistConfigFile); | ||
| } | ||
| export function resolveTargets(options: InputOptions, root: string): Targets { | ||
| const optTargets = options.targets; | ||
| let targets: InputTargets; | ||
| if (typeof optTargets === "string" || Array.isArray(optTargets)) { | ||
| targets = { browsers: optTargets }; | ||
| } else if (optTargets) { | ||
| // https://github.com/microsoft/TypeScript/issues/17002 | ||
| targets = optTargets as InputTargets; | ||
| } | ||
| const { browserslistConfigFile } = options; | ||
| let configFile; | ||
| let ignoreBrowserslistConfig = false; | ||
| if (typeof browserslistConfigFile === "string") { | ||
| configFile = browserslistConfigFile; | ||
| } else { | ||
| ignoreBrowserslistConfig = browserslistConfigFile === false; | ||
| } | ||
| return getTargets(targets, { | ||
| ignoreBrowserslistConfig, | ||
| configFile, | ||
| configPath: root, | ||
| browserslistEnv: options.browserslistEnv, | ||
| }); | ||
| } |
| /* c8 ignore start */ | ||
| // duplicated from transform-file so we do not have to import anything here | ||
| type TransformFile = { | ||
| (filename: string, callback: (error: Error, file: null) => void): void; | ||
| ( | ||
| filename: string, | ||
| opts: any, | ||
| callback: (error: Error, file: null) => void, | ||
| ): void; | ||
| }; | ||
| export const transformFile: TransformFile = function transformFile( | ||
| filename, | ||
| opts, | ||
| callback?: (error: Error, file: null) => void, | ||
| ) { | ||
| if (typeof opts === "function") { | ||
| callback = opts; | ||
| } | ||
| callback(new Error("Transforming files is not supported in browsers"), null); | ||
| }; | ||
| export function transformFileSync(): never { | ||
| throw new Error("Transforming files is not supported in browsers"); | ||
| } | ||
| export function transformFileAsync() { | ||
| return Promise.reject( | ||
| new Error("Transforming files is not supported in browsers"), | ||
| ); | ||
| } |
| import gensync, { type Handler } from "gensync"; | ||
| import loadConfig from "./config/index.ts"; | ||
| import type { InputOptions, ResolvedConfig } from "./config/index.ts"; | ||
| import { run } from "./transformation/index.ts"; | ||
| import type { FileResult, FileResultCallback } from "./transformation/index.ts"; | ||
| import * as fs from "./gensync-utils/fs.ts"; | ||
| type transformFileBrowserType = typeof import("./transform-file-browser"); | ||
| type transformFileType = typeof import("./transform-file"); | ||
| // Kind of gross, but essentially asserting that the exports of this module are the same as the | ||
| // exports of transform-file-browser, since this file may be replaced at bundle time with | ||
| // transform-file-browser. | ||
| // eslint-disable-next-line @typescript-eslint/no-unused-expressions | ||
| ({}) as any as transformFileBrowserType as transformFileType; | ||
| const transformFileRunner = gensync(function* ( | ||
| filename: string, | ||
| opts?: InputOptions, | ||
| ): Handler<FileResult | null> { | ||
| const options = { ...opts, filename }; | ||
| const config: ResolvedConfig | null = yield* loadConfig(options); | ||
| if (config === null) return null; | ||
| const code = yield* fs.readFile(filename, "utf8"); | ||
| return yield* run(config, code); | ||
| }); | ||
| // @ts-expect-error TS doesn't detect that this signature is compatible | ||
| export function transformFile( | ||
| filename: string, | ||
| callback: FileResultCallback, | ||
| ): void; | ||
| export function transformFile( | ||
| filename: string, | ||
| opts: InputOptions | undefined | null, | ||
| callback: FileResultCallback, | ||
| ): void; | ||
| export function transformFile( | ||
| ...args: Parameters<typeof transformFileRunner.errback> | ||
| ) { | ||
| transformFileRunner.errback(...args); | ||
| } | ||
| export function transformFileSync( | ||
| ...args: Parameters<typeof transformFileRunner.sync> | ||
| ) { | ||
| return transformFileRunner.sync(...args); | ||
| } | ||
| export function transformFileAsync( | ||
| ...args: Parameters<typeof transformFileRunner.async> | ||
| ) { | ||
| return transformFileRunner.async(...args); | ||
| } |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 4 instances in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 4 instances in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
585648
-1.59%29
-75%4663
-6.83%21
90.91%1
Infinity%