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.

295 lines
11 KiB

  1. "use strict";
  2. exports.__esModule = true;
  3. exports.default = definePolyfillProvider;
  4. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  5. var _helperCompilationTargets = _interopRequireWildcard(require("@babel/helper-compilation-targets"));
  6. var _utils = require("./utils");
  7. var _importsCache = _interopRequireDefault(require("./imports-cache"));
  8. var _debugUtils = require("./debug-utils");
  9. var _normalizeOptions = require("./normalize-options");
  10. var v = _interopRequireWildcard(require("./visitors"));
  11. var deps = _interopRequireWildcard(require("./node/dependencies"));
  12. var _metaResolver = _interopRequireDefault(require("./meta-resolver"));
  13. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  15. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  16. function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
  17. function resolveOptions(options, babelApi) {
  18. const {
  19. method,
  20. targets: targetsOption,
  21. ignoreBrowserslistConfig,
  22. configPath,
  23. debug,
  24. shouldInjectPolyfill,
  25. absoluteImports
  26. } = options,
  27. providerOptions = _objectWithoutPropertiesLoose(options, ["method", "targets", "ignoreBrowserslistConfig", "configPath", "debug", "shouldInjectPolyfill", "absoluteImports"]);
  28. let methodName;
  29. 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") {
  30. throw new Error(".method must be a string");
  31. } else {
  32. throw new Error(`.method must be one of "entry-global", "usage-global"` + ` or "usage-pure" (received ${JSON.stringify(method)})`);
  33. }
  34. if (typeof shouldInjectPolyfill === "function") {
  35. if (options.include || options.exclude) {
  36. throw new Error(`.include and .exclude are not supported when using the` + ` .shouldInjectPolyfill function.`);
  37. }
  38. } else if (shouldInjectPolyfill != null) {
  39. throw new Error(`.shouldInjectPolyfill must be a function, or undefined` + ` (received ${JSON.stringify(shouldInjectPolyfill)})`);
  40. }
  41. if (absoluteImports != null && typeof absoluteImports !== "boolean" && typeof absoluteImports !== "string") {
  42. throw new Error(`.absoluteImports must be a boolean, a string, or undefined` + ` (received ${JSON.stringify(absoluteImports)})`);
  43. }
  44. let targets;
  45. if ( // If any browserslist-related option is specified, fallback to the old
  46. // behavior of not using the targets specified in the top-level options.
  47. targetsOption || configPath || ignoreBrowserslistConfig) {
  48. const targetsObj = typeof targetsOption === "string" || Array.isArray(targetsOption) ? {
  49. browsers: targetsOption
  50. } : targetsOption;
  51. targets = (0, _helperCompilationTargets.default)(targetsObj, {
  52. ignoreBrowserslistConfig,
  53. configPath
  54. });
  55. } else {
  56. targets = babelApi.targets();
  57. }
  58. return {
  59. method,
  60. methodName,
  61. targets,
  62. absoluteImports: absoluteImports != null ? absoluteImports : false,
  63. shouldInjectPolyfill,
  64. debug: !!debug,
  65. providerOptions: providerOptions
  66. };
  67. }
  68. function instantiateProvider(factory, options, missingDependencies, dirname, debugLog, babelApi) {
  69. const {
  70. method,
  71. methodName,
  72. targets,
  73. debug,
  74. shouldInjectPolyfill,
  75. providerOptions,
  76. absoluteImports
  77. } = resolveOptions(options, babelApi);
  78. const getUtils = (0, _utils.createUtilsGetter)(new _importsCache.default(moduleName => deps.resolve(dirname, moduleName, absoluteImports))); // eslint-disable-next-line prefer-const
  79. let include, exclude;
  80. let polyfillsSupport;
  81. let polyfillsNames;
  82. let filterPolyfills;
  83. const depsCache = new Map();
  84. const api = {
  85. babel: babelApi,
  86. getUtils,
  87. method: options.method,
  88. targets,
  89. createMetaResolver: _metaResolver.default,
  90. shouldInjectPolyfill(name) {
  91. if (polyfillsNames === undefined) {
  92. throw new Error(`Internal error in the ${factory.name} provider: ` + `shouldInjectPolyfill() can't be called during initialization.`);
  93. }
  94. if (!polyfillsNames.has(name)) {
  95. console.warn(`Internal error in the ${provider.name} provider: ` + `unknown polyfill "${name}".`);
  96. }
  97. if (filterPolyfills && !filterPolyfills(name)) return false;
  98. let shouldInject = (0, _helperCompilationTargets.isRequired)(name, targets, {
  99. compatData: polyfillsSupport,
  100. includes: include,
  101. excludes: exclude
  102. });
  103. if (shouldInjectPolyfill) {
  104. shouldInject = shouldInjectPolyfill(name, shouldInject);
  105. if (typeof shouldInject !== "boolean") {
  106. throw new Error(`.shouldInjectPolyfill must return a boolean.`);
  107. }
  108. }
  109. return shouldInject;
  110. },
  111. debug(name) {
  112. debugLog().found = true;
  113. if (!debug || !name) return;
  114. if (debugLog().polyfills.has(provider.name)) return;
  115. debugLog().polyfills.set(name, polyfillsSupport && name && polyfillsSupport[name]);
  116. },
  117. assertDependency(name, version = "*") {
  118. if (missingDependencies === false) return;
  119. if (absoluteImports) {
  120. // If absoluteImports is not false, we will try resolving
  121. // the dependency and throw if it's not possible. We can
  122. // skip the check here.
  123. return;
  124. }
  125. const dep = version === "*" ? name : `${name}@^${version}`;
  126. const found = missingDependencies.all ? false : mapGetOr(depsCache, name, () => !deps.has(dirname, name));
  127. if (!found) {
  128. debugLog().missingDeps.add(dep);
  129. }
  130. }
  131. };
  132. const provider = factory(api, providerOptions, dirname);
  133. if (typeof provider[methodName] !== "function") {
  134. throw new Error(`The "${provider.name || factory.name}" provider doesn't ` + `support the "${method}" polyfilling method.`);
  135. }
  136. if (Array.isArray(provider.polyfills)) {
  137. polyfillsNames = new Set(provider.polyfills);
  138. filterPolyfills = provider.filterPolyfills;
  139. } else if (provider.polyfills) {
  140. polyfillsNames = new Set(Object.keys(provider.polyfills));
  141. polyfillsSupport = provider.polyfills;
  142. filterPolyfills = provider.filterPolyfills;
  143. } else {
  144. polyfillsNames = new Set();
  145. }
  146. ({
  147. include,
  148. exclude
  149. } = (0, _normalizeOptions.validateIncludeExclude)(provider.name || factory.name, polyfillsNames, providerOptions.include || [], providerOptions.exclude || []));
  150. return {
  151. debug,
  152. method,
  153. targets,
  154. provider,
  155. callProvider(payload, path) {
  156. const utils = getUtils(path); // $FlowIgnore
  157. provider[methodName](payload, utils, path);
  158. }
  159. };
  160. }
  161. function definePolyfillProvider(factory) {
  162. return (0, _helperPluginUtils.declare)((babelApi, options, dirname) => {
  163. babelApi.assertVersion(7);
  164. const {
  165. traverse
  166. } = babelApi;
  167. let debugLog;
  168. const missingDependencies = (0, _normalizeOptions.applyMissingDependenciesDefaults)(options, babelApi);
  169. const {
  170. debug,
  171. method,
  172. targets,
  173. provider,
  174. callProvider
  175. } = instantiateProvider(factory, options, missingDependencies, dirname, () => debugLog, babelApi);
  176. const createVisitor = method === "entry-global" ? v.entry : v.usage;
  177. const visitor = provider.visitor ? traverse.visitors.merge([createVisitor(callProvider), provider.visitor]) : createVisitor(callProvider);
  178. if (debug && debug !== _debugUtils.presetEnvSilentDebugHeader) {
  179. console.log(`${provider.name}: \`DEBUG\` option`);
  180. console.log(`\nUsing targets: ${(0, _debugUtils.stringifyTargetsMultiline)(targets)}`);
  181. console.log(`\nUsing polyfills with \`${method}\` method:`);
  182. }
  183. return {
  184. name: "inject-polyfills",
  185. visitor,
  186. pre() {
  187. var _provider$pre;
  188. debugLog = {
  189. polyfills: new Map(),
  190. found: false,
  191. providers: new Set(),
  192. missingDeps: new Set()
  193. }; // $FlowIgnore - Flow doesn't support optional calls
  194. (_provider$pre = provider.pre) == null ? void 0 : _provider$pre.apply(this, arguments);
  195. },
  196. post() {
  197. var _provider$post;
  198. // $FlowIgnore - Flow doesn't support optional calls
  199. (_provider$post = provider.post) == null ? void 0 : _provider$post.apply(this, arguments);
  200. if (missingDependencies !== false) {
  201. if (missingDependencies.log === "per-file") {
  202. deps.logMissing(debugLog.missingDeps);
  203. } else {
  204. deps.laterLogMissing(debugLog.missingDeps);
  205. }
  206. }
  207. if (!debug) return;
  208. if (this.filename) console.log(`\n[${this.filename}]`);
  209. if (debugLog.polyfills.size === 0) {
  210. 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.`);
  211. return;
  212. }
  213. if (method === "entry-global") {
  214. console.log(`The ${provider.name} polyfill entry has been replaced with ` + `the following polyfills:`);
  215. } else {
  216. console.log(`The ${provider.name} polyfill added the following polyfills:`);
  217. }
  218. for (const [name, support] of debugLog.polyfills) {
  219. if (support) {
  220. const filteredTargets = (0, _helperCompilationTargets.getInclusionReasons)(name, targets, support);
  221. const formattedTargets = JSON.stringify(filteredTargets).replace(/,/g, ", ").replace(/^\{"/, '{ "').replace(/"\}$/, '" }');
  222. console.log(` ${name} ${formattedTargets}`);
  223. } else {
  224. console.log(` ${name}`);
  225. }
  226. }
  227. }
  228. };
  229. });
  230. }
  231. function mapGetOr(map, key, getDefault) {
  232. let val = map.get(key);
  233. if (val === undefined) {
  234. val = getDefault();
  235. map.set(key, val);
  236. }
  237. return val;
  238. }