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.

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