index.browser.mjs 25 KB

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