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