index.browser.mjs 27 KB

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