index.node.mjs 25 KB

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