index.browser.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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) {
  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. function resolve(dirname, moduleName, absoluteImports) {
  412. if (absoluteImports === false) return moduleName;
  413. throw new Error(`"absoluteImports" is not supported in bundles prepared for the browser.`);
  414. }
  415. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  416. function has(basedir, name) {
  417. return true;
  418. }
  419. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  420. function logMissing(missingDeps) {}
  421. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  422. function laterLogMissing(missingDeps) {}
  423. const PossibleGlobalObjects = new Set(["global", "globalThis", "self", "window"]);
  424. function createMetaResolver(polyfills) {
  425. const {
  426. static: staticP,
  427. instance: instanceP,
  428. global: globalP
  429. } = polyfills;
  430. return meta => {
  431. if (meta.kind === "global" && globalP && has$1(globalP, meta.name)) {
  432. return {
  433. kind: "global",
  434. desc: globalP[meta.name],
  435. name: meta.name
  436. };
  437. }
  438. if (meta.kind === "property" || meta.kind === "in") {
  439. const {
  440. placement,
  441. object,
  442. key
  443. } = meta;
  444. if (object && placement === "static") {
  445. if (globalP && PossibleGlobalObjects.has(object) && has$1(globalP, key)) {
  446. return {
  447. kind: "global",
  448. desc: globalP[key],
  449. name: key
  450. };
  451. }
  452. if (staticP && has$1(staticP, object) && has$1(staticP[object], key)) {
  453. return {
  454. kind: "static",
  455. desc: staticP[object][key],
  456. name: `${object}$${key}`
  457. };
  458. }
  459. }
  460. if (instanceP && has$1(instanceP, key)) {
  461. return {
  462. kind: "instance",
  463. desc: instanceP[key],
  464. name: `${key}`
  465. };
  466. }
  467. }
  468. };
  469. }
  470. const getTargets = _getTargets.default || _getTargets;
  471. function resolveOptions(options, babelApi) {
  472. const {
  473. method,
  474. targets: targetsOption,
  475. ignoreBrowserslistConfig,
  476. configPath,
  477. debug,
  478. shouldInjectPolyfill,
  479. absoluteImports,
  480. ...providerOptions
  481. } = options;
  482. if (isEmpty(options)) {
  483. throw new Error(`\
  484. This plugin requires options, for example:
  485. {
  486. "plugins": [
  487. ["<plugin name>", { method: "usage-pure" }]
  488. ]
  489. }
  490. See more options at https://github.com/babel/babel-polyfills/blob/main/docs/usage.md`);
  491. }
  492. let methodName;
  493. 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") {
  494. throw new Error(".method must be a string");
  495. } else {
  496. throw new Error(`.method must be one of "entry-global", "usage-global"` + ` or "usage-pure" (received ${JSON.stringify(method)})`);
  497. }
  498. if (typeof shouldInjectPolyfill === "function") {
  499. if (options.include || options.exclude) {
  500. throw new Error(`.include and .exclude are not supported when using the` + ` .shouldInjectPolyfill function.`);
  501. }
  502. } else if (shouldInjectPolyfill != null) {
  503. throw new Error(`.shouldInjectPolyfill must be a function, or undefined` + ` (received ${JSON.stringify(shouldInjectPolyfill)})`);
  504. }
  505. if (absoluteImports != null && typeof absoluteImports !== "boolean" && typeof absoluteImports !== "string") {
  506. throw new Error(`.absoluteImports must be a boolean, a string, or undefined` + ` (received ${JSON.stringify(absoluteImports)})`);
  507. }
  508. let targets;
  509. if (
  510. // If any browserslist-related option is specified, fallback to the old
  511. // behavior of not using the targets specified in the top-level options.
  512. targetsOption || configPath || ignoreBrowserslistConfig) {
  513. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  514. browsers: targetsOption
  515. } : targetsOption;
  516. targets = getTargets(targetsObj, {
  517. ignoreBrowserslistConfig,
  518. configPath
  519. });
  520. } else {
  521. targets = babelApi.targets();
  522. }
  523. return {
  524. method,
  525. methodName,
  526. targets,
  527. absoluteImports: absoluteImports != null ? absoluteImports : false,
  528. shouldInjectPolyfill,
  529. debug: !!debug,
  530. providerOptions: providerOptions
  531. };
  532. }
  533. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  534. const {
  535. method,
  536. methodName,
  537. targets,
  538. debug,
  539. shouldInjectPolyfill,
  540. providerOptions,
  541. absoluteImports
  542. } = resolveOptions(options, babelApi);
  543. const getUtils = createUtilsGetter(new ImportsCache(moduleName => resolve(dirname, moduleName, absoluteImports)));
  544. // eslint-disable-next-line prefer-const
  545. let include, exclude;
  546. let polyfillsSupport;
  547. let polyfillsNames;
  548. let filterPolyfills;
  549. const depsCache = new Map();
  550. const api = {
  551. babel: babelApi,
  552. getUtils,
  553. method: options.method,
  554. targets,
  555. createMetaResolver,
  556. shouldInjectPolyfill(name) {
  557. if (polyfillsNames === undefined) {
  558. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  559. }
  560. if (!polyfillsNames.has(name)) {
  561. console.warn(`Internal error in the ${providerName} provider: ` + `unknown polyfill "${name}".`);
  562. }
  563. if (filterPolyfills && !filterPolyfills(name)) return false;
  564. let shouldInject = isRequired(name, targets, {
  565. compatData: polyfillsSupport,
  566. includes: include,
  567. excludes: exclude
  568. });
  569. if (shouldInjectPolyfill) {
  570. shouldInject = shouldInjectPolyfill(name, shouldInject);
  571. if (typeof shouldInject !== "boolean") {
  572. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  573. }
  574. }
  575. return shouldInject;
  576. },
  577. debug(name) {
  578. var _debugLog, _debugLog$polyfillsSu;
  579. debugLog().found = true;
  580. if (!debug || !name) return;
  581. if (debugLog().polyfills.has(providerName)) return;
  582. debugLog().polyfills.add(name);
  583. (_debugLog$polyfillsSu = (_debugLog = debugLog()).polyfillsSupport) != null ? _debugLog$polyfillsSu : _debugLog.polyfillsSupport = polyfillsSupport;
  584. },
  585. assertDependency(name, version = "*") {
  586. if (missingDependencies === false) return;
  587. if (absoluteImports) {
  588. // If absoluteImports is not false, we will try resolving
  589. // the dependency and throw if it's not possible. We can
  590. // skip the check here.
  591. return;
  592. }
  593. const dep = version === "*" ? name : `${name}@^${version}`;
  594. const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => has());
  595. if (!found) {
  596. debugLog().missingDeps.add(dep);
  597. }
  598. }
  599. };
  600. const provider = factory(api, providerOptions, dirname);
  601. const providerName = provider.name || factory.name;
  602. if (typeof provider[methodName] !== "function") {
  603. throw new Error(`The "${providerName}" provider doesn't support the "${method}" polyfilling method.`);
  604. }
  605. if (Array.isArray(provider.polyfills)) {
  606. polyfillsNames = new Set(provider.polyfills);
  607. filterPolyfills = provider.filterPolyfills;
  608. } else if (provider.polyfills) {
  609. polyfillsNames = new Set(Object.keys(provider.polyfills));
  610. polyfillsSupport = provider.polyfills;
  611. filterPolyfills = provider.filterPolyfills;
  612. } else {
  613. polyfillsNames = new Set();
  614. }
  615. ({
  616. include,
  617. exclude
  618. } = validateIncludeExclude(providerName, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  619. return {
  620. debug,
  621. method,
  622. targets,
  623. provider,
  624. providerName,
  625. callProvider(payload, path) {
  626. const utils = getUtils(path);
  627. provider[methodName](payload, utils, path);
  628. }
  629. };
  630. }
  631. function definePolyfillProvider(factory) {
  632. return declare((babelApi, options, dirname) => {
  633. babelApi.assertVersion(7);
  634. const {
  635. traverse
  636. } = babelApi;
  637. let debugLog;
  638. const missingDependencies = applyMissingDependenciesDefaults(options, babelApi);
  639. const {
  640. debug,
  641. method,
  642. targets,
  643. provider,
  644. providerName,
  645. callProvider
  646. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  647. const createVisitor = method === "entry-global" ? entry : usage;
  648. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  649. if (debug && debug !== presetEnvSilentDebugHeader) {
  650. console.log(`${providerName}: \`DEBUG\` option`);
  651. console.log(`\nUsing targets: ${stringifyTargetsMultiline(targets)}`);
  652. console.log(`\nUsing polyfills with \`${method}\` method:`);
  653. }
  654. const {
  655. runtimeName
  656. } = provider;
  657. return {
  658. name: "inject-polyfills",
  659. visitor,
  660. pre(file) {
  661. var _provider$pre;
  662. if (runtimeName) {
  663. if (file.get("runtimeHelpersModuleName") && file.get("runtimeHelpersModuleName") !== runtimeName) {
  664. 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.`);
  665. } else {
  666. file.set("runtimeHelpersModuleName", runtimeName);
  667. file.set("runtimeHelpersModuleProvider", providerName);
  668. }
  669. }
  670. debugLog = {
  671. polyfills: new Set(),
  672. polyfillsSupport: undefined,
  673. found: false,
  674. providers: new Set(),
  675. missingDeps: new Set()
  676. };
  677. (_provider$pre = provider.pre) == null ? void 0 : _provider$pre.apply(this, arguments);
  678. },
  679. post() {
  680. var _provider$post;
  681. (_provider$post = provider.post) == null ? void 0 : _provider$post.apply(this, arguments);
  682. if (missingDependencies !== false) {
  683. if (missingDependencies.log === "per-file") {
  684. logMissing(debugLog.missingDeps);
  685. } else {
  686. laterLogMissing(debugLog.missingDeps);
  687. }
  688. }
  689. if (!debug) return;
  690. if (this.filename) console.log(`\n[${this.filename}]`);
  691. if (debugLog.polyfills.size === 0) {
  692. 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.`);
  693. return;
  694. }
  695. if (method === "entry-global") {
  696. console.log(`The ${providerName} polyfill entry has been replaced with ` + `the following polyfills:`);
  697. } else {
  698. console.log(`The ${providerName} polyfill added the following polyfills:`);
  699. }
  700. for (const name of debugLog.polyfills) {
  701. var _debugLog$polyfillsSu2;
  702. if ((_debugLog$polyfillsSu2 = debugLog.polyfillsSupport) != null && _debugLog$polyfillsSu2[name]) {
  703. const filteredTargets = getInclusionReasons(name, targets, debugLog.polyfillsSupport);
  704. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  705. console.log(` ${name} ${formattedTargets}`);
  706. } else {
  707. console.log(` ${name}`);
  708. }
  709. }
  710. }
  711. };
  712. });
  713. }
  714. function mapGetOr(map, key, getDefault) {
  715. let val = map.get(key);
  716. if (val === undefined) {
  717. val = getDefault();
  718. map.set(key, val);
  719. }
  720. return val;
  721. }
  722. function isEmpty(obj) {
  723. return Object.keys(obj).length === 0;
  724. }
  725. export default definePolyfillProvider;
  726. //# sourceMappingURL=index.browser.mjs.map