web 3d图形渲染器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

873 lines
24 KiB

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