ContextDependencyHelpers.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { parseResource } = require("../util/identifier");
  7. /** @typedef {import("estree").Node} EsTreeNode */
  8. /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
  9. /** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
  10. /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
  11. /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
  12. /** @typedef {import("./ContextDependency")} ContextDependency */
  13. /** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */
  14. /**
  15. * Escapes regular expression metacharacters
  16. * @param {string} str String to quote
  17. * @returns {string} Escaped string
  18. */
  19. const quoteMeta = str => {
  20. return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
  21. };
  22. const splitContextFromPrefix = prefix => {
  23. const idx = prefix.lastIndexOf("/");
  24. let context = ".";
  25. if (idx >= 0) {
  26. context = prefix.slice(0, idx);
  27. prefix = `.${prefix.slice(idx)}`;
  28. }
  29. return {
  30. context,
  31. prefix
  32. };
  33. };
  34. /** @typedef {Partial<Omit<ContextDependencyOptions, "resource">>} PartialContextDependencyOptions */
  35. /** @typedef {{ new(options: ContextDependencyOptions, range: [number, number], valueRange: [number, number], ...args: any[]): ContextDependency }} ContextDependencyConstructor */
  36. /**
  37. * @param {ContextDependencyConstructor} Dep the Dependency class
  38. * @param {[number, number]} range source range
  39. * @param {BasicEvaluatedExpression} param context param
  40. * @param {EsTreeNode} expr expr
  41. * @param {Pick<JavascriptParserOptions, `${"expr"|"wrapped"}Context${"Critical"|"Recursive"|"RegExp"}` | "exprContextRequest">} options options for context creation
  42. * @param {PartialContextDependencyOptions} contextOptions options for the ContextModule
  43. * @param {JavascriptParser} parser the parser
  44. * @param {...any} depArgs depArgs
  45. * @returns {ContextDependency} the created Dependency
  46. */
  47. exports.create = (
  48. Dep,
  49. range,
  50. param,
  51. expr,
  52. options,
  53. contextOptions,
  54. parser,
  55. ...depArgs
  56. ) => {
  57. if (param.isTemplateString()) {
  58. let prefixRaw = param.quasis[0].string;
  59. let postfixRaw =
  60. param.quasis.length > 1
  61. ? param.quasis[param.quasis.length - 1].string
  62. : "";
  63. const valueRange = param.range;
  64. const { context, prefix } = splitContextFromPrefix(prefixRaw);
  65. const {
  66. path: postfix,
  67. query,
  68. fragment
  69. } = parseResource(postfixRaw, parser);
  70. // When there are more than two quasis, the generated RegExp can be more precise
  71. // We join the quasis with the expression regexp
  72. const innerQuasis = param.quasis.slice(1, param.quasis.length - 1);
  73. const innerRegExp =
  74. options.wrappedContextRegExp.source +
  75. innerQuasis
  76. .map(q => quoteMeta(q.string) + options.wrappedContextRegExp.source)
  77. .join("");
  78. // Example: `./context/pre${e}inner${e}inner2${e}post?query#frag`
  79. // context: "./context"
  80. // prefix: "./pre"
  81. // innerQuasis: [BEE("inner"), BEE("inner2")]
  82. // (BEE = BasicEvaluatedExpression)
  83. // postfix: "post"
  84. // query: "?query"
  85. // fragment: "#frag"
  86. // regExp: /^\.\/pre.*inner.*inner2.*post$/
  87. const regExp = new RegExp(
  88. `^${quoteMeta(prefix)}${innerRegExp}${quoteMeta(postfix)}$`
  89. );
  90. const dep = new Dep(
  91. {
  92. request: context + query + fragment,
  93. recursive: options.wrappedContextRecursive,
  94. regExp,
  95. mode: "sync",
  96. ...contextOptions
  97. },
  98. range,
  99. valueRange,
  100. ...depArgs
  101. );
  102. dep.loc = expr.loc;
  103. const replaces = [];
  104. param.parts.forEach((part, i) => {
  105. if (i % 2 === 0) {
  106. // Quasis or merged quasi
  107. let range = part.range;
  108. let value = part.string;
  109. if (param.templateStringKind === "cooked") {
  110. value = JSON.stringify(value);
  111. value = value.slice(1, value.length - 1);
  112. }
  113. if (i === 0) {
  114. // prefix
  115. value = prefix;
  116. range = [param.range[0], part.range[1]];
  117. value =
  118. (param.templateStringKind === "cooked" ? "`" : "String.raw`") +
  119. value;
  120. } else if (i === param.parts.length - 1) {
  121. // postfix
  122. value = postfix;
  123. range = [part.range[0], param.range[1]];
  124. value = value + "`";
  125. } else if (
  126. part.expression &&
  127. part.expression.type === "TemplateElement" &&
  128. part.expression.value.raw === value
  129. ) {
  130. // Shortcut when it's a single quasi and doesn't need to be replaced
  131. return;
  132. }
  133. replaces.push({
  134. range,
  135. value
  136. });
  137. } else {
  138. // Expression
  139. parser.walkExpression(part.expression);
  140. }
  141. });
  142. dep.replaces = replaces;
  143. dep.critical =
  144. options.wrappedContextCritical &&
  145. "a part of the request of a dependency is an expression";
  146. return dep;
  147. } else if (
  148. param.isWrapped() &&
  149. ((param.prefix && param.prefix.isString()) ||
  150. (param.postfix && param.postfix.isString()))
  151. ) {
  152. let prefixRaw =
  153. param.prefix && param.prefix.isString() ? param.prefix.string : "";
  154. let postfixRaw =
  155. param.postfix && param.postfix.isString() ? param.postfix.string : "";
  156. const prefixRange =
  157. param.prefix && param.prefix.isString() ? param.prefix.range : null;
  158. const postfixRange =
  159. param.postfix && param.postfix.isString() ? param.postfix.range : null;
  160. const valueRange = param.range;
  161. const { context, prefix } = splitContextFromPrefix(prefixRaw);
  162. const {
  163. path: postfix,
  164. query,
  165. fragment
  166. } = parseResource(postfixRaw, parser);
  167. const regExp = new RegExp(
  168. `^${quoteMeta(prefix)}${options.wrappedContextRegExp.source}${quoteMeta(
  169. postfix
  170. )}$`
  171. );
  172. const dep = new Dep(
  173. {
  174. request: context + query + fragment,
  175. recursive: options.wrappedContextRecursive,
  176. regExp,
  177. mode: "sync",
  178. ...contextOptions
  179. },
  180. range,
  181. valueRange,
  182. ...depArgs
  183. );
  184. dep.loc = expr.loc;
  185. const replaces = [];
  186. if (prefixRange) {
  187. replaces.push({
  188. range: prefixRange,
  189. value: JSON.stringify(prefix)
  190. });
  191. }
  192. if (postfixRange) {
  193. replaces.push({
  194. range: postfixRange,
  195. value: JSON.stringify(postfix)
  196. });
  197. }
  198. dep.replaces = replaces;
  199. dep.critical =
  200. options.wrappedContextCritical &&
  201. "a part of the request of a dependency is an expression";
  202. if (parser && param.wrappedInnerExpressions) {
  203. for (const part of param.wrappedInnerExpressions) {
  204. if (part.expression) parser.walkExpression(part.expression);
  205. }
  206. }
  207. return dep;
  208. } else {
  209. const dep = new Dep(
  210. {
  211. request: options.exprContextRequest,
  212. recursive: options.exprContextRecursive,
  213. regExp: /** @type {RegExp} */ (options.exprContextRegExp),
  214. mode: "sync",
  215. ...contextOptions
  216. },
  217. range,
  218. param.range,
  219. ...depArgs
  220. );
  221. dep.loc = expr.loc;
  222. dep.critical =
  223. options.exprContextCritical &&
  224. "the request of a dependency is an expression";
  225. parser.walkExpression(param.expression);
  226. return dep;
  227. }
  228. };