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.

347 lines
8.9 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 util = require("util");
  7. const Tapable = require("tapable/lib/Tapable");
  8. const SyncHook = require("tapable/lib/SyncHook");
  9. const AsyncSeriesBailHook = require("tapable/lib/AsyncSeriesBailHook");
  10. const AsyncSeriesHook = require("tapable/lib/AsyncSeriesHook");
  11. const createInnerContext = require("./createInnerContext");
  12. const REGEXP_NOT_MODULE = /^\.$|^\.[\\/]|^\.\.$|^\.\.[\\/]|^\/|^[A-Z]:[\\/]/i;
  13. const REGEXP_DIRECTORY = /[\\/]$/i;
  14. const memoryFsJoin = require("memory-fs/lib/join");
  15. const memoizedJoin = new Map();
  16. const memoryFsNormalize = require("memory-fs/lib/normalize");
  17. function withName(name, hook) {
  18. hook.name = name;
  19. return hook;
  20. }
  21. function toCamelCase(str) {
  22. return str.replace(/-([a-z])/g, str => str.substr(1).toUpperCase());
  23. }
  24. const deprecatedPushToMissing = util.deprecate((set, item) => {
  25. set.add(item);
  26. }, "Resolver: 'missing' is now a Set. Use add instead of push.");
  27. const deprecatedResolveContextInCallback = util.deprecate(x => {
  28. return x;
  29. }, "Resolver: The callback argument was splitted into resolveContext and callback.");
  30. const deprecatedHookAsString = util.deprecate(x => {
  31. return x;
  32. }, "Resolver#doResolve: The type arguments (string) is now a hook argument (Hook). Pass a reference to the hook instead.");
  33. class Resolver extends Tapable {
  34. constructor(fileSystem) {
  35. super();
  36. this.fileSystem = fileSystem;
  37. this.hooks = {
  38. resolveStep: withName("resolveStep", new SyncHook(["hook", "request"])),
  39. noResolve: withName("noResolve", new SyncHook(["request", "error"])),
  40. resolve: withName(
  41. "resolve",
  42. new AsyncSeriesBailHook(["request", "resolveContext"])
  43. ),
  44. result: new AsyncSeriesHook(["result", "resolveContext"])
  45. };
  46. this._pluginCompat.tap("Resolver: before/after", options => {
  47. if (/^before-/.test(options.name)) {
  48. options.name = options.name.substr(7);
  49. options.stage = -10;
  50. } else if (/^after-/.test(options.name)) {
  51. options.name = options.name.substr(6);
  52. options.stage = 10;
  53. }
  54. });
  55. this._pluginCompat.tap("Resolver: step hooks", options => {
  56. const name = options.name;
  57. const stepHook = !/^resolve(-s|S)tep$|^no(-r|R)esolve$/.test(name);
  58. if (stepHook) {
  59. options.async = true;
  60. this.ensureHook(name);
  61. const fn = options.fn;
  62. options.fn = (request, resolverContext, callback) => {
  63. const innerCallback = (err, result) => {
  64. if (err) return callback(err);
  65. if (result !== undefined) return callback(null, result);
  66. callback();
  67. };
  68. for (const key in resolverContext) {
  69. innerCallback[key] = resolverContext[key];
  70. }
  71. fn.call(this, request, innerCallback);
  72. };
  73. }
  74. });
  75. }
  76. ensureHook(name) {
  77. if (typeof name !== "string") return name;
  78. name = toCamelCase(name);
  79. if (/^before/.test(name)) {
  80. return this.ensureHook(
  81. name[6].toLowerCase() + name.substr(7)
  82. ).withOptions({
  83. stage: -10
  84. });
  85. }
  86. if (/^after/.test(name)) {
  87. return this.ensureHook(
  88. name[5].toLowerCase() + name.substr(6)
  89. ).withOptions({
  90. stage: 10
  91. });
  92. }
  93. const hook = this.hooks[name];
  94. if (!hook) {
  95. return (this.hooks[name] = withName(
  96. name,
  97. new AsyncSeriesBailHook(["request", "resolveContext"])
  98. ));
  99. }
  100. return hook;
  101. }
  102. getHook(name) {
  103. if (typeof name !== "string") return name;
  104. name = toCamelCase(name);
  105. if (/^before/.test(name)) {
  106. return this.getHook(name[6].toLowerCase() + name.substr(7)).withOptions({
  107. stage: -10
  108. });
  109. }
  110. if (/^after/.test(name)) {
  111. return this.getHook(name[5].toLowerCase() + name.substr(6)).withOptions({
  112. stage: 10
  113. });
  114. }
  115. const hook = this.hooks[name];
  116. if (!hook) {
  117. throw new Error(`Hook ${name} doesn't exist`);
  118. }
  119. return hook;
  120. }
  121. resolveSync(context, path, request) {
  122. let err,
  123. result,
  124. sync = false;
  125. this.resolve(context, path, request, {}, (e, r) => {
  126. err = e;
  127. result = r;
  128. sync = true;
  129. });
  130. if (!sync)
  131. throw new Error(
  132. "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!"
  133. );
  134. if (err) throw err;
  135. return result;
  136. }
  137. resolve(context, path, request, resolveContext, callback) {
  138. // TODO remove in enhanced-resolve 5
  139. // For backward compatiblity START
  140. if (typeof callback !== "function") {
  141. callback = deprecatedResolveContextInCallback(resolveContext);
  142. // resolveContext is a function containing additional properties
  143. // It's now used for resolveContext and callback
  144. }
  145. // END
  146. const obj = {
  147. context: context,
  148. path: path,
  149. request: request
  150. };
  151. const message = "resolve '" + request + "' in '" + path + "'";
  152. // Try to resolve assuming there is no error
  153. // We don't log stuff in this case
  154. return this.doResolve(
  155. this.hooks.resolve,
  156. obj,
  157. message,
  158. {
  159. missing: resolveContext.missing,
  160. stack: resolveContext.stack
  161. },
  162. (err, result) => {
  163. if (!err && result) {
  164. return callback(
  165. null,
  166. result.path === false ? false : result.path + (result.query || ""),
  167. result
  168. );
  169. }
  170. const localMissing = new Set();
  171. // TODO remove in enhanced-resolve 5
  172. localMissing.push = item => deprecatedPushToMissing(localMissing, item);
  173. const log = [];
  174. return this.doResolve(
  175. this.hooks.resolve,
  176. obj,
  177. message,
  178. {
  179. log: msg => {
  180. if (resolveContext.log) {
  181. resolveContext.log(msg);
  182. }
  183. log.push(msg);
  184. },
  185. missing: localMissing,
  186. stack: resolveContext.stack
  187. },
  188. (err, result) => {
  189. if (err) return callback(err);
  190. const error = new Error("Can't " + message);
  191. error.details = log.join("\n");
  192. error.missing = Array.from(localMissing);
  193. this.hooks.noResolve.call(obj, error);
  194. return callback(error);
  195. }
  196. );
  197. }
  198. );
  199. }
  200. doResolve(hook, request, message, resolveContext, callback) {
  201. // TODO remove in enhanced-resolve 5
  202. // For backward compatiblity START
  203. if (typeof callback !== "function") {
  204. callback = deprecatedResolveContextInCallback(resolveContext);
  205. // resolveContext is a function containing additional properties
  206. // It's now used for resolveContext and callback
  207. }
  208. if (typeof hook === "string") {
  209. const name = toCamelCase(hook);
  210. hook = deprecatedHookAsString(this.hooks[name]);
  211. if (!hook) {
  212. throw new Error(`Hook "${name}" doesn't exist`);
  213. }
  214. }
  215. // END
  216. if (typeof callback !== "function")
  217. throw new Error("callback is not a function " + Array.from(arguments));
  218. if (!resolveContext)
  219. throw new Error(
  220. "resolveContext is not an object " + Array.from(arguments)
  221. );
  222. const stackLine =
  223. hook.name +
  224. ": (" +
  225. request.path +
  226. ") " +
  227. (request.request || "") +
  228. (request.query || "") +
  229. (request.directory ? " directory" : "") +
  230. (request.module ? " module" : "");
  231. let newStack;
  232. if (resolveContext.stack) {
  233. newStack = new Set(resolveContext.stack);
  234. if (resolveContext.stack.has(stackLine)) {
  235. // Prevent recursion
  236. const recursionError = new Error(
  237. "Recursion in resolving\nStack:\n " +
  238. Array.from(newStack).join("\n ")
  239. );
  240. recursionError.recursion = true;
  241. if (resolveContext.log)
  242. resolveContext.log("abort resolving because of recursion");
  243. return callback(recursionError);
  244. }
  245. newStack.add(stackLine);
  246. } else {
  247. newStack = new Set([stackLine]);
  248. }
  249. this.hooks.resolveStep.call(hook, request);
  250. if (hook.isUsed()) {
  251. const innerContext = createInnerContext(
  252. {
  253. log: resolveContext.log,
  254. missing: resolveContext.missing,
  255. stack: newStack
  256. },
  257. message
  258. );
  259. return hook.callAsync(request, innerContext, (err, result) => {
  260. if (err) return callback(err);
  261. if (result) return callback(null, result);
  262. callback();
  263. });
  264. } else {
  265. callback();
  266. }
  267. }
  268. parse(identifier) {
  269. if (identifier === "") return null;
  270. const part = {
  271. request: "",
  272. query: "",
  273. module: false,
  274. directory: false,
  275. file: false
  276. };
  277. const idxQuery = identifier.indexOf("?");
  278. if (idxQuery === 0) {
  279. part.query = identifier;
  280. } else if (idxQuery > 0) {
  281. part.request = identifier.slice(0, idxQuery);
  282. part.query = identifier.slice(idxQuery);
  283. } else {
  284. part.request = identifier;
  285. }
  286. if (part.request) {
  287. part.module = this.isModule(part.request);
  288. part.directory = this.isDirectory(part.request);
  289. if (part.directory) {
  290. part.request = part.request.substr(0, part.request.length - 1);
  291. }
  292. }
  293. return part;
  294. }
  295. isModule(path) {
  296. return !REGEXP_NOT_MODULE.test(path);
  297. }
  298. isDirectory(path) {
  299. return REGEXP_DIRECTORY.test(path);
  300. }
  301. join(path, request) {
  302. let cacheEntry;
  303. let pathCache = memoizedJoin.get(path);
  304. if (typeof pathCache === "undefined") {
  305. memoizedJoin.set(path, (pathCache = new Map()));
  306. } else {
  307. cacheEntry = pathCache.get(request);
  308. if (typeof cacheEntry !== "undefined") return cacheEntry;
  309. }
  310. cacheEntry = memoryFsJoin(path, request);
  311. pathCache.set(request, cacheEntry);
  312. return cacheEntry;
  313. }
  314. normalize(path) {
  315. return memoryFsNormalize(path);
  316. }
  317. }
  318. module.exports = Resolver;