UNPKG

28.8 kBTypeScriptView Raw
1// Type definitions for @babel/core 7.1
2// Project: https://github.com/babel/babel/tree/master/packages/babel-core, https://babeljs.io
3// Definitions by: Troy Gerwien <https://github.com/yortus>
4// Marvin Hagemeister <https://github.com/marvinhagemeister>
5// Melvin Groenhoff <https://github.com/mgroenhoff>
6// Jessica Franco <https://github.com/Jessidhia>
7// Ifiok Jr. <https://github.com/ifiokjr>
8// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
9// Minimum TypeScript Version: 3.4
10
11import { GeneratorOptions } from '@babel/generator';
12import { ParserOptions } from '@babel/parser';
13import template from '@babel/template';
14import traverse, { Hub, NodePath, Scope, Visitor } from '@babel/traverse';
15import * as t from '@babel/types';
16
17export { ParserOptions, GeneratorOptions, t as types, template, traverse, NodePath, Visitor };
18
19export type Node = t.Node;
20export type ParseResult = ReturnType<typeof import('@babel/parser').parse>;
21export const version: string;
22export const DEFAULT_EXTENSIONS: ['.js', '.jsx', '.es6', '.es', '.mjs'];
23
24/**
25 * Source map standard format as to revision 3
26 * @see {@link https://sourcemaps.info/spec.html}
27 * @see {@link https://github.com/mozilla/source-map/blob/HEAD/source-map.d.ts}
28 */
29interface InputSourceMap {
30 version: number;
31 sources: string[];
32 names: string[];
33 sourceRoot?: string | undefined;
34 sourcesContent?: string[] | undefined;
35 mappings: string;
36 file: string;
37}
38
39export interface TransformOptions {
40 /**
41 * Specify which assumptions it can make about your code, to better optimize the compilation result. **NOTE**: This replaces the various `loose` options in plugins in favor of
42 * top-level options that can apply to multiple plugins
43 *
44 * @see https://babeljs.io/docs/en/assumptions
45 */
46 assumptions?: { [name: string]: boolean } | null | undefined;
47
48 /**
49 * Include the AST in the returned object
50 *
51 * Default: `false`
52 */
53 ast?: boolean | null | undefined;
54
55 /**
56 * Attach a comment after all non-user injected code
57 *
58 * Default: `null`
59 */
60 auxiliaryCommentAfter?: string | null | undefined;
61
62 /**
63 * Attach a comment before all non-user injected code
64 *
65 * Default: `null`
66 */
67 auxiliaryCommentBefore?: string | null | undefined;
68
69 /**
70 * Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow `.babelrc` files inside of.
71 *
72 * Default: `"."`
73 */
74 root?: string | null | undefined;
75
76 /**
77 * This option, combined with the "root" value, defines how Babel chooses its project root.
78 * The different modes define different ways that Babel can process the "root" value to get
79 * the final project root.
80 *
81 * @see https://babeljs.io/docs/en/next/options#rootmode
82 */
83 rootMode?: 'root' | 'upward' | 'upward-optional' | undefined;
84
85 /**
86 * The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files.
87 *
88 * Default: `undefined`
89 */
90 configFile?: string | boolean | null | undefined;
91
92 /**
93 * Specify whether or not to use .babelrc and
94 * .babelignore files.
95 *
96 * Default: `true`
97 */
98 babelrc?: boolean | null | undefined;
99
100 /**
101 * Specify which packages should be search for .babelrc files when they are being compiled. `true` to always search, or a path string or an array of paths to packages to search
102 * inside of. Defaults to only searching the "root" package.
103 *
104 * Default: `(root)`
105 */
106 babelrcRoots?: boolean | MatchPattern | MatchPattern[] | null | undefined;
107
108 /**
109 * Toggles whether or not browserslist config sources are used, which includes searching for any browserslist files or referencing the browserslist key inside package.json.
110 * This is useful for projects that use a browserslist config for files that won't be compiled with Babel.
111 *
112 * If a string is specified, it must represent the path of a browserslist configuration file. Relative paths are resolved relative to the configuration file which specifies
113 * this option, or to `cwd` when it's passed as part of the programmatic options.
114 *
115 * Default: `true`
116 */
117 browserslistConfigFile?: boolean | null | undefined;
118
119 /**
120 * The Browserslist environment to use.
121 *
122 * Default: `undefined`
123 */
124 browserslistEnv?: string | null | undefined;
125
126 /**
127 * By default `babel.transformFromAst` will clone the input AST to avoid mutations.
128 * Specifying `cloneInputAst: false` can improve parsing performance if the input AST is not used elsewhere.
129 *
130 * Default: `true`
131 */
132 cloneInputAst?: boolean | null | undefined;
133
134 /**
135 * Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"`
136 *
137 * Default: env vars
138 */
139 envName?: string | undefined;
140
141 /**
142 * If any of patterns match, the current configuration object is considered inactive and is ignored during config processing.
143 */
144 exclude?: MatchPattern | MatchPattern[] | undefined;
145
146 /**
147 * Enable code generation
148 *
149 * Default: `true`
150 */
151 code?: boolean | null | undefined;
152
153 /**
154 * Output comments in generated output
155 *
156 * Default: `true`
157 */
158 comments?: boolean | null | undefined;
159
160 /**
161 * Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB
162 *
163 * Default: `"auto"`
164 */
165 compact?: boolean | 'auto' | null | undefined;
166
167 /**
168 * The working directory that Babel's programmatic options are loaded relative to.
169 *
170 * Default: `"."`
171 */
172 cwd?: string | null | undefined;
173
174 /**
175 * Utilities may pass a caller object to identify themselves to Babel and
176 * pass capability-related flags for use by configs, presets and plugins.
177 *
178 * @see https://babeljs.io/docs/en/next/options#caller
179 */
180 caller?: TransformCaller | undefined;
181
182 /**
183 * This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { \/* specific options *\/ } } }`
184 * which will use those options when the `envName` is `production`
185 *
186 * Default: `{}`
187 */
188 env?: { [index: string]: TransformOptions | null | undefined } | null | undefined;
189
190 /**
191 * A path to a `.babelrc` file to extend
192 *
193 * Default: `null`
194 */
195 extends?: string | null | undefined;
196
197 /**
198 * Filename for use in errors etc
199 *
200 * Default: `"unknown"`
201 */
202 filename?: string | null | undefined;
203
204 /**
205 * Filename relative to `sourceRoot`
206 *
207 * Default: `(filename)`
208 */
209 filenameRelative?: string | null | undefined;
210
211 /**
212 * An object containing the options to be passed down to the babel code generator, @babel/generator
213 *
214 * Default: `{}`
215 */
216 generatorOpts?: GeneratorOptions | null | undefined;
217
218 /**
219 * Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used
220 *
221 * Default: `null`
222 */
223 getModuleId?: ((moduleName: string) => string | null | undefined) | null | undefined;
224
225 /**
226 * ANSI highlight syntax error code frames
227 *
228 * Default: `true`
229 */
230 highlightCode?: boolean | null | undefined;
231
232 /**
233 * Opposite to the `only` option. `ignore` is disregarded if `only` is specified
234 *
235 * Default: `null`
236 */
237 ignore?: MatchPattern[] | null | undefined;
238
239 /**
240 * This option is a synonym for "test"
241 */
242 include?: MatchPattern | MatchPattern[] | undefined;
243
244 /**
245 * A source map object that the output source map will be based on
246 *
247 * Default: `null`
248 */
249 inputSourceMap?: InputSourceMap | null | undefined;
250
251 /**
252 * Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe)
253 *
254 * Default: `false`
255 */
256 minified?: boolean | null | undefined;
257
258 /**
259 * Specify a custom name for module ids
260 *
261 * Default: `null`
262 */
263 moduleId?: string | null | undefined;
264
265 /**
266 * If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules)
267 *
268 * Default: `false`
269 */
270 moduleIds?: boolean | null | undefined;
271
272 /**
273 * Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions
274 *
275 * Default: `(sourceRoot)`
276 */
277 moduleRoot?: string | null | undefined;
278
279 /**
280 * A glob, regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile
281 * a non-matching file it's returned verbatim
282 *
283 * Default: `null`
284 */
285 only?: MatchPattern[] | null | undefined;
286
287 /**
288 * Allows users to provide an array of options that will be merged into the current configuration one at a time.
289 * This feature is best used alongside the "test"/"include"/"exclude" options to provide conditions for which an override should apply
290 */
291 overrides?: TransformOptions[] | undefined;
292
293 /**
294 * An object containing the options to be passed down to the babel parser, @babel/parser
295 *
296 * Default: `{}`
297 */
298 parserOpts?: ParserOptions | null | undefined;
299
300 /**
301 * List of plugins to load and use
302 *
303 * Default: `[]`
304 */
305 plugins?: PluginItem[] | null | undefined;
306
307 /**
308 * List of presets (a set of plugins) to load and use
309 *
310 * Default: `[]`
311 */
312 presets?: PluginItem[] | null | undefined;
313
314 /**
315 * Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE**: This will not retain the columns)
316 *
317 * Default: `false`
318 */
319 retainLines?: boolean | null | undefined;
320
321 /**
322 * An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comment` option when used
323 *
324 * Default: `null`
325 */
326 shouldPrintComment?: ((commentContents: string) => boolean) | null | undefined;
327
328 /**
329 * Set `sources[0]` on returned source map
330 *
331 * Default: `(filenameRelative)`
332 */
333 sourceFileName?: string | null | undefined;
334
335 /**
336 * If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"`
337 * then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!**
338 *
339 * Default: `false`
340 */
341 sourceMaps?: boolean | 'inline' | 'both' | null | undefined;
342
343 /**
344 * The root from which all sources are relative
345 *
346 * Default: `(moduleRoot)`
347 */
348 sourceRoot?: string | null | undefined;
349
350 /**
351 * Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". `"unambiguous"` will make Babel attempt to guess, based on the presence of ES6
352 * `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`.
353 *
354 * Default: `("module")`
355 */
356 sourceType?: 'script' | 'module' | 'unambiguous' | null | undefined;
357
358 /**
359 * If all patterns fail to match, the current configuration object is considered inactive and is ignored during config processing.
360 */
361 test?: MatchPattern | MatchPattern[] | undefined;
362
363 /**
364 * An optional callback that can be used to wrap visitor methods. **NOTE**: This is useful for things like introspection, and not really needed for implementing anything. Called as
365 * `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`.
366 */
367 wrapPluginVisitorMethod?:
368 | ((
369 pluginAlias: string,
370 visitorType: 'enter' | 'exit',
371 callback: (path: NodePath, state: any) => void,
372 ) => (path: NodePath, state: any) => void)
373 | null | undefined;
374}
375
376export interface TransformCaller {
377 // the only required property
378 name: string;
379 // e.g. set to true by `babel-loader` and false by `babel-jest`
380 supportsStaticESM?: boolean | undefined;
381 supportsDynamicImport?: boolean | undefined;
382 supportsExportNamespaceFrom?: boolean | undefined;
383 supportsTopLevelAwait?: boolean | undefined;
384 // augment this with a "declare module '@babel/core' { ... }" if you need more keys
385}
386
387export type FileResultCallback = (err: Error | null, result: BabelFileResult | null) => any;
388
389export interface MatchPatternContext {
390 envName: string;
391 dirname: string;
392 caller: TransformCaller | undefined;
393}
394export type MatchPattern = string | RegExp | ((filename: string | undefined, context: MatchPatternContext) => boolean);
395
396/**
397 * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
398 */
399export function transform(code: string, callback: FileResultCallback): void;
400
401/**
402 * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
403 */
404export function transform(code: string, opts: TransformOptions | undefined, callback: FileResultCallback): void;
405
406/**
407 * Here for backward-compatibility. Ideally use `transformSync` if you want a synchronous API.
408 */
409export function transform(code: string, opts?: TransformOptions): BabelFileResult | null;
410
411/**
412 * Transforms the passed in code. Returning an object with the generated code, source map, and AST.
413 */
414export function transformSync(code: string, opts?: TransformOptions): BabelFileResult | null;
415
416/**
417 * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
418 */
419export function transformAsync(code: string, opts?: TransformOptions): Promise<BabelFileResult | null>;
420
421/**
422 * Asynchronously transforms the entire contents of a file.
423 */
424export function transformFile(filename: string, callback: FileResultCallback): void;
425
426/**
427 * Asynchronously transforms the entire contents of a file.
428 */
429export function transformFile(filename: string, opts: TransformOptions | undefined, callback: FileResultCallback): void;
430
431/**
432 * Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`.
433 */
434export function transformFileSync(filename: string, opts?: TransformOptions): BabelFileResult | null;
435
436/**
437 * Asynchronously transforms the entire contents of a file.
438 */
439export function transformFileAsync(filename: string, opts?: TransformOptions): Promise<BabelFileResult | null>;
440
441/**
442 * Given an AST, transform it.
443 */
444export function transformFromAst(ast: Node, code: string | undefined, callback: FileResultCallback): void;
445
446/**
447 * Given an AST, transform it.
448 */
449export function transformFromAst(
450 ast: Node,
451 code: string | undefined,
452 opts: TransformOptions | undefined,
453 callback: FileResultCallback,
454): void;
455
456/**
457 * Here for backward-compatibility. Ideally use ".transformSync" if you want a synchronous API.
458 */
459export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult | null;
460
461/**
462 * Given an AST, transform it.
463 */
464export function transformFromAstAsync(
465 ast: Node,
466 code?: string,
467 opts?: TransformOptions,
468): Promise<BabelFileResult | null>;
469
470// A babel plugin is a simple function which must return an object matching
471// the following interface. Babel will throw if it finds unknown properties.
472// The list of allowed plugin keys is here:
473// https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-core/src/config/option-manager.js#L71
474export interface PluginObj<S = PluginPass> {
475 name?: string | undefined;
476 manipulateOptions?(opts: any, parserOpts: any): void;
477 pre?(this: S, file: BabelFile): void;
478 visitor: Visitor<S>;
479 post?(this: S, file: BabelFile): void;
480 inherits?: any;
481}
482
483export interface BabelFile {
484 ast: t.File;
485 opts: TransformOptions;
486 hub: Hub;
487 metadata: object;
488 path: NodePath<t.Program>;
489 scope: Scope;
490 inputMap: object | null;
491 code: string;
492}
493
494export interface PluginPass {
495 file: BabelFile;
496 key: string;
497 opts: object;
498 cwd: string;
499 filename: string | undefined;
500 get(key: unknown): any;
501 set(key: unknown, value: unknown): void;
502 [key: string]: unknown;
503}
504
505export interface BabelFileResult {
506 ast?: t.File | null | undefined;
507 code?: string | null | undefined;
508 ignored?: boolean | undefined;
509 map?: {
510 version: number;
511 sources: string[];
512 names: string[];
513 sourceRoot?: string | undefined;
514 sourcesContent?: string[] | undefined;
515 mappings: string;
516 file: string;
517 } | null | undefined;
518 metadata?: BabelFileMetadata | undefined;
519}
520
521export interface BabelFileMetadata {
522 usedHelpers: string[];
523 marked: Array<{
524 type: string;
525 message: string;
526 loc: object;
527 }>;
528 modules: BabelFileModulesMetadata;
529}
530
531export interface BabelFileModulesMetadata {
532 imports: object[];
533 exports: {
534 exported: object[];
535 specifiers: object[];
536 };
537}
538
539export type FileParseCallback = (err: Error | null, result: ParseResult | null) => any;
540
541/**
542 * Given some code, parse it using Babel's standard behavior.
543 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
544 */
545export function parse(code: string, callback: FileParseCallback): void;
546
547/**
548 * Given some code, parse it using Babel's standard behavior.
549 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
550 */
551export function parse(code: string, options: TransformOptions | undefined, callback: FileParseCallback): void;
552
553/**
554 * Given some code, parse it using Babel's standard behavior.
555 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
556 */
557export function parse(code: string, options?: TransformOptions): ParseResult | null;
558
559/**
560 * Given some code, parse it using Babel's standard behavior.
561 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
562 */
563export function parseSync(code: string, options?: TransformOptions): ParseResult | null;
564
565/**
566 * Given some code, parse it using Babel's standard behavior.
567 * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
568 */
569export function parseAsync(code: string, options?: TransformOptions): Promise<ParseResult | null>;
570
571/**
572 * Resolve Babel's options fully, resulting in an options object where:
573 *
574 * * opts.plugins is a full list of Plugin instances.
575 * * opts.presets is empty and all presets are flattened into opts.
576 * * It can be safely passed back to Babel. Fields like babelrc have been set to false so that later calls to Babel
577 * will not make a second attempt to load config files.
578 *
579 * Plugin instances aren't meant to be manipulated directly, but often callers will serialize this opts to JSON to
580 * use it as a cache key representing the options Babel has received. Caching on this isn't 100% guaranteed to
581 * invalidate properly, but it is the best we have at the moment.
582 */
583export function loadOptions(options?: TransformOptions): object | null;
584
585/**
586 * To allow systems to easily manipulate and validate a user's config, this function resolves the plugins and
587 * presets and proceeds no further. The expectation is that callers will take the config's .options, manipulate it
588 * as then see fit and pass it back to Babel again.
589 *
590 * * `babelrc: string | void` - The path of the `.babelrc` file, if there was one.
591 * * `babelignore: string | void` - The path of the `.babelignore` file, if there was one.
592 * * `options: ValidatedOptions` - The partially resolved options, which can be manipulated and passed back
593 * to Babel again.
594 * * `plugins: Array<ConfigItem>` - See below.
595 * * `presets: Array<ConfigItem>` - See below.
596 * * It can be safely passed back to Babel. Fields like `babelrc` have been set to false so that later calls to
597 * Babel will not make a second attempt to load config files.
598 *
599 * `ConfigItem` instances expose properties to introspect the values, but each item should be treated as
600 * immutable. If changes are desired, the item should be removed from the list and replaced with either a normal
601 * Babel config value, or with a replacement item created by `babel.createConfigItem`. See that function for
602 * information about `ConfigItem` fields.
603 */
604export function loadPartialConfig(options?: TransformOptions): Readonly<PartialConfig> | null;
605export function loadPartialConfigAsync(options?: TransformOptions): Promise<Readonly<PartialConfig> | null>;
606
607export interface PartialConfig {
608 options: TransformOptions;
609 babelrc?: string | undefined;
610 babelignore?: string | undefined;
611 config?: string | undefined;
612 hasFilesystemConfig: () => boolean;
613}
614
615export interface ConfigItem {
616 /**
617 * The name that the user gave the plugin instance, e.g. `plugins: [ ['env', {}, 'my-env'] ]`
618 */
619 name?: string | undefined;
620
621 /**
622 * The resolved value of the plugin.
623 */
624 value: object | ((...args: any[]) => any);
625
626 /**
627 * The options object passed to the plugin.
628 */
629 options?: object | false | undefined;
630
631 /**
632 * The path that the options are relative to.
633 */
634 dirname: string;
635
636 /**
637 * Information about the plugin's file, if Babel knows it.
638 * *
639 */
640 file?: {
641 /**
642 * The file that the user requested, e.g. `"@babel/env"`
643 */
644 request: string;
645
646 /**
647 * The full path of the resolved file, e.g. `"/tmp/node_modules/@babel/preset-env/lib/index.js"`
648 */
649 resolved: string;
650 } | null | undefined;
651}
652
653export type PluginOptions = object | undefined | false;
654
655export type PluginTarget = string | object | ((...args: any[]) => any);
656
657export type PluginItem =
658 | ConfigItem
659 | PluginObj<any>
660 | PluginTarget
661 | [PluginTarget, PluginOptions]
662 | [PluginTarget, PluginOptions, string | undefined];
663
664export function resolvePlugin(name: string, dirname: string): string | null;
665export function resolvePreset(name: string, dirname: string): string | null;
666
667export interface CreateConfigItemOptions {
668 dirname?: string | undefined;
669 type?: 'preset' | 'plugin' | undefined;
670}
671
672/**
673 * Allows build tooling to create and cache config items up front. If this function is called multiple times for a
674 * given plugin, Babel will call the plugin's function itself multiple times. If you have a clear set of expected
675 * plugins and presets to inject, pre-constructing the config items would be recommended.
676 */
677export function createConfigItem(
678 value: PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined],
679 options?: CreateConfigItemOptions,
680): ConfigItem;
681
682// NOTE: the documentation says the ConfigAPI also exposes @babel/core's exports, but it actually doesn't
683/**
684 * @see https://babeljs.io/docs/en/next/config-files#config-function-api
685 */
686export interface ConfigAPI {
687 /**
688 * The version string for the Babel version that is loading the config file.
689 *
690 * @see https://babeljs.io/docs/en/next/config-files#apiversion
691 */
692 version: string;
693 /**
694 * @see https://babeljs.io/docs/en/next/config-files#apicache
695 */
696 cache: SimpleCacheConfigurator;
697 /**
698 * @see https://babeljs.io/docs/en/next/config-files#apienv
699 */
700 env: EnvFunction;
701 // undocumented; currently hardcoded to return 'false'
702 // async(): boolean
703 /**
704 * This API is used as a way to access the `caller` data that has been passed to Babel.
705 * Since many instances of Babel may be running in the same process with different `caller` values,
706 * this API is designed to automatically configure `api.cache`, the same way `api.env()` does.
707 *
708 * The `caller` value is available as the first parameter of the callback function.
709 * It is best used with something like this to toggle configuration behavior
710 * based on a specific environment:
711 *
712 * @example
713 * function isBabelRegister(caller?: { name: string }) {
714 * return !!(caller && caller.name === "@babel/register")
715 * }
716 * api.caller(isBabelRegister)
717 *
718 * @see https://babeljs.io/docs/en/next/config-files#apicallercb
719 */
720 caller<T extends SimpleCacheKey>(callerCallback: (caller: TransformOptions['caller']) => T): T;
721 /**
722 * While `api.version` can be useful in general, it's sometimes nice to just declare your version.
723 * This API exposes a simple way to do that with:
724 *
725 * @example
726 * api.assertVersion(7) // major version only
727 * api.assertVersion("^7.2")
728 *
729 * @see https://babeljs.io/docs/en/next/config-files#apiassertversionrange
730 */
731 assertVersion(versionRange: number | string): boolean;
732 // NOTE: this is an undocumented reexport from "@babel/parser" but it's missing from its types
733 // tokTypes: typeof tokTypes
734}
735
736/**
737 * JS configs are great because they can compute a config on the fly,
738 * but the downside there is that it makes caching harder.
739 * Babel wants to avoid re-executing the config function every time a file is compiled,
740 * because then it would also need to re-execute any plugin and preset functions
741 * referenced in that config.
742 *
743 * To avoid this, Babel expects users of config functions to tell it how to manage caching
744 * within a config file.
745 *
746 * @see https://babeljs.io/docs/en/next/config-files#apicache
747 */
748export interface SimpleCacheConfigurator {
749 // there is an undocumented call signature that is a shorthand for forever()/never()/using().
750 // (ever: boolean): void
751 // <T extends SimpleCacheKey>(callback: CacheCallback<T>): T
752 /**
753 * Permacache the computed config and never call the function again.
754 */
755 forever(): void;
756 /**
757 * Do not cache this config, and re-execute the function every time.
758 */
759 never(): void;
760 /**
761 * Any time the using callback returns a value other than the one that was expected,
762 * the overall config function will be called again and a new entry will be added to the cache.
763 *
764 * @example
765 * api.cache.using(() => process.env.NODE_ENV)
766 */
767 using<T extends SimpleCacheKey>(callback: SimpleCacheCallback<T>): T;
768 /**
769 * Any time the using callback returns a value other than the one that was expected,
770 * the overall config function will be called again and all entries in the cache will
771 * be replaced with the result.
772 *
773 * @example
774 * api.cache.invalidate(() => process.env.NODE_ENV)
775 */
776 invalidate<T extends SimpleCacheKey>(callback: SimpleCacheCallback<T>): T;
777}
778
779// https://github.com/babel/babel/blob/v7.3.3/packages/babel-core/src/config/caching.js#L231
780export type SimpleCacheKey = string | boolean | number | null | undefined;
781export type SimpleCacheCallback<T extends SimpleCacheKey> = () => T;
782
783/**
784 * Since `NODE_ENV` is a fairly common way to toggle behavior, Babel also includes an API function
785 * meant specifically for that. This API is used as a quick way to check the `"envName"` that Babel
786 * was loaded with, which takes `NODE_ENV` into account if no other overriding environment is set.
787 *
788 * @see https://babeljs.io/docs/en/next/config-files#apienv
789 */
790export interface EnvFunction {
791 /**
792 * @returns the current `envName` string
793 */
794 (): string;
795 /**
796 * @returns `true` if the `envName` is `===` any of the given strings
797 */
798 (envName: string | ReadonlyArray<string>): boolean;
799 // the official documentation is misleading for this one...
800 // this just passes the callback to `cache.using` but with an additional argument.
801 // it returns its result instead of necessarily returning a boolean.
802 <T extends SimpleCacheKey>(envCallback: (envName: NonNullable<TransformOptions['envName']>) => T): T;
803}
804
805export type ConfigFunction = (api: ConfigAPI) => TransformOptions;
806
807export as namespace babel;