index.node.mjs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. import { declare } from '@babel/helper-plugin-utils';
  2. import _getTargets, { prettifyTargets, getInclusionReasons, isRequired } from '@babel/helper-compilation-targets';
  3. import * as _babel from '@babel/core';
  4. import path from 'path';
  5. import debounce from 'lodash.debounce';
  6. import requireResolve from 'resolve';
  7. import { createRequire } from 'module';
  8. const {
  9. types: t$1,
  10. template: template
  11. } = _babel.default || _babel;
  12. function intersection(a, b) {
  13. const result = new Set();
  14. a.forEach(v => b.has(v) && result.add(v));
  15. return result;
  16. }
  17. function has$1(object, key) {
  18. return Object.prototype.hasOwnProperty.call(object, key);
  19. }
  20. function resolve$1(path, resolved = new Set()) {
  21. if (resolved.has(path)) return;
  22. resolved.add(path);
  23. if (path.isVariableDeclarator()) {
  24. if (path.get("id").isIdentifier()) {
  25. return resolve$1(path.get("init"), resolved);
  26. }
  27. } else if (path.isReferencedIdentifier()) {
  28. const binding = path.scope.getBinding(path.node.name);
  29. if (!binding) return path;
  30. if (!binding.constant) return;
  31. return resolve$1(binding.path, resolved);
  32. }
  33. return path;
  34. }
  35. function resolveId(path) {
  36. if (path.isIdentifier() && !path.scope.hasBinding(path.node.name, /* noGlobals */true)) {
  37. return path.node.name;
  38. }
  39. const resolved = resolve$1(path);
  40. if (resolved != null && resolved.isIdentifier()) {
  41. return resolved.node.name;
  42. }
  43. }
  44. function resolveKey(path, computed = false) {
  45. const {
  46. scope
  47. } = path;
  48. if (path.isStringLiteral()) return path.node.value;
  49. const isIdentifier = path.isIdentifier();
  50. if (isIdentifier && !(computed || path.parent.computed)) {
  51. return path.node.name;
  52. }
  53. if (computed && path.isMemberExpression() && path.get("object").isIdentifier({
  54. name: "Symbol"
  55. }) && !scope.hasBinding("Symbol", /* noGlobals */true)) {
  56. const sym = resolveKey(path.get("property"), path.node.computed);
  57. if (sym) return "Symbol." + sym;
  58. }
  59. if (isIdentifier ? scope.hasBinding(path.node.name, /* noGlobals */true) : path.isPure()) {
  60. const {
  61. value
  62. } = path.evaluate();
  63. if (typeof value === "string") return value;
  64. }
  65. }
  66. function resolveSource(obj) {
  67. if (obj.isMemberExpression() && obj.get("property").isIdentifier({
  68. name: "prototype"
  69. })) {
  70. const id = resolveId(obj.get("object"));
  71. if (id) {
  72. return {
  73. id,
  74. placement: "prototype"
  75. };
  76. }
  77. return {
  78. id: null,
  79. placement: null
  80. };
  81. }
  82. const id = resolveId(obj);
  83. if (id) {
  84. return {
  85. id,
  86. placement: "static"
  87. };
  88. }
  89. const path = resolve$1(obj);
  90. switch (path == null ? void 0 : path.type) {
  91. case "RegExpLiteral":
  92. return {
  93. id: "RegExp",
  94. placement: "prototype"
  95. };
  96. case "FunctionExpression":
  97. return {
  98. id: "Function",
  99. placement: "prototype"
  100. };
  101. case "StringLiteral":
  102. return {
  103. id: "String",
  104. placement: "prototype"
  105. };
  106. case "NumberLiteral":
  107. return {
  108. id: "Number",
  109. placement: "prototype"
  110. };
  111. case "BooleanLiteral":
  112. return {
  113. id: "Boolean",
  114. placement: "prototype"
  115. };
  116. case "ObjectExpression":
  117. return {
  118. id: "Object",
  119. placement: "prototype"
  120. };
  121. case "ArrayExpression":
  122. return {
  123. id: "Array",
  124. placement: "prototype"
  125. };
  126. }
  127. return {
  128. id: null,
  129. placement: null
  130. };
  131. }
  132. function getImportSource({
  133. node
  134. }) {
  135. if (node.specifiers.length === 0) return node.source.value;
  136. }
  137. function getRequireSource({
  138. node
  139. }) {
  140. if (!t$1.isExpressionStatement(node)) return;
  141. const {
  142. expression
  143. } = node;
  144. if (t$1.isCallExpression(expression) && t$1.isIdentifier(expression.callee) && expression.callee.name === "require" && expression.arguments.length === 1 && t$1.isStringLiteral(expression.arguments[0])) {
  145. return expression.arguments[0].value;
  146. }
  147. }
  148. function hoist(node) {
  149. // @ts-expect-error
  150. node._blockHoist = 3;
  151. return node;
  152. }
  153. function createUtilsGetter(cache) {
  154. return path => {
  155. const prog = path.findParent(p => p.isProgram());
  156. return {
  157. injectGlobalImport(url, moduleName) {
  158. cache.storeAnonymous(prog, url, moduleName, (isScript, source) => {
  159. return isScript ? template.statement.ast`require(${source})` : t$1.importDeclaration([], source);
  160. });
  161. },
  162. injectNamedImport(url, name, hint = name, moduleName) {
  163. return cache.storeNamed(prog, url, name, moduleName, (isScript, source, name) => {
  164. const id = prog.scope.generateUidIdentifier(hint);
  165. return {
  166. node: isScript ? hoist(template.statement.ast`
  167. var ${id} = require(${source}).${name}
  168. `) : t$1.importDeclaration([t$1.importSpecifier(id, name)], source),
  169. name: id.name
  170. };
  171. });
  172. },
  173. injectDefaultImport(url, hint = url, moduleName) {
  174. return cache.storeNamed(prog, url, "default", moduleName, (isScript, source) => {
  175. const id = prog.scope.generateUidIdentifier(hint);
  176. return {
  177. node: isScript ? hoist(template.statement.ast`var ${id} = require(${source})`) : t$1.importDeclaration([t$1.importDefaultSpecifier(id)], source),
  178. name: id.name
  179. };
  180. });
  181. }
  182. };
  183. };
  184. }
  185. const {
  186. types: t
  187. } = _babel.default || _babel;
  188. class ImportsCachedInjector {
  189. constructor(resolver, getPreferredIndex) {
  190. this._imports = new WeakMap();
  191. this._anonymousImports = new WeakMap();
  192. this._lastImports = new WeakMap();
  193. this._resolver = resolver;
  194. this._getPreferredIndex = getPreferredIndex;
  195. }
  196. storeAnonymous(programPath, url, moduleName, getVal) {
  197. const key = this._normalizeKey(programPath, url);
  198. const imports = this._ensure(this._anonymousImports, programPath, Set);
  199. if (imports.has(key)) return;
  200. const node = getVal(programPath.node.sourceType === "script", t.stringLiteral(this._resolver(url)));
  201. imports.add(key);
  202. this._injectImport(programPath, node, moduleName);
  203. }
  204. storeNamed(programPath, url, name, moduleName, getVal) {
  205. const key = this._normalizeKey(programPath, url, name);
  206. const imports = this._ensure(this._imports, programPath, Map);
  207. if (!imports.has(key)) {
  208. const {
  209. node,
  210. name: id
  211. } = getVal(programPath.node.sourceType === "script", t.stringLiteral(this._resolver(url)), t.identifier(name));
  212. imports.set(key, id);
  213. this._injectImport(programPath, node, moduleName);
  214. }
  215. return t.identifier(imports.get(key));
  216. }
  217. _injectImport(programPath, node, moduleName) {
  218. var _this$_lastImports$ge;
  219. const newIndex = this._getPreferredIndex(moduleName);
  220. const lastImports = (_this$_lastImports$ge = this._lastImports.get(programPath)) != null ? _this$_lastImports$ge : [];
  221. const isPathStillValid = path => path.node &&
  222. // Sometimes the AST is modified and the "last import"
  223. // we have has been replaced
  224. path.parent === programPath.node && path.container === programPath.node.body;
  225. let last;
  226. if (newIndex === Infinity) {
  227. // Fast path: we can always just insert at the end if newIndex is `Infinity`
  228. if (lastImports.length > 0) {
  229. last = lastImports[lastImports.length - 1].path;
  230. if (!isPathStillValid(last)) last = undefined;
  231. }
  232. } else {
  233. for (const [i, data] of lastImports.entries()) {
  234. const {
  235. path,
  236. index
  237. } = data;
  238. if (isPathStillValid(path)) {
  239. if (newIndex < index) {
  240. const [newPath] = path.insertBefore(node);
  241. lastImports.splice(i, 0, {
  242. path: newPath,
  243. index: newIndex
  244. });
  245. return;
  246. }
  247. last = path;
  248. }
  249. }
  250. }
  251. if (last) {
  252. const [newPath] = last.insertAfter(node);
  253. lastImports.push({
  254. path: newPath,
  255. index: newIndex
  256. });
  257. } else {
  258. const [newPath] = programPath.unshiftContainer("body", [node]);
  259. this._lastImports.set(programPath, [{
  260. path: newPath,
  261. index: newIndex
  262. }]);
  263. }
  264. }
  265. _ensure(map, programPath, Collection) {
  266. let collection = map.get(programPath);
  267. if (!collection) {
  268. collection = new Collection();
  269. map.set(programPath, collection);
  270. }
  271. return collection;
  272. }
  273. _normalizeKey(programPath, url, name = "") {
  274. const {
  275. sourceType
  276. } = programPath.node;
  277. // If we rely on the imported binding (the "name" parameter), we also need to cache
  278. // based on the sourceType. This is because the module transforms change the names
  279. // of the import variables.
  280. return `${name && sourceType}::${url}::${name}`;
  281. }
  282. }
  283. const presetEnvSilentDebugHeader = "#__secret_key__@babel/preset-env__don't_log_debug_header_and_resolved_targets";
  284. function stringifyTargetsMultiline(targets) {
  285. return JSON.stringify(prettifyTargets(targets), null, 2);
  286. }
  287. function patternToRegExp(pattern) {
  288. if (pattern instanceof RegExp) return pattern;
  289. try {
  290. return new RegExp(`^${pattern}$`);
  291. } catch {
  292. return null;
  293. }
  294. }
  295. function buildUnusedError(label, unused) {
  296. if (!unused.length) return "";
  297. return ` - The following "${label}" patterns didn't match any polyfill:\n` + unused.map(original => ` ${String(original)}\n`).join("");
  298. }
  299. function buldDuplicatesError(duplicates) {
  300. if (!duplicates.size) return "";
  301. return ` - The following polyfills were matched both by "include" and "exclude" patterns:\n` + Array.from(duplicates, name => ` ${name}\n`).join("");
  302. }
  303. function validateIncludeExclude(provider, polyfills, includePatterns, excludePatterns) {
  304. let current;
  305. const filter = pattern => {
  306. const regexp = patternToRegExp(pattern);
  307. if (!regexp) return false;
  308. let matched = false;
  309. for (const polyfill of polyfills.keys()) {
  310. if (regexp.test(polyfill)) {
  311. matched = true;
  312. current.add(polyfill);
  313. }
  314. }
  315. return !matched;
  316. };
  317. // prettier-ignore
  318. const include = current = new Set();
  319. const unusedInclude = Array.from(includePatterns).filter(filter);
  320. // prettier-ignore
  321. const exclude = current = new Set();
  322. const unusedExclude = Array.from(excludePatterns).filter(filter);
  323. const duplicates = intersection(include, exclude);
  324. if (duplicates.size > 0 || unusedInclude.length > 0 || unusedExclude.length > 0) {
  325. throw new Error(`Error while validating the "${provider}" provider options:\n` + buildUnusedError("include", unusedInclude) + buildUnusedError("exclude", unusedExclude) + buldDuplicatesError(duplicates));
  326. }
  327. return {
  328. include,
  329. exclude
  330. };
  331. }
  332. function applyMissingDependenciesDefaults(options, babelApi) {
  333. const {
  334. missingDependencies = {}
  335. } = options;
  336. if (missingDependencies === false) return false;
  337. const caller = babelApi.caller(caller => caller == null ? void 0 : caller.name);
  338. const {
  339. log = "deferred",
  340. inject = caller === "rollup-plugin-babel" ? "throw" : "import",
  341. all = false
  342. } = missingDependencies;
  343. return {
  344. log,
  345. inject,
  346. all
  347. };
  348. }
  349. function isRemoved(path) {
  350. if (path.removed) return true;
  351. if (!path.parentPath) return false;
  352. if (path.listKey) {
  353. var _path$parentPath$node;
  354. if (!((_path$parentPath$node = path.parentPath.node) != null && (_path$parentPath$node = _path$parentPath$node[path.listKey]) != null && _path$parentPath$node.includes(path.node))) return true;
  355. } else {
  356. var _path$parentPath$node2;
  357. if (((_path$parentPath$node2 = path.parentPath.node) == null ? void 0 : _path$parentPath$node2[path.key]) !== path.node) return true;
  358. }
  359. return isRemoved(path.parentPath);
  360. }
  361. var usage = callProvider => {
  362. function property(object, key, placement, path) {
  363. return callProvider({
  364. kind: "property",
  365. object,
  366. key,
  367. placement
  368. }, path);
  369. }
  370. function handleReferencedIdentifier(path) {
  371. const {
  372. node: {
  373. name
  374. },
  375. scope
  376. } = path;
  377. if (scope.getBindingIdentifier(name)) return;
  378. callProvider({
  379. kind: "global",
  380. name
  381. }, path);
  382. }
  383. function analyzeMemberExpression(path) {
  384. const key = resolveKey(path.get("property"), path.node.computed);
  385. return {
  386. key,
  387. handleAsMemberExpression: !!key && key !== "prototype"
  388. };
  389. }
  390. return {
  391. // Symbol(), new Promise
  392. ReferencedIdentifier(path) {
  393. const {
  394. parentPath
  395. } = path;
  396. if (parentPath.isMemberExpression({
  397. object: path.node
  398. }) && analyzeMemberExpression(parentPath).handleAsMemberExpression) {
  399. return;
  400. }
  401. handleReferencedIdentifier(path);
  402. },
  403. "MemberExpression|OptionalMemberExpression"(path) {
  404. const {
  405. key,
  406. handleAsMemberExpression
  407. } = analyzeMemberExpression(path);
  408. if (!handleAsMemberExpression) return;
  409. const object = path.get("object");
  410. let objectIsGlobalIdentifier = object.isIdentifier();
  411. if (objectIsGlobalIdentifier) {
  412. const binding = object.scope.getBinding(object.node.name);
  413. if (binding) {
  414. if (binding.path.isImportNamespaceSpecifier()) return;
  415. objectIsGlobalIdentifier = false;
  416. }
  417. }
  418. const source = resolveSource(object);
  419. let skipObject = property(source.id, key, source.placement, path);
  420. skipObject || (skipObject = !objectIsGlobalIdentifier || path.shouldSkip || object.shouldSkip || isRemoved(object));
  421. if (!skipObject) handleReferencedIdentifier(object);
  422. },
  423. ObjectPattern(path) {
  424. const {
  425. parentPath,
  426. parent
  427. } = path;
  428. let obj;
  429. // const { keys, values } = Object
  430. if (parentPath.isVariableDeclarator()) {
  431. obj = parentPath.get("init");
  432. // ({ keys, values } = Object)
  433. } else if (parentPath.isAssignmentExpression()) {
  434. obj = parentPath.get("right");
  435. // !function ({ keys, values }) {...} (Object)
  436. // resolution does not work after properties transform :-(
  437. } else if (parentPath.isFunction()) {
  438. const grand = parentPath.parentPath;
  439. if (grand.isCallExpression() || grand.isNewExpression()) {
  440. if (grand.node.callee === parent) {
  441. obj = grand.get("arguments")[path.key];
  442. }
  443. }
  444. }
  445. let id = null;
  446. let placement = null;
  447. if (obj) ({
  448. id,
  449. placement
  450. } = resolveSource(obj));
  451. for (const prop of path.get("properties")) {
  452. if (prop.isObjectProperty()) {
  453. const key = resolveKey(prop.get("key"));
  454. if (key) property(id, key, placement, prop);
  455. }
  456. }
  457. },
  458. BinaryExpression(path) {
  459. if (path.node.operator !== "in") return;
  460. const source = resolveSource(path.get("right"));
  461. const key = resolveKey(path.get("left"), true);
  462. if (!key) return;
  463. callProvider({
  464. kind: "in",
  465. object: source.id,
  466. key,
  467. placement: source.placement
  468. }, path);
  469. }
  470. };
  471. };
  472. var entry = callProvider => ({
  473. ImportDeclaration(path) {
  474. const source = getImportSource(path);
  475. if (!source) return;
  476. callProvider({
  477. kind: "import",
  478. source
  479. }, path);
  480. },
  481. Program(path) {
  482. path.get("body").forEach(bodyPath => {
  483. const source = getRequireSource(bodyPath);
  484. if (!source) return;
  485. callProvider({
  486. kind: "import",
  487. source
  488. }, bodyPath);
  489. });
  490. }
  491. });
  492. const nativeRequireResolve = parseFloat(process.versions.node) >= 8.9;
  493. const require = createRequire(import /*::(_)*/.meta.url); // eslint-disable-line
  494. function myResolve(name, basedir) {
  495. if (nativeRequireResolve) {
  496. return require.resolve(name, {
  497. paths: [basedir]
  498. }).replace(/\\/g, "/");
  499. } else {
  500. return requireResolve.sync(name, {
  501. basedir
  502. }).replace(/\\/g, "/");
  503. }
  504. }
  505. function resolve(dirname, moduleName, absoluteImports) {
  506. if (absoluteImports === false) return moduleName;
  507. let basedir = dirname;
  508. if (typeof absoluteImports === "string") {
  509. basedir = path.resolve(basedir, absoluteImports);
  510. }
  511. try {
  512. return myResolve(moduleName, basedir);
  513. } catch (err) {
  514. if (err.code !== "MODULE_NOT_FOUND") throw err;
  515. throw Object.assign(new Error(`Failed to resolve "${moduleName}" relative to "${dirname}"`), {
  516. code: "BABEL_POLYFILL_NOT_FOUND",
  517. polyfill: moduleName,
  518. dirname
  519. });
  520. }
  521. }
  522. function has(basedir, name) {
  523. try {
  524. myResolve(name, basedir);
  525. return true;
  526. } catch {
  527. return false;
  528. }
  529. }
  530. function logMissing(missingDeps) {
  531. if (missingDeps.size === 0) return;
  532. const deps = Array.from(missingDeps).sort().join(" ");
  533. console.warn("\nSome polyfills have been added but are not present in your dependencies.\n" + "Please run one of the following commands:\n" + `\tnpm install --save ${deps}\n` + `\tyarn add ${deps}\n`);
  534. process.exitCode = 1;
  535. }
  536. let allMissingDeps = new Set();
  537. const laterLogMissingDependencies = debounce(() => {
  538. logMissing(allMissingDeps);
  539. allMissingDeps = new Set();
  540. }, 100);
  541. function laterLogMissing(missingDeps) {
  542. if (missingDeps.size === 0) return;
  543. missingDeps.forEach(name => allMissingDeps.add(name));
  544. laterLogMissingDependencies();
  545. }
  546. const PossibleGlobalObjects = new Set(["global", "globalThis", "self", "window"]);
  547. function createMetaResolver(polyfills) {
  548. const {
  549. static: staticP,
  550. instance: instanceP,
  551. global: globalP
  552. } = polyfills;
  553. return meta => {
  554. if (meta.kind === "global" && globalP && has$1(globalP, meta.name)) {
  555. return {
  556. kind: "global",
  557. desc: globalP[meta.name],
  558. name: meta.name
  559. };
  560. }
  561. if (meta.kind === "property" || meta.kind === "in") {
  562. const {
  563. placement,
  564. object,
  565. key
  566. } = meta;
  567. if (object && placement === "static") {
  568. if (globalP && PossibleGlobalObjects.has(object) && has$1(globalP, key)) {
  569. return {
  570. kind: "global",
  571. desc: globalP[key],
  572. name: key
  573. };
  574. }
  575. if (staticP && has$1(staticP, object) && has$1(staticP[object], key)) {
  576. return {
  577. kind: "static",
  578. desc: staticP[object][key],
  579. name: `${object}$${key}`
  580. };
  581. }
  582. }
  583. if (instanceP && has$1(instanceP, key)) {
  584. return {
  585. kind: "instance",
  586. desc: instanceP[key],
  587. name: `${key}`
  588. };
  589. }
  590. }
  591. };
  592. }
  593. const getTargets = _getTargets.default || _getTargets;
  594. function resolveOptions(options, babelApi) {
  595. const {
  596. method,
  597. targets: targetsOption,
  598. ignoreBrowserslistConfig,
  599. configPath,
  600. debug,
  601. shouldInjectPolyfill,
  602. absoluteImports,
  603. ...providerOptions
  604. } = options;
  605. if (isEmpty(options)) {
  606. throw new Error(`\
  607. This plugin requires options, for example:
  608. {
  609. "plugins": [
  610. ["<plugin name>", { method: "usage-pure" }]
  611. ]
  612. }
  613. See more options at https://github.com/babel/babel-polyfills/blob/main/docs/usage.md`);
  614. }
  615. let methodName;
  616. if (method === "usage-global") methodName = "usageGlobal";else if (method === "entry-global") methodName = "entryGlobal";else if (method === "usage-pure") methodName = "usagePure";else if (typeof method !== "string") {
  617. throw new Error(".method must be a string");
  618. } else {
  619. throw new Error(`.method must be one of "entry-global", "usage-global"` + ` or "usage-pure" (received ${JSON.stringify(method)})`);
  620. }
  621. if (typeof shouldInjectPolyfill === "function") {
  622. if (options.include || options.exclude) {
  623. throw new Error(`.include and .exclude are not supported when using the` + ` .shouldInjectPolyfill function.`);
  624. }
  625. } else if (shouldInjectPolyfill != null) {
  626. throw new Error(`.shouldInjectPolyfill must be a function, or undefined` + ` (received ${JSON.stringify(shouldInjectPolyfill)})`);
  627. }
  628. if (absoluteImports != null && typeof absoluteImports !== "boolean" && typeof absoluteImports !== "string") {
  629. throw new Error(`.absoluteImports must be a boolean, a string, or undefined` + ` (received ${JSON.stringify(absoluteImports)})`);
  630. }
  631. let targets;
  632. if (
  633. // If any browserslist-related option is specified, fallback to the old
  634. // behavior of not using the targets specified in the top-level options.
  635. targetsOption || configPath || ignoreBrowserslistConfig) {
  636. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  637. browsers: targetsOption
  638. } : targetsOption;
  639. targets = getTargets(targetsObj, {
  640. ignoreBrowserslistConfig,
  641. configPath
  642. });
  643. } else {
  644. targets = babelApi.targets();
  645. }
  646. return {
  647. method,
  648. methodName,
  649. targets,
  650. absoluteImports: absoluteImports != null ? absoluteImports : false,
  651. shouldInjectPolyfill,
  652. debug: !!debug,
  653. providerOptions: providerOptions
  654. };
  655. }
  656. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  657. const {
  658. method,
  659. methodName,
  660. targets,
  661. debug,
  662. shouldInjectPolyfill,
  663. providerOptions,
  664. absoluteImports
  665. } = resolveOptions(options, babelApi);
  666. // eslint-disable-next-line prefer-const
  667. let include, exclude;
  668. let polyfillsSupport;
  669. let polyfillsNames;
  670. let filterPolyfills;
  671. const getUtils = createUtilsGetter(new ImportsCachedInjector(moduleName => resolve(dirname, moduleName, absoluteImports), name => {
  672. var _polyfillsNames$get, _polyfillsNames;
  673. return (_polyfillsNames$get = (_polyfillsNames = polyfillsNames) == null ? void 0 : _polyfillsNames.get(name)) != null ? _polyfillsNames$get : Infinity;
  674. }));
  675. const depsCache = new Map();
  676. const api = {
  677. babel: babelApi,
  678. getUtils,
  679. method: options.method,
  680. targets,
  681. createMetaResolver,
  682. shouldInjectPolyfill(name) {
  683. if (polyfillsNames === undefined) {
  684. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  685. }
  686. if (!polyfillsNames.has(name)) {
  687. console.warn(`Internal error in the ${providerName} provider: ` + `unknown polyfill "${name}".`);
  688. }
  689. if (filterPolyfills && !filterPolyfills(name)) return false;
  690. let shouldInject = isRequired(name, targets, {
  691. compatData: polyfillsSupport,
  692. includes: include,
  693. excludes: exclude
  694. });
  695. if (shouldInjectPolyfill) {
  696. shouldInject = shouldInjectPolyfill(name, shouldInject);
  697. if (typeof shouldInject !== "boolean") {
  698. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  699. }
  700. }
  701. return shouldInject;
  702. },
  703. debug(name) {
  704. var _debugLog, _debugLog$polyfillsSu;
  705. debugLog().found = true;
  706. if (!debug || !name) return;
  707. if (debugLog().polyfills.has(providerName)) return;
  708. debugLog().polyfills.add(name);
  709. (_debugLog$polyfillsSu = (_debugLog = debugLog()).polyfillsSupport) != null ? _debugLog$polyfillsSu : _debugLog.polyfillsSupport = polyfillsSupport;
  710. },
  711. assertDependency(name, version = "*") {
  712. if (missingDependencies === false) return;
  713. if (absoluteImports) {
  714. // If absoluteImports is not false, we will try resolving
  715. // the dependency and throw if it's not possible. We can
  716. // skip the check here.
  717. return;
  718. }
  719. const dep = version === "*" ? name : `${name}@^${version}`;
  720. const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => has(dirname, name));
  721. if (!found) {
  722. debugLog().missingDeps.add(dep);
  723. }
  724. }
  725. };
  726. const provider = factory(api, providerOptions, dirname);
  727. const providerName = provider.name || factory.name;
  728. if (typeof provider[methodName] !== "function") {
  729. throw new Error(`The "${providerName}" provider doesn't support the "${method}" polyfilling method.`);
  730. }
  731. if (Array.isArray(provider.polyfills)) {
  732. polyfillsNames = new Map(provider.polyfills.map((name, index) => [name, index]));
  733. filterPolyfills = provider.filterPolyfills;
  734. } else if (provider.polyfills) {
  735. polyfillsNames = new Map(Object.keys(provider.polyfills).map((name, index) => [name, index]));
  736. polyfillsSupport = provider.polyfills;
  737. filterPolyfills = provider.filterPolyfills;
  738. } else {
  739. polyfillsNames = new Map();
  740. }
  741. ({
  742. include,
  743. exclude
  744. } = validateIncludeExclude(providerName, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  745. let callProvider;
  746. if (methodName === "usageGlobal") {
  747. callProvider = (payload, path) => {
  748. var _ref;
  749. const utils = getUtils(path);
  750. return (_ref = provider[methodName](payload, utils, path)) != null ? _ref : false;
  751. };
  752. } else {
  753. callProvider = (payload, path) => {
  754. const utils = getUtils(path);
  755. provider[methodName](payload, utils, path);
  756. return false;
  757. };
  758. }
  759. return {
  760. debug,
  761. method,
  762. targets,
  763. provider,
  764. providerName,
  765. callProvider
  766. };
  767. }
  768. function definePolyfillProvider(factory) {
  769. return declare((babelApi, options, dirname) => {
  770. babelApi.assertVersion("^7.0.0 || ^8.0.0-alpha.0");
  771. const {
  772. traverse
  773. } = babelApi;
  774. let debugLog;
  775. const missingDependencies = applyMissingDependenciesDefaults(options, babelApi);
  776. const {
  777. debug,
  778. method,
  779. targets,
  780. provider,
  781. providerName,
  782. callProvider
  783. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  784. const createVisitor = method === "entry-global" ? entry : usage;
  785. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  786. if (debug && debug !== presetEnvSilentDebugHeader) {
  787. console.log(`${providerName}: \`DEBUG\` option`);
  788. console.log(`\nUsing targets: ${stringifyTargetsMultiline(targets)}`);
  789. console.log(`\nUsing polyfills with \`${method}\` method:`);
  790. }
  791. const {
  792. runtimeName
  793. } = provider;
  794. return {
  795. name: "inject-polyfills",
  796. visitor,
  797. pre(file) {
  798. var _provider$pre;
  799. if (runtimeName) {
  800. if (file.get("runtimeHelpersModuleName") && file.get("runtimeHelpersModuleName") !== runtimeName) {
  801. console.warn(`Two different polyfill providers` + ` (${file.get("runtimeHelpersModuleProvider")}` + ` and ${providerName}) are trying to define two` + ` conflicting @babel/runtime alternatives:` + ` ${file.get("runtimeHelpersModuleName")} and ${runtimeName}.` + ` The second one will be ignored.`);
  802. } else {
  803. file.set("runtimeHelpersModuleName", runtimeName);
  804. file.set("runtimeHelpersModuleProvider", providerName);
  805. }
  806. }
  807. debugLog = {
  808. polyfills: new Set(),
  809. polyfillsSupport: undefined,
  810. found: false,
  811. providers: new Set(),
  812. missingDeps: new Set()
  813. };
  814. (_provider$pre = provider.pre) == null || _provider$pre.apply(this, arguments);
  815. },
  816. post() {
  817. var _provider$post;
  818. (_provider$post = provider.post) == null || _provider$post.apply(this, arguments);
  819. if (missingDependencies !== false) {
  820. if (missingDependencies.log === "per-file") {
  821. logMissing(debugLog.missingDeps);
  822. } else {
  823. laterLogMissing(debugLog.missingDeps);
  824. }
  825. }
  826. if (!debug) return;
  827. if (this.filename) console.log(`\n[${this.filename}]`);
  828. if (debugLog.polyfills.size === 0) {
  829. console.log(method === "entry-global" ? debugLog.found ? `Based on your targets, the ${providerName} polyfill did not add any polyfill.` : `The entry point for the ${providerName} polyfill has not been found.` : `Based on your code and targets, the ${providerName} polyfill did not add any polyfill.`);
  830. return;
  831. }
  832. if (method === "entry-global") {
  833. console.log(`The ${providerName} polyfill entry has been replaced with ` + `the following polyfills:`);
  834. } else {
  835. console.log(`The ${providerName} polyfill added the following polyfills:`);
  836. }
  837. for (const name of debugLog.polyfills) {
  838. var _debugLog$polyfillsSu2;
  839. if ((_debugLog$polyfillsSu2 = debugLog.polyfillsSupport) != null && _debugLog$polyfillsSu2[name]) {
  840. const filteredTargets = getInclusionReasons(name, targets, debugLog.polyfillsSupport);
  841. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  842. console.log(` ${name} ${formattedTargets}`);
  843. } else {
  844. console.log(` ${name}`);
  845. }
  846. }
  847. }
  848. };
  849. });
  850. }
  851. function mapGetOr(map, key, getDefault) {
  852. let val = map.get(key);
  853. if (val === undefined) {
  854. val = getDefault();
  855. map.set(key, val);
  856. }
  857. return val;
  858. }
  859. function isEmpty(obj) {
  860. return Object.keys(obj).length === 0;
  861. }
  862. export { definePolyfillProvider as default };
  863. //# sourceMappingURL=index.node.mjs.map