index.node.mjs 25 KB

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