index.node.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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. const {
  8. types: t$1,
  9. template
  10. } = babel.default || babel;
  11. function intersection(a, b) {
  12. const result = new Set();
  13. a.forEach(v => b.has(v) && result.add(v));
  14. return result;
  15. }
  16. function has$1(object, key) {
  17. return Object.prototype.hasOwnProperty.call(object, key);
  18. }
  19. function getType(target) {
  20. return Object.prototype.toString.call(target).slice(8, -1);
  21. }
  22. function resolveId(path) {
  23. if (path.isIdentifier() && !path.scope.hasBinding(path.node.name,
  24. /* noGlobals */
  25. true)) {
  26. return path.node.name;
  27. }
  28. const {
  29. deopt
  30. } = path.evaluate();
  31. if (deopt && deopt.isIdentifier()) {
  32. return deopt.node.name;
  33. }
  34. }
  35. function resolveKey(path, computed = false) {
  36. const {
  37. node,
  38. parent,
  39. scope
  40. } = path;
  41. if (path.isStringLiteral()) return node.value;
  42. const {
  43. name
  44. } = node;
  45. const isIdentifier = path.isIdentifier();
  46. if (isIdentifier && !(computed || parent.computed)) return name;
  47. if (computed && path.isMemberExpression() && path.get("object").isIdentifier({
  48. name: "Symbol"
  49. }) && !scope.hasBinding("Symbol",
  50. /* noGlobals */
  51. true)) {
  52. const sym = resolveKey(path.get("property"), path.node.computed);
  53. if (sym) return "Symbol." + sym;
  54. }
  55. if (!isIdentifier || scope.hasBinding(name,
  56. /* noGlobals */
  57. true)) {
  58. const {
  59. value
  60. } = path.evaluate();
  61. if (typeof value === "string") return value;
  62. }
  63. }
  64. function resolveSource(obj) {
  65. if (obj.isMemberExpression() && obj.get("property").isIdentifier({
  66. name: "prototype"
  67. })) {
  68. const id = resolveId(obj.get("object"));
  69. if (id) {
  70. return {
  71. id,
  72. placement: "prototype"
  73. };
  74. }
  75. return {
  76. id: null,
  77. placement: null
  78. };
  79. }
  80. const id = resolveId(obj);
  81. if (id) {
  82. return {
  83. id,
  84. placement: "static"
  85. };
  86. }
  87. const {
  88. value
  89. } = obj.evaluate();
  90. if (value !== undefined) {
  91. return {
  92. id: getType(value),
  93. placement: "prototype"
  94. };
  95. } else if (obj.isRegExpLiteral()) {
  96. return {
  97. id: "RegExp",
  98. placement: "prototype"
  99. };
  100. } else if (obj.isFunction()) {
  101. return {
  102. id: "Function",
  103. placement: "prototype"
  104. };
  105. }
  106. return {
  107. id: null,
  108. placement: null
  109. };
  110. }
  111. function getImportSource({
  112. node
  113. }) {
  114. if (node.specifiers.length === 0) return node.source.value;
  115. }
  116. function getRequireSource({
  117. node
  118. }) {
  119. if (!t$1.isExpressionStatement(node)) return;
  120. const {
  121. expression
  122. } = node;
  123. const isRequire = t$1.isCallExpression(expression) && t$1.isIdentifier(expression.callee) && expression.callee.name === "require" && expression.arguments.length === 1 && t$1.isStringLiteral(expression.arguments[0]);
  124. if (isRequire) return expression.arguments[0].value;
  125. }
  126. function hoist(node) {
  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. let lastImport = this._lastImports.get(programPath);
  196. if (lastImport && lastImport.node && // Sometimes the AST is modified and the "last import"
  197. // we have has been replaced
  198. lastImport.parent === programPath.node && lastImport.container === programPath.node.body) {
  199. lastImport = lastImport.insertAfter(node);
  200. } else {
  201. lastImport = programPath.unshiftContainer("body", node);
  202. }
  203. lastImport = lastImport[lastImport.length - 1];
  204. this._lastImports.set(programPath, lastImport);
  205. /*
  206. let lastImport;
  207. programPath.get("body").forEach(path => {
  208. if (path.isImportDeclaration()) lastImport = path;
  209. if (
  210. path.isExpressionStatement() &&
  211. isRequireCall(path.get("expression"))
  212. ) {
  213. lastImport = path;
  214. }
  215. if (
  216. path.isVariableDeclaration() &&
  217. path.get("declarations").length === 1 &&
  218. (isRequireCall(path.get("declarations.0.init")) ||
  219. (path.get("declarations.0.init").isMemberExpression() &&
  220. isRequireCall(path.get("declarations.0.init.object"))))
  221. ) {
  222. lastImport = path;
  223. }
  224. });*/
  225. }
  226. _ensure(map, programPath, Collection) {
  227. let collection = map.get(programPath);
  228. if (!collection) {
  229. collection = new Collection();
  230. map.set(programPath, collection);
  231. }
  232. return collection;
  233. }
  234. _normalizeKey(programPath, url, name = "") {
  235. const {
  236. sourceType
  237. } = programPath.node; // If we rely on the imported binding (the "name" parameter), we also need to cache
  238. // based on the sourceType. This is because the module transforms change the names
  239. // of the import variables.
  240. return `${name && sourceType}::${url}::${name}`;
  241. }
  242. }
  243. const presetEnvSilentDebugHeader = "#__secret_key__@babel/preset-env__don't_log_debug_header_and_resolved_targets";
  244. function stringifyTargetsMultiline(targets) {
  245. return JSON.stringify(prettifyTargets(targets), null, 2);
  246. }
  247. function patternToRegExp(pattern) {
  248. if (pattern instanceof RegExp) return pattern;
  249. try {
  250. return new RegExp(`^${pattern}$`);
  251. } catch {
  252. return null;
  253. }
  254. }
  255. function buildUnusedError(label, unused) {
  256. if (!unused.length) return "";
  257. return ` - The following "${label}" patterns didn't match any polyfill:\n` + unused.map(original => ` ${String(original)}\n`).join("");
  258. }
  259. function buldDuplicatesError(duplicates) {
  260. if (!duplicates.size) return "";
  261. return ` - The following polyfills were matched both by "include" and "exclude" patterns:\n` + Array.from(duplicates, name => ` ${name}\n`).join("");
  262. }
  263. function validateIncludeExclude(provider, polyfills, includePatterns, excludePatterns) {
  264. let current;
  265. const filter = pattern => {
  266. const regexp = patternToRegExp(pattern);
  267. if (!regexp) return false;
  268. let matched = false;
  269. for (const polyfill of polyfills) {
  270. if (regexp.test(polyfill)) {
  271. matched = true;
  272. current.add(polyfill);
  273. }
  274. }
  275. return !matched;
  276. }; // prettier-ignore
  277. const include = current = new Set();
  278. const unusedInclude = Array.from(includePatterns).filter(filter); // 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. const binding = object.scope.getBinding(object.node.name);
  336. if (binding && binding.path.isImportNamespaceSpecifier()) return;
  337. const source = resolveSource(object);
  338. return property(source.id, key, source.placement, path);
  339. },
  340. ObjectPattern(path) {
  341. const {
  342. parentPath,
  343. parent
  344. } = path;
  345. let obj; // const { keys, values } = Object
  346. if (parentPath.isVariableDeclarator()) {
  347. obj = parentPath.get("init"); // ({ keys, values } = Object)
  348. } else if (parentPath.isAssignmentExpression()) {
  349. obj = parentPath.get("right"); // !function ({ keys, values }) {...} (Object)
  350. // resolution does not work after properties transform :-(
  351. } else if (parentPath.isFunction()) {
  352. const grand = parentPath.parentPath;
  353. if (grand.isCallExpression() || grand.isNewExpression()) {
  354. if (grand.node.callee === parent) {
  355. obj = grand.get("arguments")[path.key];
  356. }
  357. }
  358. }
  359. let id = null;
  360. let placement = null;
  361. if (obj) ({
  362. id,
  363. placement
  364. } = resolveSource(obj));
  365. for (const prop of path.get("properties")) {
  366. if (prop.isObjectProperty()) {
  367. const key = resolveKey(prop.get("key"));
  368. if (key) property(id, key, placement, prop);
  369. }
  370. }
  371. },
  372. BinaryExpression(path) {
  373. if (path.node.operator !== "in") return;
  374. const source = resolveSource(path.get("right"));
  375. const key = resolveKey(path.get("left"), true);
  376. if (!key) return;
  377. callProvider({
  378. kind: "in",
  379. object: source.id,
  380. key,
  381. placement: source.placement
  382. }, path);
  383. }
  384. };
  385. });
  386. var entry = (callProvider => ({
  387. ImportDeclaration(path) {
  388. const source = getImportSource(path);
  389. if (!source) return;
  390. callProvider({
  391. kind: "import",
  392. source
  393. }, path);
  394. },
  395. Program(path) {
  396. path.get("body").forEach(bodyPath => {
  397. const source = getRequireSource(bodyPath);
  398. if (!source) return;
  399. callProvider({
  400. kind: "import",
  401. source
  402. }, bodyPath);
  403. });
  404. }
  405. }));
  406. const nativeRequireResolve = parseFloat(process.versions.node) >= 8.9;
  407. function resolve(dirname, moduleName, absoluteImports) {
  408. if (absoluteImports === false) return moduleName;
  409. let basedir = dirname;
  410. if (typeof absoluteImports === "string") {
  411. basedir = path.resolve(basedir, absoluteImports);
  412. }
  413. try {
  414. if (nativeRequireResolve) {
  415. // $FlowIgnore
  416. return require.resolve(moduleName, {
  417. paths: [basedir]
  418. });
  419. } else {
  420. return requireResolve.sync(moduleName, {
  421. basedir
  422. });
  423. }
  424. } catch (err) {
  425. if (err.code !== "MODULE_NOT_FOUND") throw err; // $FlowIgnore
  426. throw Object.assign(new Error(`Failed to resolve "${moduleName}" relative to "${dirname}"`), {
  427. code: "BABEL_POLYFILL_NOT_FOUND",
  428. polyfill: moduleName,
  429. dirname
  430. });
  431. }
  432. }
  433. function has(basedir, name) {
  434. try {
  435. if (nativeRequireResolve) {
  436. // $FlowIgnore
  437. require.resolve(name, {
  438. paths: [basedir]
  439. });
  440. } else {
  441. requireResolve.sync(name, {
  442. basedir
  443. });
  444. }
  445. return true;
  446. } catch {
  447. return false;
  448. }
  449. }
  450. function logMissing(missingDeps) {
  451. if (missingDeps.size === 0) return;
  452. const deps = Array.from(missingDeps).sort().join(" ");
  453. 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`);
  454. process.exitCode = 1;
  455. }
  456. let allMissingDeps = new Set();
  457. const laterLogMissingDependencies = debounce(() => {
  458. logMissing(allMissingDeps);
  459. allMissingDeps = new Set();
  460. }, 100);
  461. function laterLogMissing(missingDeps) {
  462. if (missingDeps.size === 0) return;
  463. missingDeps.forEach(name => allMissingDeps.add(name));
  464. laterLogMissingDependencies();
  465. }
  466. const PossibleGlobalObjects = new Set(["global", "globalThis", "self", "window"]);
  467. function createMetaResolver(polyfills) {
  468. const {
  469. static: staticP,
  470. instance: instanceP,
  471. global: globalP
  472. } = polyfills;
  473. return meta => {
  474. if (meta.kind === "global" && globalP && has$1(globalP, meta.name)) {
  475. return {
  476. kind: "global",
  477. desc: globalP[meta.name],
  478. name: meta.name
  479. };
  480. }
  481. if (meta.kind === "property" || meta.kind === "in") {
  482. const {
  483. placement,
  484. object,
  485. key
  486. } = meta;
  487. if (object && placement === "static") {
  488. if (globalP && PossibleGlobalObjects.has(object) && has$1(globalP, key)) {
  489. return {
  490. kind: "global",
  491. desc: globalP[key],
  492. name: key
  493. };
  494. }
  495. if (staticP && has$1(staticP, object) && has$1(staticP[object], key)) {
  496. return {
  497. kind: "static",
  498. desc: staticP[object][key],
  499. name: `${object}$${key}`
  500. };
  501. }
  502. }
  503. if (instanceP && has$1(instanceP, key)) {
  504. return {
  505. kind: "instance",
  506. desc: instanceP[key],
  507. name: `${key}`
  508. };
  509. }
  510. }
  511. };
  512. }
  513. const getTargets = _getTargets.default || _getTargets;
  514. function resolveOptions(options, babelApi) {
  515. const {
  516. method,
  517. targets: targetsOption,
  518. ignoreBrowserslistConfig,
  519. configPath,
  520. debug,
  521. shouldInjectPolyfill,
  522. absoluteImports,
  523. ...providerOptions
  524. } = options;
  525. let methodName;
  526. 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") {
  527. throw new Error(".method must be a string");
  528. } else {
  529. throw new Error(`.method must be one of "entry-global", "usage-global"` + ` or "usage-pure" (received ${JSON.stringify(method)})`);
  530. }
  531. if (typeof shouldInjectPolyfill === "function") {
  532. if (options.include || options.exclude) {
  533. throw new Error(`.include and .exclude are not supported when using the` + ` .shouldInjectPolyfill function.`);
  534. }
  535. } else if (shouldInjectPolyfill != null) {
  536. throw new Error(`.shouldInjectPolyfill must be a function, or undefined` + ` (received ${JSON.stringify(shouldInjectPolyfill)})`);
  537. }
  538. if (absoluteImports != null && typeof absoluteImports !== "boolean" && typeof absoluteImports !== "string") {
  539. throw new Error(`.absoluteImports must be a boolean, a string, or undefined` + ` (received ${JSON.stringify(absoluteImports)})`);
  540. }
  541. let targets;
  542. if ( // If any browserslist-related option is specified, fallback to the old
  543. // behavior of not using the targets specified in the top-level options.
  544. targetsOption || configPath || ignoreBrowserslistConfig) {
  545. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  546. browsers: targetsOption
  547. } : targetsOption;
  548. targets = getTargets(targetsObj, {
  549. ignoreBrowserslistConfig,
  550. configPath
  551. });
  552. } else {
  553. targets = babelApi.targets();
  554. }
  555. return {
  556. method,
  557. methodName,
  558. targets,
  559. absoluteImports: absoluteImports != null ? absoluteImports : false,
  560. shouldInjectPolyfill,
  561. debug: !!debug,
  562. providerOptions: providerOptions
  563. };
  564. }
  565. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  566. const {
  567. method,
  568. methodName,
  569. targets,
  570. debug,
  571. shouldInjectPolyfill,
  572. providerOptions,
  573. absoluteImports
  574. } = resolveOptions(options, babelApi);
  575. const getUtils = createUtilsGetter(new ImportsCache(moduleName => resolve(dirname, moduleName, absoluteImports))); // eslint-disable-next-line prefer-const
  576. let include, exclude;
  577. let polyfillsSupport;
  578. let polyfillsNames;
  579. let filterPolyfills;
  580. const depsCache = new Map();
  581. const api = {
  582. babel: babelApi,
  583. getUtils,
  584. method: options.method,
  585. targets,
  586. createMetaResolver,
  587. shouldInjectPolyfill(name) {
  588. if (polyfillsNames === undefined) {
  589. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  590. }
  591. if (!polyfillsNames.has(name)) {
  592. console.warn(`Internal error in the ${provider.name} provider: ` + `unknown polyfill "${name}".`);
  593. }
  594. if (filterPolyfills && !filterPolyfills(name)) return false;
  595. let shouldInject = isRequired(name, targets, {
  596. compatData: polyfillsSupport,
  597. includes: include,
  598. excludes: exclude
  599. });
  600. if (shouldInjectPolyfill) {
  601. shouldInject = shouldInjectPolyfill(name, shouldInject);
  602. if (typeof shouldInject !== "boolean") {
  603. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  604. }
  605. }
  606. return shouldInject;
  607. },
  608. debug(name) {
  609. debugLog().found = true;
  610. if (!debug || !name) return;
  611. if (debugLog().polyfills.has(provider.name)) return;
  612. debugLog().polyfills.set(name, polyfillsSupport && name && polyfillsSupport[name]);
  613. },
  614. assertDependency(name, version = "*") {
  615. if (missingDependencies === false) return;
  616. if (absoluteImports) {
  617. // If absoluteImports is not false, we will try resolving
  618. // the dependency and throw if it's not possible. We can
  619. // skip the check here.
  620. return;
  621. }
  622. const dep = version === "*" ? name : `${name}@^${version}`;
  623. const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => has(dirname, name));
  624. if (!found) {
  625. debugLog().missingDeps.add(dep);
  626. }
  627. }
  628. };
  629. const provider = factory(api, providerOptions, dirname);
  630. if (typeof provider[methodName] !== "function") {
  631. throw new Error(`The "${provider.name || factory.name}" provider doesn't ` + `support the "${method}" polyfilling method.`);
  632. }
  633. if (Array.isArray(provider.polyfills)) {
  634. polyfillsNames = new Set(provider.polyfills);
  635. filterPolyfills = provider.filterPolyfills;
  636. } else if (provider.polyfills) {
  637. polyfillsNames = new Set(Object.keys(provider.polyfills));
  638. polyfillsSupport = provider.polyfills;
  639. filterPolyfills = provider.filterPolyfills;
  640. } else {
  641. polyfillsNames = new Set();
  642. }
  643. ({
  644. include,
  645. exclude
  646. } = validateIncludeExclude(provider.name || factory.name, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  647. return {
  648. debug,
  649. method,
  650. targets,
  651. provider,
  652. callProvider(payload, path) {
  653. const utils = getUtils(path); // $FlowIgnore
  654. provider[methodName](payload, utils, path);
  655. }
  656. };
  657. }
  658. function definePolyfillProvider(factory) {
  659. return declare((babelApi, options, dirname) => {
  660. babelApi.assertVersion(7);
  661. const {
  662. traverse
  663. } = babelApi;
  664. let debugLog;
  665. const missingDependencies = applyMissingDependenciesDefaults(options, babelApi);
  666. const {
  667. debug,
  668. method,
  669. targets,
  670. provider,
  671. callProvider
  672. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  673. const createVisitor = method === "entry-global" ? entry : usage;
  674. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  675. if (debug && debug !== presetEnvSilentDebugHeader) {
  676. console.log(`${provider.name}: \`DEBUG\` option`);
  677. console.log(`\nUsing targets: ${stringifyTargetsMultiline(targets)}`);
  678. console.log(`\nUsing polyfills with \`${method}\` method:`);
  679. }
  680. return {
  681. name: "inject-polyfills",
  682. visitor,
  683. pre() {
  684. var _provider$pre;
  685. debugLog = {
  686. polyfills: new Map(),
  687. found: false,
  688. providers: new Set(),
  689. missingDeps: new Set()
  690. }; // $FlowIgnore - Flow doesn't support optional calls
  691. (_provider$pre = provider.pre) == null ? void 0 : _provider$pre.apply(this, arguments);
  692. },
  693. post() {
  694. var _provider$post;
  695. // $FlowIgnore - Flow doesn't support optional calls
  696. (_provider$post = provider.post) == null ? void 0 : _provider$post.apply(this, arguments);
  697. if (missingDependencies !== false) {
  698. if (missingDependencies.log === "per-file") {
  699. logMissing(debugLog.missingDeps);
  700. } else {
  701. laterLogMissing(debugLog.missingDeps);
  702. }
  703. }
  704. if (!debug) return;
  705. if (this.filename) console.log(`\n[${this.filename}]`);
  706. if (debugLog.polyfills.size === 0) {
  707. 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.`);
  708. return;
  709. }
  710. if (method === "entry-global") {
  711. console.log(`The ${provider.name} polyfill entry has been replaced with ` + `the following polyfills:`);
  712. } else {
  713. console.log(`The ${provider.name} polyfill added the following polyfills:`);
  714. }
  715. for (const [name, support] of debugLog.polyfills) {
  716. if (support) {
  717. const filteredTargets = getInclusionReasons(name, targets, support);
  718. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  719. console.log(` ${name} ${formattedTargets}`);
  720. } else {
  721. console.log(` ${name}`);
  722. }
  723. }
  724. }
  725. };
  726. });
  727. }
  728. function mapGetOr(map, key, getDefault) {
  729. let val = map.get(key);
  730. if (val === undefined) {
  731. val = getDefault();
  732. map.set(key, val);
  733. }
  734. return val;
  735. }
  736. export default definePolyfillProvider;
  737. //# sourceMappingURL=index.node.mjs.map