4b55d0a522ff6574538b4a3ce21ff21dbca19a5ab47f69d207ab813d38899a65cf0d5e5afcf34f37b352d7d02990183727056d0ea4170148c3c05a6c522da7 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.ROOT_CONFIG_FILENAMES = void 0;
  6. exports.findConfigUpwards = findConfigUpwards;
  7. exports.findRelativeConfig = findRelativeConfig;
  8. exports.findRootConfig = findRootConfig;
  9. exports.loadConfig = loadConfig;
  10. exports.resolveShowConfigPath = resolveShowConfigPath;
  11. function _debug() {
  12. const data = require("debug");
  13. _debug = function () {
  14. return data;
  15. };
  16. return data;
  17. }
  18. function _fs() {
  19. const data = require("fs");
  20. _fs = function () {
  21. return data;
  22. };
  23. return data;
  24. }
  25. function _path() {
  26. const data = require("path");
  27. _path = function () {
  28. return data;
  29. };
  30. return data;
  31. }
  32. function _json() {
  33. const data = require("json5");
  34. _json = function () {
  35. return data;
  36. };
  37. return data;
  38. }
  39. function _gensync() {
  40. const data = require("gensync");
  41. _gensync = function () {
  42. return data;
  43. };
  44. return data;
  45. }
  46. var _caching = require("../caching.js");
  47. var _configApi = require("../helpers/config-api.js");
  48. var _utils = require("./utils.js");
  49. var _moduleTypes = require("./module-types.js");
  50. var _patternToRegex = require("../pattern-to-regex.js");
  51. var _configError = require("../../errors/config-error.js");
  52. var fs = require("../../gensync-utils/fs.js");
  53. require("module");
  54. var _rewriteStackTrace = require("../../errors/rewrite-stack-trace.js");
  55. var _async = require("../../gensync-utils/async.js");
  56. const debug = _debug()("babel:config:loading:files:configuration");
  57. const ROOT_CONFIG_FILENAMES = exports.ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json", "babel.config.cts"];
  58. const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json", ".babelrc.cts"];
  59. const BABELIGNORE_FILENAME = ".babelignore";
  60. const runConfig = (0, _caching.makeWeakCache)(function* runConfig(options, cache) {
  61. yield* [];
  62. return {
  63. options: (0, _rewriteStackTrace.endHiddenCallStack)(options)((0, _configApi.makeConfigAPI)(cache)),
  64. cacheNeedsConfiguration: !cache.configured()
  65. };
  66. });
  67. function* readConfigCode(filepath, data) {
  68. if (!_fs().existsSync(filepath)) return null;
  69. let options = yield* (0, _moduleTypes.default)(filepath, (yield* (0, _async.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.");
  70. let cacheNeedsConfiguration = false;
  71. if (typeof options === "function") {
  72. ({
  73. options,
  74. cacheNeedsConfiguration
  75. } = yield* runConfig(options, data));
  76. }
  77. if (!options || typeof options !== "object" || Array.isArray(options)) {
  78. throw new _configError.default(`Configuration should be an exported JavaScript object.`, filepath);
  79. }
  80. if (typeof options.then === "function") {
  81. options.catch == null || options.catch(() => {});
  82. throw new _configError.default(`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);
  83. }
  84. if (cacheNeedsConfiguration) throwConfigError(filepath);
  85. return buildConfigFileObject(options, filepath);
  86. }
  87. const cfboaf = new WeakMap();
  88. function buildConfigFileObject(options, filepath) {
  89. let configFilesByFilepath = cfboaf.get(options);
  90. if (!configFilesByFilepath) {
  91. cfboaf.set(options, configFilesByFilepath = new Map());
  92. }
  93. let configFile = configFilesByFilepath.get(filepath);
  94. if (!configFile) {
  95. configFile = {
  96. filepath,
  97. dirname: _path().dirname(filepath),
  98. options
  99. };
  100. configFilesByFilepath.set(filepath, configFile);
  101. }
  102. return configFile;
  103. }
  104. const packageToBabelConfig = (0, _caching.makeWeakCacheSync)(file => {
  105. const babel = file.options["babel"];
  106. if (babel === undefined) return null;
  107. if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
  108. throw new _configError.default(`.babel property must be an object`, file.filepath);
  109. }
  110. return {
  111. filepath: file.filepath,
  112. dirname: file.dirname,
  113. options: babel
  114. };
  115. });
  116. const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => {
  117. let options;
  118. try {
  119. options = _json().parse(content);
  120. } catch (err) {
  121. throw new _configError.default(`Error while parsing config - ${err.message}`, filepath);
  122. }
  123. if (!options) throw new _configError.default(`No config detected`, filepath);
  124. if (typeof options !== "object") {
  125. throw new _configError.default(`Config returned typeof ${typeof options}`, filepath);
  126. }
  127. if (Array.isArray(options)) {
  128. throw new _configError.default(`Expected config object but found array`, filepath);
  129. }
  130. delete options["$schema"];
  131. return {
  132. filepath,
  133. dirname: _path().dirname(filepath),
  134. options
  135. };
  136. });
  137. const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => {
  138. const ignoreDir = _path().dirname(filepath);
  139. const ignorePatterns = content.split("\n").map(line => line.replace(/#.*$/, "").trim()).filter(Boolean);
  140. for (const pattern of ignorePatterns) {
  141. if (pattern[0] === "!") {
  142. throw new _configError.default(`Negation of file paths is not supported.`, filepath);
  143. }
  144. }
  145. return {
  146. filepath,
  147. dirname: _path().dirname(filepath),
  148. ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir))
  149. };
  150. });
  151. function findConfigUpwards(rootDir) {
  152. let dirname = rootDir;
  153. for (;;) {
  154. for (const filename of ROOT_CONFIG_FILENAMES) {
  155. if (_fs().existsSync(_path().join(dirname, filename))) {
  156. return dirname;
  157. }
  158. }
  159. const nextDir = _path().dirname(dirname);
  160. if (dirname === nextDir) break;
  161. dirname = nextDir;
  162. }
  163. return null;
  164. }
  165. function* findRelativeConfig(packageData, envName, caller) {
  166. let config = null;
  167. let ignore = null;
  168. const dirname = _path().dirname(packageData.filepath);
  169. for (const loc of packageData.directories) {
  170. if (!config) {
  171. var _packageData$pkg;
  172. config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, ((_packageData$pkg = packageData.pkg) == null ? void 0 : _packageData$pkg.dirname) === loc ? packageToBabelConfig(packageData.pkg) : null);
  173. }
  174. if (!ignore) {
  175. const ignoreLoc = _path().join(loc, BABELIGNORE_FILENAME);
  176. ignore = yield* readIgnoreConfig(ignoreLoc);
  177. if (ignore) {
  178. debug("Found ignore %o from %o.", ignore.filepath, dirname);
  179. }
  180. }
  181. }
  182. return {
  183. config,
  184. ignore
  185. };
  186. }
  187. function findRootConfig(dirname, envName, caller) {
  188. return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller);
  189. }
  190. function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) {
  191. const configs = yield* _gensync().all(names.map(filename => readConfig(_path().join(dirname, filename), envName, caller)));
  192. const config = configs.reduce((previousConfig, config) => {
  193. if (config && previousConfig) {
  194. throw new _configError.default(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`);
  195. }
  196. return config || previousConfig;
  197. }, previousConfig);
  198. if (config) {
  199. debug("Found configuration %o from %o.", config.filepath, dirname);
  200. }
  201. return config;
  202. }
  203. function* loadConfig(name, dirname, envName, caller) {
  204. const filepath = (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, {
  205. paths: [b]
  206. }, M = require("module")) => {
  207. let f = M._findPath(r, M._nodeModulePaths(b).concat(b));
  208. if (f) return f;
  209. f = new Error(`Cannot resolve module '${r}'`);
  210. f.code = "MODULE_NOT_FOUND";
  211. throw f;
  212. })(name, {
  213. paths: [dirname]
  214. });
  215. const conf = yield* readConfig(filepath, envName, caller);
  216. if (!conf) {
  217. throw new _configError.default(`Config file contains no configuration data`, filepath);
  218. }
  219. debug("Loaded config %o from %o.", name, dirname);
  220. return conf;
  221. }
  222. function readConfig(filepath, envName, caller) {
  223. const ext = _path().extname(filepath);
  224. switch (ext) {
  225. case ".js":
  226. case ".cjs":
  227. case ".mjs":
  228. case ".ts":
  229. case ".cts":
  230. case ".mts":
  231. return readConfigCode(filepath, {
  232. envName,
  233. caller
  234. });
  235. default:
  236. return readConfigJSON5(filepath);
  237. }
  238. }
  239. function* resolveShowConfigPath(dirname) {
  240. const targetPath = process.env.BABEL_SHOW_CONFIG_FOR;
  241. if (targetPath != null) {
  242. const absolutePath = _path().resolve(dirname, targetPath);
  243. const stats = yield* fs.stat(absolutePath);
  244. if (!stats.isFile()) {
  245. throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`);
  246. }
  247. return absolutePath;
  248. }
  249. return null;
  250. }
  251. function throwConfigError(filepath) {
  252. throw new _configError.default(`\
  253. Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured
  254. for various types of caching, using the first param of their handler functions:
  255. module.exports = function(api) {
  256. // The API exposes the following:
  257. // Cache the returned value forever and don't call this function again.
  258. api.cache(true);
  259. // Don't cache at all. Not recommended because it will be very slow.
  260. api.cache(false);
  261. // Cached based on the value of some function. If this function returns a value different from
  262. // a previously-encountered value, the plugins will re-evaluate.
  263. var env = api.cache(() => process.env.NODE_ENV);
  264. // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for
  265. // any possible NODE_ENV value that might come up during plugin execution.
  266. var isProd = api.cache(() => process.env.NODE_ENV === "production");
  267. // .cache(fn) will perform a linear search though instances to find the matching plugin based
  268. // based on previous instantiated plugins. If you want to recreate the plugin and discard the
  269. // previous instance whenever something changes, you may use:
  270. var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production");
  271. // Note, we also expose the following more-verbose versions of the above examples:
  272. api.cache.forever(); // api.cache(true)
  273. api.cache.never(); // api.cache(false)
  274. api.cache.using(fn); // api.cache(fn)
  275. // Return the value that will be cached.
  276. return { };
  277. };`, filepath);
  278. }
  279. 0 && 0;
  280. //# sourceMappingURL=configuration.js.map