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.

86 lines
2.4 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RequireResolveDependency = require("./RequireResolveDependency");
  7. const RequireResolveContextDependency = require("./RequireResolveContextDependency");
  8. const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency");
  9. const ContextDependencyHelpers = require("./ContextDependencyHelpers");
  10. class RequireResolveDependencyParserPlugin {
  11. constructor(options) {
  12. this.options = options;
  13. }
  14. apply(parser) {
  15. const options = this.options;
  16. const process = (expr, weak) => {
  17. if (expr.arguments.length !== 1) return;
  18. const param = parser.evaluateExpression(expr.arguments[0]);
  19. if (param.isConditional()) {
  20. for (const option of param.options) {
  21. const result = processItem(expr, option, weak);
  22. if (result === undefined) {
  23. processContext(expr, option, weak);
  24. }
  25. }
  26. const dep = new RequireResolveHeaderDependency(expr.callee.range);
  27. dep.loc = expr.loc;
  28. parser.state.current.addDependency(dep);
  29. return true;
  30. } else {
  31. const result = processItem(expr, param, weak);
  32. if (result === undefined) {
  33. processContext(expr, param, weak);
  34. }
  35. const dep = new RequireResolveHeaderDependency(expr.callee.range);
  36. dep.loc = expr.loc;
  37. parser.state.current.addDependency(dep);
  38. return true;
  39. }
  40. };
  41. const processItem = (expr, param, weak) => {
  42. if (param.isString()) {
  43. const dep = new RequireResolveDependency(param.string, param.range);
  44. dep.loc = expr.loc;
  45. dep.optional = !!parser.scope.inTry;
  46. dep.weak = weak;
  47. parser.state.current.addDependency(dep);
  48. return true;
  49. }
  50. };
  51. const processContext = (expr, param, weak) => {
  52. const dep = ContextDependencyHelpers.create(
  53. RequireResolveContextDependency,
  54. param.range,
  55. param,
  56. expr,
  57. options,
  58. {
  59. mode: weak ? "weak" : "sync"
  60. },
  61. parser
  62. );
  63. if (!dep) return;
  64. dep.loc = expr.loc;
  65. dep.optional = !!parser.scope.inTry;
  66. parser.state.current.addDependency(dep);
  67. return true;
  68. };
  69. parser.hooks.call
  70. .for("require.resolve")
  71. .tap("RequireResolveDependencyParserPlugin", expr => {
  72. return process(expr, false);
  73. });
  74. parser.hooks.call
  75. .for("require.resolveWeak")
  76. .tap("RequireResolveDependencyParserPlugin", expr => {
  77. return process(expr, true);
  78. });
  79. }
  80. }
  81. module.exports = RequireResolveDependencyParserPlugin;