source: frontend/node_modules/@babel/helper-define-polyfill-provider/esm/index.browser.mjs

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 2 weeks ago

Fix frontend appearance

  • Property mode set to 100644
File size: 33.7 KB
Line 
1import { declare } from '@babel/helper-plugin-utils';
2import _getTargets, { prettifyTargets, getInclusionReasons, isRequired } from '@babel/helper-compilation-targets';
3import * as _babel from '@babel/core';
4
5const {
6 types: t$1,
7 template: template
8} = _babel.default || _babel;
9const PossibleGlobalObjects = new Set(["global", "globalThis", "self", "window"]);
10function intersection(a, b) {
11 const result = new Set();
12 a.forEach(v => b.has(v) && result.add(v));
13 return result;
14}
15function has$1(object, key) {
16 return Object.prototype.hasOwnProperty.call(object, key);
17}
18function resolve$1(path, seen = new Set()) {
19 if (seen.has(path)) return;
20 seen.add(path);
21 if (path.isVariableDeclarator()) {
22 if (path.get("id").isIdentifier()) {
23 return resolve$1(path.get("init"), seen);
24 }
25 } else if (path.isReferencedIdentifier()) {
26 const binding = path.scope.getBinding(path.node.name);
27 if (!binding) return path;
28 if (!binding.constant) return;
29 return resolve$1(binding.path, seen);
30 }
31 return path;
32}
33function resolveId(path) {
34 if (path.isIdentifier() && !path.scope.hasBinding(path.node.name, /* noGlobals */true)) {
35 return path.node.name;
36 }
37
38 // globalThis.Object / window.Array / self.Map / global.Set -> resolve to
39 // the property name, because accessing a built-in through a global object
40 // reference is equivalent to accessing it directly.
41 if (path.isMemberExpression() && !path.node.computed) {
42 const object = path.get("object");
43 const property = path.get("property");
44 if (object.isIdentifier() && !object.scope.hasBinding(object.node.name, /* noGlobals */true) && PossibleGlobalObjects.has(object.node.name) && property.isIdentifier()) {
45 return property.node.name;
46 }
47 }
48 const resolved = resolve$1(path);
49 if (resolved != null && resolved.isIdentifier()) {
50 return resolved.node.name;
51 }
52}
53function resolveKey(path, computed = false) {
54 const {
55 scope
56 } = path;
57 if (path.isStringLiteral()) return path.node.value;
58 const isIdentifier = path.isIdentifier();
59 if (isIdentifier && !(computed || path.parent.computed)) {
60 return path.node.name;
61 }
62 if (computed && path.isMemberExpression() && path.get("object").isIdentifier({
63 name: "Symbol"
64 }) && !scope.hasBinding("Symbol", /* noGlobals */true)) {
65 const sym = resolveKey(path.get("property"), path.node.computed);
66 if (sym) return "Symbol." + sym;
67 }
68 if (isIdentifier ? scope.hasBinding(path.node.name, /* noGlobals */true) : path.isPure()) {
69 const {
70 value
71 } = path.evaluate();
72 if (typeof value === "string") return value;
73 }
74}
75function resolveInstance(obj, seen) {
76 const source = resolveSource(obj, seen);
77 return source.placement === "prototype" ? source.id : null;
78}
79function resolveSource(obj, seen) {
80 if (seen.has(obj)) {
81 return {
82 id: null,
83 placement: null
84 };
85 }
86 seen.add(obj);
87 if (obj.isMemberExpression() && obj.get("property").isIdentifier({
88 name: "prototype"
89 })) {
90 const id = resolveId(obj.get("object"));
91 if (id) {
92 return {
93 id,
94 placement: "prototype"
95 };
96 }
97 return {
98 id: null,
99 placement: null
100 };
101 }
102 const id = resolveId(obj);
103 if (id) {
104 return {
105 id,
106 placement: "static"
107 };
108 }
109 const path = resolve$1(obj);
110 switch (path == null ? void 0 : path.type) {
111 case "NullLiteral":
112 return {
113 id: null,
114 placement: null
115 };
116 case "RegExpLiteral":
117 return {
118 id: "RegExp",
119 placement: "prototype"
120 };
121 case "StringLiteral":
122 case "TemplateLiteral":
123 return {
124 id: "String",
125 placement: "prototype"
126 };
127 case "NumericLiteral":
128 return {
129 id: "Number",
130 placement: "prototype"
131 };
132 case "BooleanLiteral":
133 return {
134 id: "Boolean",
135 placement: "prototype"
136 };
137 case "BigIntLiteral":
138 return {
139 id: "BigInt",
140 placement: "prototype"
141 };
142 case "ObjectExpression":
143 return {
144 id: "Object",
145 placement: "prototype"
146 };
147 case "ArrayExpression":
148 return {
149 id: "Array",
150 placement: "prototype"
151 };
152 case "FunctionExpression":
153 case "ArrowFunctionExpression":
154 case "ClassExpression":
155 return {
156 id: "Function",
157 placement: "prototype"
158 };
159 // new Constructor() -> resolve the constructor name
160 case "NewExpression":
161 {
162 const calleeId = resolveId(path.get("callee"));
163 if (calleeId) return {
164 id: calleeId,
165 placement: "prototype"
166 };
167 return {
168 id: null,
169 placement: null
170 };
171 }
172 // Unary expressions -> result type depends on operator
173 case "UnaryExpression":
174 {
175 const {
176 operator
177 } = path.node;
178 if (operator === "typeof") return {
179 id: "String",
180 placement: "prototype"
181 };
182 if (operator === "!" || operator === "delete") return {
183 id: "Boolean",
184 placement: "prototype"
185 };
186 // Unary + always produces Number (throws on BigInt)
187 if (operator === "+") return {
188 id: "Number",
189 placement: "prototype"
190 };
191 // Unary - and ~ can produce Number or BigInt depending on operand
192 if (operator === "-" || operator === "~") {
193 const arg = resolveInstance(path.get("argument"), seen);
194 if (arg === "BigInt") return {
195 id: "BigInt",
196 placement: "prototype"
197 };
198 if (arg !== null) return {
199 id: "Number",
200 placement: "prototype"
201 };
202 return {
203 id: null,
204 placement: null
205 };
206 }
207 return {
208 id: null,
209 placement: null
210 };
211 }
212 // ++i, i++ produce Number or BigInt depending on the argument
213 case "UpdateExpression":
214 {
215 const arg = resolveInstance(path.get("argument"), seen);
216 if (arg === "BigInt") return {
217 id: "BigInt",
218 placement: "prototype"
219 };
220 if (arg !== null) return {
221 id: "Number",
222 placement: "prototype"
223 };
224 return {
225 id: null,
226 placement: null
227 };
228 }
229 // Binary expressions -> result type depends on operator
230 case "BinaryExpression":
231 {
232 const {
233 operator
234 } = path.node;
235 if (operator === "==" || operator === "!=" || operator === "===" || operator === "!==" || operator === "<" || operator === ">" || operator === "<=" || operator === ">=" || operator === "instanceof" || operator === "in") {
236 return {
237 id: "Boolean",
238 placement: "prototype"
239 };
240 }
241 // >>> always produces Number
242 if (operator === ">>>") {
243 return {
244 id: "Number",
245 placement: "prototype"
246 };
247 }
248 // Arithmetic and bitwise operators can produce Number or BigInt
249 if (operator === "-" || operator === "*" || operator === "/" || operator === "%" || operator === "**" || operator === "&" || operator === "|" || operator === "^" || operator === "<<" || operator === ">>") {
250 const left = resolveInstance(path.get("left"), seen);
251 const right = resolveInstance(path.get("right"), seen);
252 if (left === "BigInt" && right === "BigInt") {
253 return {
254 id: "BigInt",
255 placement: "prototype"
256 };
257 }
258 if (left !== null && right !== null) {
259 return {
260 id: "Number",
261 placement: "prototype"
262 };
263 }
264 return {
265 id: null,
266 placement: null
267 };
268 }
269 // + depends on operand types: string wins, otherwise number or bigint
270 if (operator === "+") {
271 const left = resolveInstance(path.get("left"), seen);
272 const right = resolveInstance(path.get("right"), seen);
273 if (left === "String" || right === "String") {
274 return {
275 id: "String",
276 placement: "prototype"
277 };
278 }
279 if (left === "Number" && right === "Number") {
280 return {
281 id: "Number",
282 placement: "prototype"
283 };
284 }
285 if (left === "BigInt" && right === "BigInt") {
286 return {
287 id: "BigInt",
288 placement: "prototype"
289 };
290 }
291 }
292 return {
293 id: null,
294 placement: null
295 };
296 }
297 // (a, b, c) -> the result is the last expression
298 case "SequenceExpression":
299 {
300 const expressions = path.get("expressions");
301 return resolveSource(expressions[expressions.length - 1], seen);
302 }
303 // a = b -> the result is the right side
304 case "AssignmentExpression":
305 {
306 if (path.node.operator === "=") {
307 return resolveSource(path.get("right"), seen);
308 }
309 return {
310 id: null,
311 placement: null
312 };
313 }
314 // a ? b : c -> if both branches resolve to the same type, use it
315 case "ConditionalExpression":
316 {
317 const consequent = resolveSource(path.get("consequent"), seen);
318 const alternate = resolveSource(path.get("alternate"), seen);
319 if (consequent.id && consequent.id === alternate.id) {
320 return consequent;
321 }
322 return {
323 id: null,
324 placement: null
325 };
326 }
327 // (expr) -> unwrap parenthesized expressions
328 case "ParenthesizedExpression":
329 return resolveSource(path.get("expression"), seen);
330 // TypeScript / Flow type wrappers -> unwrap to the inner expression
331 case "TSAsExpression":
332 case "TSSatisfiesExpression":
333 case "TSNonNullExpression":
334 case "TSInstantiationExpression":
335 case "TSTypeAssertion":
336 case "TypeCastExpression":
337 return resolveSource(path.get("expression"), seen);
338 }
339 return {
340 id: null,
341 placement: null
342 };
343}
344function getImportSource({
345 node
346}) {
347 if (node.specifiers.length === 0) return node.source.value;
348}
349function getRequireSource({
350 node
351}) {
352 if (!t$1.isExpressionStatement(node)) return;
353 const {
354 expression
355 } = node;
356 if (t$1.isCallExpression(expression) && t$1.isIdentifier(expression.callee) && expression.callee.name === "require" && expression.arguments.length === 1 && t$1.isStringLiteral(expression.arguments[0])) {
357 return expression.arguments[0].value;
358 }
359}
360function hoist(node) {
361 // @ts-expect-error
362 node._blockHoist = 3;
363 return node;
364}
365function createUtilsGetter(cache) {
366 return path => {
367 const prog = path.findParent(p => p.isProgram());
368 return {
369 injectGlobalImport(url, moduleName) {
370 cache.storeAnonymous(prog, url, moduleName, (isScript, source) => {
371 return isScript ? template.statement.ast`require(${source})` : t$1.importDeclaration([], source);
372 });
373 },
374 injectNamedImport(url, name, hint = name, moduleName) {
375 return cache.storeNamed(prog, url, name, moduleName, (isScript, source, name) => {
376 const id = prog.scope.generateUidIdentifier(hint);
377 return {
378 node: isScript ? hoist(template.statement.ast`
379 var ${id} = require(${source}).${name}
380 `) : t$1.importDeclaration([t$1.importSpecifier(id, name)], source),
381 name: id.name
382 };
383 });
384 },
385 injectDefaultImport(url, hint = url, moduleName) {
386 return cache.storeNamed(prog, url, "default", moduleName, (isScript, source) => {
387 const id = prog.scope.generateUidIdentifier(hint);
388 return {
389 node: isScript ? hoist(template.statement.ast`var ${id} = require(${source})`) : t$1.importDeclaration([t$1.importDefaultSpecifier(id)], source),
390 name: id.name
391 };
392 });
393 }
394 };
395 };
396}
397
398const {
399 types: t
400} = _babel.default || _babel;
401class ImportsCachedInjector {
402 constructor(resolver, getPreferredIndex) {
403 this._imports = new WeakMap();
404 this._anonymousImports = new WeakMap();
405 this._lastImports = new WeakMap();
406 this._resolver = resolver;
407 this._getPreferredIndex = getPreferredIndex;
408 }
409 storeAnonymous(programPath, url, moduleName, getVal) {
410 const key = this._normalizeKey(programPath, url);
411 const imports = this._ensure(this._anonymousImports, programPath, Set);
412 if (imports.has(key)) return;
413 const node = getVal(programPath.node.sourceType === "script", t.stringLiteral(this._resolver(url)));
414 imports.add(key);
415 this._injectImport(programPath, node, moduleName);
416 }
417 storeNamed(programPath, url, name, moduleName, getVal) {
418 const key = this._normalizeKey(programPath, url, name);
419 const imports = this._ensure(this._imports, programPath, Map);
420 if (!imports.has(key)) {
421 const {
422 node,
423 name: id
424 } = getVal(programPath.node.sourceType === "script", t.stringLiteral(this._resolver(url)), t.identifier(name));
425 imports.set(key, id);
426 this._injectImport(programPath, node, moduleName);
427 }
428 return t.identifier(imports.get(key));
429 }
430 _injectImport(programPath, node, moduleName) {
431 var _this$_lastImports$ge;
432 const newIndex = this._getPreferredIndex(moduleName);
433 const lastImports = (_this$_lastImports$ge = this._lastImports.get(programPath)) != null ? _this$_lastImports$ge : [];
434 const isPathStillValid = path => path.node &&
435 // Sometimes the AST is modified and the "last import"
436 // we have has been replaced
437 path.parent === programPath.node && path.container === programPath.node.body;
438 let last;
439 if (newIndex === Infinity) {
440 // Fast path: we can always just insert at the end if newIndex is `Infinity`
441 if (lastImports.length > 0) {
442 last = lastImports[lastImports.length - 1].path;
443 if (!isPathStillValid(last)) last = undefined;
444 }
445 } else {
446 for (const [i, data] of lastImports.entries()) {
447 const {
448 path,
449 index
450 } = data;
451 if (isPathStillValid(path)) {
452 if (newIndex < index) {
453 const [newPath] = path.insertBefore(node);
454 lastImports.splice(i, 0, {
455 path: newPath,
456 index: newIndex
457 });
458 return;
459 }
460 last = path;
461 }
462 }
463 }
464 if (last) {
465 const [newPath] = last.insertAfter(node);
466 lastImports.push({
467 path: newPath,
468 index: newIndex
469 });
470 } else {
471 const [newPath] = programPath.unshiftContainer("body", [node]);
472 this._lastImports.set(programPath, [{
473 path: newPath,
474 index: newIndex
475 }]);
476 }
477 }
478 _ensure(map, programPath, Collection) {
479 let collection = map.get(programPath);
480 if (!collection) {
481 collection = new Collection();
482 map.set(programPath, collection);
483 }
484 return collection;
485 }
486 _normalizeKey(programPath, url, name = "") {
487 const {
488 sourceType
489 } = programPath.node;
490
491 // If we rely on the imported binding (the "name" parameter), we also need to cache
492 // based on the sourceType. This is because the module transforms change the names
493 // of the import variables.
494 return `${name && sourceType}::${url}::${name}`;
495 }
496}
497
498const presetEnvSilentDebugHeader = "#__secret_key__@babel/preset-env__don't_log_debug_header_and_resolved_targets";
499function stringifyTargetsMultiline(targets) {
500 return JSON.stringify(prettifyTargets(targets), null, 2);
501}
502
503function patternToRegExp(pattern) {
504 if (pattern instanceof RegExp) return pattern;
505 try {
506 return new RegExp(`^${pattern}$`);
507 } catch {
508 return null;
509 }
510}
511function buildUnusedError(label, unused) {
512 if (!unused.length) return "";
513 return ` - The following "${label}" patterns didn't match any polyfill:\n` + unused.map(original => ` ${String(original)}\n`).join("");
514}
515function buldDuplicatesError(duplicates) {
516 if (!duplicates.size) return "";
517 return ` - The following polyfills were matched both by "include" and "exclude" patterns:\n` + Array.from(duplicates, name => ` ${name}\n`).join("");
518}
519function validateIncludeExclude(provider, polyfills, includePatterns, excludePatterns) {
520 let current;
521 const filter = pattern => {
522 const regexp = patternToRegExp(pattern);
523 if (!regexp) return false;
524 let matched = false;
525 for (const polyfill of polyfills.keys()) {
526 if (regexp.test(polyfill)) {
527 matched = true;
528 current.add(polyfill);
529 }
530 }
531 return !matched;
532 };
533
534 // prettier-ignore
535 const include = current = new Set();
536 const unusedInclude = Array.from(includePatterns).filter(filter);
537
538 // prettier-ignore
539 const exclude = current = new Set();
540 const unusedExclude = Array.from(excludePatterns).filter(filter);
541 const duplicates = intersection(include, exclude);
542 if (duplicates.size > 0 || unusedInclude.length > 0 || unusedExclude.length > 0) {
543 throw new Error(`Error while validating the "${provider}" provider options:\n` + buildUnusedError("include", unusedInclude) + buildUnusedError("exclude", unusedExclude) + buldDuplicatesError(duplicates));
544 }
545 return {
546 include,
547 exclude
548 };
549}
550function applyMissingDependenciesDefaults(options, babelApi) {
551 const {
552 missingDependencies = {}
553 } = options;
554 if (missingDependencies === false) return false;
555 const caller = babelApi.caller(caller => caller == null ? void 0 : caller.name);
556 const {
557 log = "deferred",
558 inject = caller === "rollup-plugin-babel" ? "throw" : "import",
559 all = false
560 } = missingDependencies;
561 return {
562 log,
563 inject,
564 all
565 };
566}
567
568function isRemoved(path) {
569 if (path.removed) return true;
570 if (!path.parentPath) return false;
571 if (path.listKey) {
572 var _path$parentPath$node;
573 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;
574 } else {
575 var _path$parentPath$node2;
576 if (((_path$parentPath$node2 = path.parentPath.node) == null ? void 0 : _path$parentPath$node2[path.key]) !== path.node) return true;
577 }
578 return isRemoved(path.parentPath);
579}
580var usage = callProvider => {
581 function property(object, key, placement, path) {
582 return callProvider({
583 kind: "property",
584 object,
585 key,
586 placement
587 }, path);
588 }
589 function handleReferencedIdentifier(path) {
590 const {
591 node: {
592 name
593 },
594 scope
595 } = path;
596 if (scope.getBindingIdentifier(name)) return;
597 callProvider({
598 kind: "global",
599 name
600 }, path);
601 }
602 function analyzeMemberExpression(path) {
603 const key = resolveKey(path.get("property"), path.node.computed);
604 return {
605 key,
606 handleAsMemberExpression: !!key && key !== "prototype"
607 };
608 }
609 return {
610 // Symbol(), new Promise
611 ReferencedIdentifier(path) {
612 const {
613 parentPath
614 } = path;
615 if (parentPath.isMemberExpression({
616 object: path.node
617 }) && analyzeMemberExpression(parentPath).handleAsMemberExpression) {
618 return;
619 }
620 handleReferencedIdentifier(path);
621 },
622 "MemberExpression|OptionalMemberExpression"(path) {
623 const {
624 key,
625 handleAsMemberExpression
626 } = analyzeMemberExpression(path);
627 if (!handleAsMemberExpression) return;
628 const object = path.get("object");
629 let objectIsGlobalIdentifier = object.isIdentifier();
630 if (objectIsGlobalIdentifier) {
631 const binding = object.scope.getBinding(object.node.name);
632 if (binding) {
633 if (binding.path.isImportNamespaceSpecifier()) return;
634 objectIsGlobalIdentifier = false;
635 }
636 }
637 const source = resolveSource(object, new Set());
638 const skipObject = property(source.id, key, source.placement, path);
639 const canHandleObject = objectIsGlobalIdentifier && !path.shouldSkip && !object.shouldSkip && !isRemoved(object);
640 if (canHandleObject && (!skipObject || PossibleGlobalObjects.has(source.id))) {
641 handleReferencedIdentifier(object);
642 }
643 },
644 ObjectPattern(path) {
645 const {
646 parentPath,
647 parent
648 } = path;
649 let obj;
650
651 // const { keys, values } = Object
652 if (parentPath.isVariableDeclarator()) {
653 obj = parentPath.get("init");
654 // ({ keys, values } = Object)
655 } else if (parentPath.isAssignmentExpression()) {
656 obj = parentPath.get("right");
657 // !function ({ keys, values }) {...} (Object)
658 // resolution does not work after properties transform :-(
659 } else if (parentPath.isFunction()) {
660 const grand = parentPath.parentPath;
661 if (grand.isCallExpression() || grand.isNewExpression()) {
662 if (grand.node.callee === parent) {
663 obj = grand.get("arguments")[path.key];
664 }
665 }
666 }
667 let id = null;
668 let placement = null;
669 if (obj) ({
670 id,
671 placement
672 } = resolveSource(obj, new Set()));
673 for (const prop of path.get("properties")) {
674 if (prop.isObjectProperty()) {
675 const key = resolveKey(prop.get("key"));
676 if (key) property(id, key, placement, prop);
677 }
678 }
679 },
680 BinaryExpression(path) {
681 if (path.node.operator !== "in") return;
682 const source = resolveSource(path.get("right"), new Set());
683 const key = resolveKey(path.get("left"), true);
684 if (!key) return;
685 callProvider({
686 kind: "in",
687 object: source.id,
688 key,
689 placement: source.placement
690 }, path);
691 }
692 };
693};
694
695var entry = callProvider => ({
696 ImportDeclaration(path) {
697 const source = getImportSource(path);
698 if (!source) return;
699 callProvider({
700 kind: "import",
701 source
702 }, path);
703 },
704 Program(path) {
705 path.get("body").forEach(bodyPath => {
706 const source = getRequireSource(bodyPath);
707 if (!source) return;
708 callProvider({
709 kind: "import",
710 source
711 }, bodyPath);
712 });
713 }
714});
715
716function resolve(dirname, moduleName, absoluteImports) {
717 if (absoluteImports === false) return moduleName;
718 throw new Error(`"absoluteImports" is not supported in bundles prepared for the browser.`);
719}
720
721// eslint-disable-next-line @typescript-eslint/no-unused-vars
722function has(basedir, name) {
723 return true;
724}
725
726// eslint-disable-next-line @typescript-eslint/no-unused-vars
727function logMissing(missingDeps) {}
728
729// eslint-disable-next-line @typescript-eslint/no-unused-vars
730function laterLogMissing(missingDeps) {}
731
732function createMetaResolver(polyfills) {
733 const {
734 static: staticP,
735 instance: instanceP,
736 global: globalP
737 } = polyfills;
738 return meta => {
739 if (meta.kind === "global" && globalP && has$1(globalP, meta.name)) {
740 return {
741 kind: "global",
742 desc: globalP[meta.name],
743 name: meta.name
744 };
745 }
746 if (meta.kind === "property" || meta.kind === "in") {
747 const {
748 placement,
749 object,
750 key
751 } = meta;
752 if (object && placement === "static") {
753 if (globalP && PossibleGlobalObjects.has(object) && has$1(globalP, key)) {
754 return {
755 kind: "global",
756 desc: globalP[key],
757 name: key
758 };
759 }
760 if (staticP && has$1(staticP, object) && has$1(staticP[object], key)) {
761 return {
762 kind: "static",
763 desc: staticP[object][key],
764 name: `${object}$${key}`
765 };
766 }
767 }
768 if (instanceP && has$1(instanceP, key)) {
769 return {
770 kind: "instance",
771 desc: instanceP[key],
772 name: `${key}`
773 };
774 }
775 }
776 };
777}
778
779const getTargets = _getTargets.default || _getTargets;
780function resolveOptions(options, babelApi) {
781 const {
782 method,
783 targets: targetsOption,
784 ignoreBrowserslistConfig,
785 configPath,
786 debug,
787 shouldInjectPolyfill,
788 absoluteImports,
789 ...providerOptions
790 } = options;
791 if (isEmpty(options)) {
792 throw new Error(`\
793This plugin requires options, for example:
794 {
795 "plugins": [
796 ["<plugin name>", { method: "usage-pure" }]
797 ]
798 }
799
800See more options at https://github.com/babel/babel-polyfills/blob/main/docs/usage.md`);
801 }
802 let methodName;
803 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") {
804 throw new Error(".method must be a string");
805 } else {
806 throw new Error(`.method must be one of "entry-global", "usage-global"` + ` or "usage-pure" (received ${JSON.stringify(method)})`);
807 }
808 if (typeof shouldInjectPolyfill === "function") {
809 if (options.include || options.exclude) {
810 throw new Error(`.include and .exclude are not supported when using the` + ` .shouldInjectPolyfill function.`);
811 }
812 } else if (shouldInjectPolyfill != null) {
813 throw new Error(`.shouldInjectPolyfill must be a function, or undefined` + ` (received ${JSON.stringify(shouldInjectPolyfill)})`);
814 }
815 if (absoluteImports != null && typeof absoluteImports !== "boolean" && typeof absoluteImports !== "string") {
816 throw new Error(`.absoluteImports must be a boolean, a string, or undefined` + ` (received ${JSON.stringify(absoluteImports)})`);
817 }
818 let targets;
819 if (
820 // If any browserslist-related option is specified, fallback to the old
821 // behavior of not using the targets specified in the top-level options.
822 targetsOption || configPath || ignoreBrowserslistConfig) {
823 const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
824 browsers: targetsOption
825 } : targetsOption;
826 targets = getTargets(targetsObj, {
827 ignoreBrowserslistConfig,
828 configPath
829 });
830 } else {
831 targets = babelApi.targets();
832 }
833 return {
834 method,
835 methodName,
836 targets,
837 absoluteImports: absoluteImports != null ? absoluteImports : false,
838 shouldInjectPolyfill,
839 debug: !!debug,
840 providerOptions: providerOptions
841 };
842}
843function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
844 const {
845 method,
846 methodName,
847 targets,
848 debug,
849 shouldInjectPolyfill,
850 providerOptions,
851 absoluteImports
852 } = resolveOptions(options, babelApi);
853
854 // eslint-disable-next-line prefer-const
855 let include, exclude;
856 let polyfillsSupport;
857 let polyfillsNames;
858 let filterPolyfills;
859 const getUtils = createUtilsGetter(new ImportsCachedInjector(moduleName => resolve(dirname, moduleName, absoluteImports), name => {
860 var _polyfillsNames$get, _polyfillsNames;
861 return (_polyfillsNames$get = (_polyfillsNames = polyfillsNames) == null ? void 0 : _polyfillsNames.get(name)) != null ? _polyfillsNames$get : Infinity;
862 }));
863 const depsCache = new Map();
864 const api = {
865 babel: babelApi,
866 getUtils,
867 method: options.method,
868 targets,
869 createMetaResolver,
870 shouldInjectPolyfill(name) {
871 if (polyfillsNames === undefined) {
872 throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
873 }
874 if (!polyfillsNames.has(name)) {
875 console.warn(`Internal error in the ${providerName} provider: ` + `unknown polyfill "${name}".`);
876 }
877 if (filterPolyfills && !filterPolyfills(name)) return false;
878 let shouldInject = isRequired(name, targets, {
879 compatData: polyfillsSupport,
880 includes: include,
881 excludes: exclude
882 });
883 if (shouldInjectPolyfill) {
884 shouldInject = shouldInjectPolyfill(name, shouldInject);
885 if (typeof shouldInject !== "boolean") {
886 throw new Error(`.shouldInjectPolyfill must return a boolean.`);
887 }
888 }
889 return shouldInject;
890 },
891 debug(name) {
892 var _debugLog, _debugLog$polyfillsSu;
893 debugLog().found = true;
894 if (!debug || !name) return;
895 if (debugLog().polyfills.has(providerName)) return;
896 debugLog().polyfills.add(name);
897 (_debugLog$polyfillsSu = (_debugLog = debugLog()).polyfillsSupport) != null ? _debugLog$polyfillsSu : _debugLog.polyfillsSupport = polyfillsSupport;
898 },
899 assertDependency(name, version = "*") {
900 if (missingDependencies === false) return;
901 if (absoluteImports) {
902 // If absoluteImports is not false, we will try resolving
903 // the dependency and throw if it's not possible. We can
904 // skip the check here.
905 return;
906 }
907 const dep = version === "*" ? name : `${name}@^${version}`;
908 const found = missingDependencies.all ? false : mapGetOr(depsCache, `${name} :: ${dirname}`, () => has());
909 if (!found) {
910 debugLog().missingDeps.add(dep);
911 }
912 }
913 };
914 const provider = factory(api, providerOptions, dirname);
915 const providerName = provider.name || factory.name;
916 if (typeof provider[methodName] !== "function") {
917 throw new Error(`The "${providerName}" provider doesn't support the "${method}" polyfilling method.`);
918 }
919 if (Array.isArray(provider.polyfills)) {
920 polyfillsNames = new Map(provider.polyfills.map((name, index) => [name, index]));
921 filterPolyfills = provider.filterPolyfills;
922 } else if (provider.polyfills) {
923 polyfillsNames = new Map(Object.keys(provider.polyfills).map((name, index) => [name, index]));
924 polyfillsSupport = provider.polyfills;
925 filterPolyfills = provider.filterPolyfills;
926 } else {
927 polyfillsNames = new Map();
928 }
929 ({
930 include,
931 exclude
932 } = validateIncludeExclude(providerName, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
933 let callProvider;
934 if (methodName === "usageGlobal") {
935 callProvider = (payload, path) => {
936 var _ref;
937 const utils = getUtils(path);
938 return (_ref = provider[methodName](payload, utils, path)) != null ? _ref : false;
939 };
940 } else {
941 callProvider = (payload, path) => {
942 const utils = getUtils(path);
943 provider[methodName](payload, utils, path);
944 return false;
945 };
946 }
947 return {
948 debug,
949 method,
950 targets,
951 provider,
952 providerName,
953 callProvider
954 };
955}
956function definePolyfillProvider(factory) {
957 return declare((babelApi, options, dirname) => {
958 babelApi.assertVersion("^7.0.0 || ^8.0.0-alpha.0");
959 const {
960 traverse
961 } = babelApi;
962 let debugLog;
963 const missingDependencies = applyMissingDependenciesDefaults(options, babelApi);
964 const {
965 debug,
966 method,
967 targets,
968 provider,
969 providerName,
970 callProvider
971 } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
972 const createVisitor = method === "entry-global" ? entry : usage;
973 const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
974 if (debug && debug !== presetEnvSilentDebugHeader) {
975 console.log(`${providerName}: \`DEBUG\` option`);
976 console.log(`\nUsing targets: ${stringifyTargetsMultiline(targets)}`);
977 console.log(`\nUsing polyfills with \`${method}\` method:`);
978 }
979 const {
980 runtimeName
981 } = provider;
982 return {
983 name: "inject-polyfills",
984 visitor,
985 pre(file) {
986 var _provider$pre;
987 if (runtimeName) {
988 if (file.get("runtimeHelpersModuleName") && file.get("runtimeHelpersModuleName") !== runtimeName) {
989 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.`);
990 } else {
991 file.set("runtimeHelpersModuleName", runtimeName);
992 file.set("runtimeHelpersModuleProvider", providerName);
993 }
994 }
995 debugLog = {
996 polyfills: new Set(),
997 polyfillsSupport: undefined,
998 found: false,
999 providers: new Set(),
1000 missingDeps: new Set()
1001 };
1002 (_provider$pre = provider.pre) == null || _provider$pre.apply(this, arguments);
1003 },
1004 post() {
1005 var _provider$post;
1006 (_provider$post = provider.post) == null || _provider$post.apply(this, arguments);
1007 if (missingDependencies !== false) {
1008 if (missingDependencies.log === "per-file") {
1009 logMissing(debugLog.missingDeps);
1010 } else {
1011 laterLogMissing(debugLog.missingDeps);
1012 }
1013 }
1014 if (!debug) return;
1015 if (this.filename) console.log(`\n[${this.filename}]`);
1016 if (debugLog.polyfills.size === 0) {
1017 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.`);
1018 return;
1019 }
1020 if (method === "entry-global") {
1021 console.log(`The ${providerName} polyfill entry has been replaced with ` + `the following polyfills:`);
1022 } else {
1023 console.log(`The ${providerName} polyfill added the following polyfills:`);
1024 }
1025 for (const name of debugLog.polyfills) {
1026 var _debugLog$polyfillsSu2;
1027 if ((_debugLog$polyfillsSu2 = debugLog.polyfillsSupport) != null && _debugLog$polyfillsSu2[name]) {
1028 const filteredTargets = getInclusionReasons(name, targets, debugLog.polyfillsSupport);
1029 const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
1030 console.log(` ${name} ${formattedTargets}`);
1031 } else {
1032 console.log(` ${name}`);
1033 }
1034 }
1035 }
1036 };
1037 });
1038}
1039function mapGetOr(map, key, getDefault) {
1040 let val = map.get(key);
1041 if (val === undefined) {
1042 val = getDefault();
1043 map.set(key, val);
1044 }
1045 return val;
1046}
1047function isEmpty(obj) {
1048 return Object.keys(obj).length === 0;
1049}
1050
1051export { definePolyfillProvider as default };
1052//# sourceMappingURL=index.browser.mjs.map
Note: See TracBrowser for help on using the repository browser.