DescriptionFilePlugin.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const DescriptionFileUtils = require("./DescriptionFileUtils");
  7. /** @typedef {import("./Resolver")} Resolver */
  8. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  9. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  10. module.exports = class DescriptionFilePlugin {
  11. /**
  12. * @param {string | ResolveStepHook} source source
  13. * @param {string[]} filenames filenames
  14. * @param {boolean} pathIsFile pathIsFile
  15. * @param {string | ResolveStepHook} target target
  16. */
  17. constructor(source, filenames, pathIsFile, target) {
  18. this.source = source;
  19. this.filenames = filenames;
  20. this.pathIsFile = pathIsFile;
  21. this.target = target;
  22. }
  23. /**
  24. * @param {Resolver} resolver the resolver
  25. * @returns {void}
  26. */
  27. apply(resolver) {
  28. const target = resolver.ensureHook(this.target);
  29. resolver
  30. .getHook(this.source)
  31. .tapAsync(
  32. "DescriptionFilePlugin",
  33. (request, resolveContext, callback) => {
  34. const path = request.path;
  35. if (!path) return callback();
  36. const directory = this.pathIsFile
  37. ? DescriptionFileUtils.cdUp(path)
  38. : path;
  39. if (!directory) return callback();
  40. DescriptionFileUtils.loadDescriptionFile(
  41. resolver,
  42. directory,
  43. this.filenames,
  44. request.descriptionFilePath
  45. ? {
  46. path: request.descriptionFilePath,
  47. content: request.descriptionFileData,
  48. directory: /** @type {string} */ (request.descriptionFileRoot)
  49. }
  50. : undefined,
  51. resolveContext,
  52. (err, result) => {
  53. if (err) return callback(err);
  54. if (!result) {
  55. if (resolveContext.log)
  56. resolveContext.log(
  57. `No description file found in ${directory} or above`
  58. );
  59. return callback();
  60. }
  61. const relativePath =
  62. "." + path.slice(result.directory.length).replace(/\\/g, "/");
  63. /** @type {ResolveRequest} */
  64. const obj = {
  65. ...request,
  66. descriptionFilePath: result.path,
  67. descriptionFileData: result.content,
  68. descriptionFileRoot: result.directory,
  69. relativePath: relativePath
  70. };
  71. resolver.doResolve(
  72. target,
  73. obj,
  74. "using description file: " +
  75. result.path +
  76. " (relative path: " +
  77. relativePath +
  78. ")",
  79. resolveContext,
  80. (err, result) => {
  81. if (err) return callback(err);
  82. // Don't allow other processing
  83. if (result === undefined) return callback(null, null);
  84. callback(null, result);
  85. }
  86. );
  87. }
  88. );
  89. }
  90. );
  91. }
  92. };