index.node.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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,
  25. /* noGlobals */
  26. true)) {
  27. return path.node.name;
  28. }
  29. const {
  30. deopt
  31. } = path.evaluate();
  32. if (deopt && deopt.isIdentifier()) {
  33. return deopt.node.name;
  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",
  48. /* noGlobals */
  49. true)) {
  50. const sym = resolveKey(path.get("property"), path.node.computed);
  51. if (sym) return "Symbol." + sym;
  52. }
  53. if (!isIdentifier || scope.hasBinding(path.node.name,
  54. /* noGlobals */
  55. true)) {
  56. const {
  57. value
  58. } = path.evaluate();
  59. if (typeof value === "string") return value;
  60. }
  61. }
  62. function resolveSource(obj) {
  63. if (obj.isMemberExpression() && obj.get("property").isIdentifier({
  64. name: "prototype"
  65. })) {
  66. const id = resolveId(obj.get("object"));
  67. if (id) {
  68. return {
  69. id,
  70. placement: "prototype"
  71. };
  72. }
  73. return {
  74. id: null,
  75. placement: null
  76. };
  77. }
  78. const id = resolveId(obj);
  79. if (id) {
  80. return {
  81. id,
  82. placement: "static"
  83. };
  84. }
  85. const {
  86. value
  87. } = obj.evaluate();
  88. if (value !== undefined) {
  89. return {
  90. id: getType(value),
  91. placement: "prototype"
  92. };
  93. } else if (obj.isRegExpLiteral()) {
  94. return {
  95. id: "RegExp",
  96. placement: "prototype"
  97. };
  98. } else if (obj.isFunction()) {
  99. return {
  100. id: "Function",
  101. placement: "prototype"
  102. };
  103. }
  104. return {
  105. id: null,
  106. placement: null
  107. };
  108. }
  109. function getImportSource({
  110. node
  111. }) {
  112. if (node.specifiers.length === 0) return node.source.value;
  113. }
  114. function getRequireSource({
  115. node
  116. }) {
  117. if (!t$1.isExpressionStatement(node)) return;
  118. const {
  119. expression
  120. } = node;
  121. if (t$1.isCallExpression(expression) && t$1.isIdentifier(expression.callee) && expression.callee.name === "require" && expression.arguments.length === 1 && t$1.isStringLiteral(expression.arguments[0])) {
  122. return expression.arguments[0].value;
  123. }
  124. }
  125. function hoist(node) {
  126. // @ts-expect-error
  127. node._blockHoist = 3;
  128. return node;
  129. }
  130. function createUtilsGetter(cache) {
  131. return path => {
  132. const prog = path.findParent(p => p.isProgram());
  133. return {
  134. injectGlobalImport(url) {
  135. cache.storeAnonymous(prog, url, (isScript, source) => {
  136. return isScript ? template.statement.ast`require(${source})` : t$1.importDeclaration([], source);
  137. });
  138. },
  139. injectNamedImport(url, name, hint = name) {
  140. return cache.storeNamed(prog, url, name, (isScript, source, name) => {
  141. const id = prog.scope.generateUidIdentifier(hint);
  142. return {
  143. node: isScript ? hoist(template.statement.ast`
  144. var ${id} = require(${source}).${name}
  145. `) : t$1.importDeclaration([t$1.importSpecifier(id, name)], source),
  146. name: id.name
  147. };
  148. });
  149. },
  150. injectDefaultImport(url, hint = url) {
  151. return cache.storeNamed(prog, url, "default", (isScript, source) => {
  152. const id = prog.scope.generateUidIdentifier(hint);
  153. return {
  154. node: isScript ? hoist(template.statement.ast`var ${id} = require(${source})`) : t$1.importDeclaration([t$1.importDefaultSpecifier(id)], source),
  155. name: id.name
  156. };
  157. });
  158. }
  159. };
  160. };
  161. }
  162. const {
  163. types: t
  164. } = _babel.default || _babel;
  165. class ImportsCache {
  166. constructor(resolver) {
  167. this._imports = new WeakMap();
  168. this._anonymousImports = new WeakMap();
  169. this._lastImports = new WeakMap();
  170. this._resolver = resolver;
  171. }
  172. storeAnonymous(programPath, url, // eslint-disable-next-line no-undef
  173. getVal) {
  174. const key = this._normalizeKey(programPath, url);
  175. const imports = this._ensure(this._anonymousImports, programPath, Set);
  176. if (imports.has(key)) return;
  177. const node = getVal(programPath.node.sourceType === "script", t.stringLiteral(this._resolver(url)));
  178. imports.add(key);
  179. this._injectImport(programPath, node);
  180. }
  181. storeNamed(programPath, url, name, getVal) {
  182. const key = this._normalizeKey(programPath, url, name);
  183. const imports = this._ensure(this._imports, programPath, Map);
  184. if (!imports.has(key)) {
  185. const {
  186. node,
  187. name: id
  188. } = getVal(programPath.node.sourceType === "script", t.stringLiteral(this._resolver(url)), t.identifier(name));
  189. imports.set(key, id);
  190. this._injectImport(programPath, node);
  191. }
  192. return t.identifier(imports.get(key));
  193. }
  194. _injectImport(programPath, node) {
  195. const lastImport = this._lastImports.get(programPath);
  196. let newNodes;
  197. if (lastImport && lastImport.node && // 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; // If we rely on the imported binding (the "name" parameter), we also need to cache
  239. // based on the sourceType. This is because the module transforms change the names
  240. // of the import variables.
  241. return `${name && sourceType}::${url}::${name}`;
  242. }
  243. }
  244. const presetEnvSilentDebugHeader = "#__secret_key__@babel/preset-env__don't_log_debug_header_and_resolved_targets";
  245. function stringifyTargetsMultiline(targets) {
  246. return JSON.stringify(prettifyTargets(targets), null, 2);
  247. }
  248. function patternToRegExp(pattern) {
  249. if (pattern instanceof RegExp) return pattern;
  250. try {
  251. return new RegExp(`^${pattern}$`);
  252. } catch {
  253. return null;
  254. }
  255. }
  256. function buildUnusedError(label, unused) {
  257. if (!unused.length) return "";
  258. return ` - The following "${label}" patterns didn't match any polyfill:\n` + unused.map(original => ` ${String(original)}\n`).join("");
  259. }
  260. function buldDuplicatesError(duplicates) {
  261. if (!duplicates.size) return "";
  262. return ` - The following polyfills were matched both by "include" and "exclude" patterns:\n` + Array.from(duplicates, name => ` ${name}\n`).join("");
  263. }
  264. function validateIncludeExclude(provider, polyfills, includePatterns, excludePatterns) {
  265. let current;
  266. const filter = pattern => {
  267. const regexp = patternToRegExp(pattern);
  268. if (!regexp) return false;
  269. let matched = false;
  270. for (const polyfill of polyfills) {
  271. if (regexp.test(polyfill)) {
  272. matched = true;
  273. current.add(polyfill);
  274. }
  275. }
  276. return !matched;
  277. }; // prettier-ignore
  278. const include = current = new Set();
  279. const unusedInclude = Array.from(includePatterns).filter(filter); // prettier-ignore
  280. const exclude = current = new Set();
  281. const unusedExclude = Array.from(excludePatterns).filter(filter);
  282. const duplicates = intersection(include, exclude);
  283. if (duplicates.size > 0 || unusedInclude.length > 0 || unusedExclude.length > 0) {
  284. throw new Error(`Error while validating the "${provider}" provider options:\n` + buildUnusedError("include", unusedInclude) + buildUnusedError("exclude", unusedExclude) + buldDuplicatesError(duplicates));
  285. }
  286. return {
  287. include,
  288. exclude
  289. };
  290. }
  291. function applyMissingDependenciesDefaults(options, babelApi) {
  292. const {
  293. missingDependencies = {}
  294. } = options;
  295. if (missingDependencies === false) return false;
  296. const caller = babelApi.caller(caller => caller == null ? void 0 : caller.name);
  297. const {
  298. log = "deferred",
  299. inject = caller === "rollup-plugin-babel" ? "throw" : "import",
  300. all = false
  301. } = missingDependencies;
  302. return {
  303. log,
  304. inject,
  305. all
  306. };
  307. }
  308. var usage = (callProvider => {
  309. function property(object, key, placement, path) {
  310. return callProvider({
  311. kind: "property",
  312. object,
  313. key,
  314. placement
  315. }, path);
  316. }
  317. return {
  318. // Symbol(), new Promise
  319. ReferencedIdentifier(path) {
  320. const {
  321. node: {
  322. name
  323. },
  324. scope
  325. } = path;
  326. if (scope.getBindingIdentifier(name)) return;
  327. callProvider({
  328. kind: "global",
  329. name
  330. }, path);
  331. },
  332. MemberExpression(path) {
  333. const key = resolveKey(path.get("property"), path.node.computed);
  334. if (!key || key === "prototype") return;
  335. const object = path.get("object");
  336. if (object.isIdentifier()) {
  337. const binding = object.scope.getBinding(object.node.name);
  338. if (binding && binding.path.isImportNamespaceSpecifier()) return;
  339. }
  340. const source = resolveSource(object);
  341. return property(source.id, key, source.placement, path);
  342. },
  343. ObjectPattern(path) {
  344. const {
  345. parentPath,
  346. parent
  347. } = path;
  348. let obj; // const { keys, values } = Object
  349. if (parentPath.isVariableDeclarator()) {
  350. obj = parentPath.get("init"); // ({ keys, values } = Object)
  351. } else if (parentPath.isAssignmentExpression()) {
  352. obj = parentPath.get("right"); // !function ({ keys, values }) {...} (Object)
  353. // resolution does not work after properties transform :-(
  354. } else if (parentPath.isFunction()) {
  355. const grand = parentPath.parentPath;
  356. if (grand.isCallExpression() || grand.isNewExpression()) {
  357. if (grand.node.callee === parent) {
  358. obj = grand.get("arguments")[path.key];
  359. }
  360. }
  361. }
  362. let id = null;
  363. let placement = null;
  364. if (obj) ({
  365. id,
  366. placement
  367. } = resolveSource(obj));
  368. for (const prop of path.get("properties")) {
  369. if (prop.isObjectProperty()) {
  370. const key = resolveKey(prop.get("key"));
  371. if (key) property(id, key, placement, prop);
  372. }
  373. }
  374. },
  375. BinaryExpression(path) {
  376. if (path.node.operator !== "in") return;
  377. const source = resolveSource(path.get("right"));
  378. const key = resolveKey(path.get("left"), true);
  379. if (!key) return;
  380. callProvider({
  381. kind: "in",
  382. object: source.id,
  383. key,
  384. placement: source.placement
  385. }, path);
  386. }
  387. };
  388. });
  389. var entry = (callProvider => ({
  390. ImportDeclaration(path) {
  391. const source = getImportSource(path);
  392. if (!source) return;
  393. callProvider({
  394. kind: "import",
  395. source
  396. }, path);
  397. },
  398. Program(path) {
  399. path.get("body").forEach(bodyPath => {
  400. const source = getRequireSource(bodyPath);
  401. if (!source) return;
  402. callProvider({
  403. kind: "import",
  404. source
  405. }, bodyPath);
  406. });
  407. }
  408. }));
  409. const nativeRequireResolve = parseFloat(process.versions.node) >= 8.9;
  410. const require = createRequire(import
  411. /*::(_)*/
  412. .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 ( // If any browserslist-related option is specified, fallback to the old
  552. // behavior of not using the targets specified in the top-level options.
  553. targetsOption || configPath || ignoreBrowserslistConfig) {
  554. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  555. browsers: targetsOption
  556. } : targetsOption;
  557. targets = getTargets(targetsObj, {
  558. ignoreBrowserslistConfig,
  559. configPath
  560. });
  561. } else {
  562. targets = babelApi.targets();
  563. }
  564. return {
  565. method,
  566. methodName,
  567. targets,
  568. absoluteImports: absoluteImports != null ? absoluteImports : false,
  569. shouldInjectPolyfill,
  570. debug: !!debug,
  571. providerOptions: providerOptions
  572. };
  573. }
  574. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  575. const {
  576. method,
  577. methodName,
  578. targets,
  579. debug,
  580. shouldInjectPolyfill,
  581. providerOptions,
  582. absoluteImports
  583. } = resolveOptions(options, babelApi);
  584. const getUtils = createUtilsGetter(new ImportsCache(moduleName => resolve(dirname, moduleName, absoluteImports))); // eslint-disable-next-line prefer-const
  585. let include, exclude;
  586. let polyfillsSupport;
  587. let polyfillsNames;
  588. let filterPolyfills;
  589. const depsCache = new Map();
  590. const api = {
  591. babel: babelApi,
  592. getUtils,
  593. method: options.method,
  594. targets,
  595. createMetaResolver,
  596. shouldInjectPolyfill(name) {
  597. if (polyfillsNames === undefined) {
  598. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  599. }
  600. if (!polyfillsNames.has(name)) {
  601. console.warn(`Internal error in the ${provider.name} provider: ` + `unknown polyfill "${name}".`);
  602. }
  603. if (filterPolyfills && !filterPolyfills(name)) return false;
  604. let shouldInject = isRequired(name, targets, {
  605. compatData: polyfillsSupport,
  606. includes: include,
  607. excludes: exclude
  608. });
  609. if (shouldInjectPolyfill) {
  610. shouldInject = shouldInjectPolyfill(name, shouldInject);
  611. if (typeof shouldInject !== "boolean") {
  612. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  613. }
  614. }
  615. return shouldInject;
  616. },
  617. debug(name) {
  618. var _debugLog, _debugLog$polyfillsSu;
  619. debugLog().found = true;
  620. if (!debug || !name) return;
  621. if (debugLog().polyfills.has(provider.name)) return;
  622. debugLog().polyfills.add(name);
  623. (_debugLog$polyfillsSu = (_debugLog = debugLog()).polyfillsSupport) != null ? _debugLog$polyfillsSu : _debugLog.polyfillsSupport = polyfillsSupport;
  624. },
  625. assertDependency(name, version = "*") {
  626. if (missingDependencies === false) return;
  627. if (absoluteImports) {
  628. // If absoluteImports is not false, we will try resolving
  629. // the dependency and throw if it's not possible. We can
  630. // skip the check here.
  631. return;
  632. }
  633. const dep = version === "*" ? name : `${name}@^${version}`;
  634. const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => has(dirname, name));
  635. if (!found) {
  636. debugLog().missingDeps.add(dep);
  637. }
  638. }
  639. };
  640. const provider = factory(api, providerOptions, dirname);
  641. if (typeof provider[methodName] !== "function") {
  642. throw new Error(`The "${provider.name || factory.name}" provider doesn't ` + `support the "${method}" polyfilling method.`);
  643. }
  644. if (Array.isArray(provider.polyfills)) {
  645. polyfillsNames = new Set(provider.polyfills);
  646. filterPolyfills = provider.filterPolyfills;
  647. } else if (provider.polyfills) {
  648. polyfillsNames = new Set(Object.keys(provider.polyfills));
  649. polyfillsSupport = provider.polyfills;
  650. filterPolyfills = provider.filterPolyfills;
  651. } else {
  652. polyfillsNames = new Set();
  653. }
  654. ({
  655. include,
  656. exclude
  657. } = validateIncludeExclude(provider.name || factory.name, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  658. return {
  659. debug,
  660. method,
  661. targets,
  662. provider,
  663. callProvider(payload, path) {
  664. const utils = getUtils(path);
  665. provider[methodName](payload, utils, path);
  666. }
  667. };
  668. }
  669. function definePolyfillProvider(factory) {
  670. return declare((babelApi, options, dirname) => {
  671. babelApi.assertVersion(7);
  672. const {
  673. traverse
  674. } = babelApi;
  675. let debugLog;
  676. const missingDependencies = applyMissingDependenciesDefaults(options, babelApi);
  677. const {
  678. debug,
  679. method,
  680. targets,
  681. provider,
  682. callProvider
  683. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  684. const createVisitor = method === "entry-global" ? entry : usage;
  685. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  686. if (debug && debug !== presetEnvSilentDebugHeader) {
  687. console.log(`${provider.name}: \`DEBUG\` option`);
  688. console.log(`\nUsing targets: ${stringifyTargetsMultiline(targets)}`);
  689. console.log(`\nUsing polyfills with \`${method}\` method:`);
  690. }
  691. return {
  692. name: "inject-polyfills",
  693. visitor,
  694. pre() {
  695. var _provider$pre;
  696. debugLog = {
  697. polyfills: new Set(),
  698. polyfillsSupport: undefined,
  699. found: false,
  700. providers: new Set(),
  701. missingDeps: new Set()
  702. };
  703. (_provider$pre = provider.pre) == null ? void 0 : _provider$pre.apply(this, arguments);
  704. },
  705. post() {
  706. var _provider$post;
  707. (_provider$post = provider.post) == null ? void 0 : _provider$post.apply(this, arguments);
  708. if (missingDependencies !== false) {
  709. if (missingDependencies.log === "per-file") {
  710. logMissing(debugLog.missingDeps);
  711. } else {
  712. laterLogMissing(debugLog.missingDeps);
  713. }
  714. }
  715. if (!debug) return;
  716. if (this.filename) console.log(`\n[${this.filename}]`);
  717. if (debugLog.polyfills.size === 0) {
  718. console.log(method === "entry-global" ? debugLog.found ? `Based on your targets, the ${provider.name} polyfill did not add any polyfill.` : `The entry point for the ${provider.name} polyfill has not been found.` : `Based on your code and targets, the ${provider.name} polyfill did not add any polyfill.`);
  719. return;
  720. }
  721. if (method === "entry-global") {
  722. console.log(`The ${provider.name} polyfill entry has been replaced with ` + `the following polyfills:`);
  723. } else {
  724. console.log(`The ${provider.name} polyfill added the following polyfills:`);
  725. }
  726. for (const name of debugLog.polyfills) {
  727. var _debugLog$polyfillsSu2;
  728. if ((_debugLog$polyfillsSu2 = debugLog.polyfillsSupport) != null && _debugLog$polyfillsSu2[name]) {
  729. const filteredTargets = getInclusionReasons(name, targets, debugLog.polyfillsSupport);
  730. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  731. console.log(` ${name} ${formattedTargets}`);
  732. } else {
  733. console.log(` ${name}`);
  734. }
  735. }
  736. }
  737. };
  738. });
  739. }
  740. function mapGetOr(map, key, getDefault) {
  741. let val = map.get(key);
  742. if (val === undefined) {
  743. val = getDefault();
  744. map.set(key, val);
  745. }
  746. return val;
  747. }
  748. function isEmpty(obj) {
  749. return Object.keys(obj).length === 0;
  750. }
  751. export default definePolyfillProvider;
  752. //# sourceMappingURL=index.node.mjs.map