index.browser.mjs 23 KB

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