1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const path = require("path");
|
---|
9 | const DescriptionFileUtils = require("./DescriptionFileUtils");
|
---|
10 |
|
---|
11 | /** @typedef {import("./Resolver")} Resolver */
|
---|
12 | /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
|
---|
13 | /** @typedef {{name: string|Array<string>, forceRelative: boolean}} MainFieldOptions */
|
---|
14 |
|
---|
15 | const alreadyTriedMainField = Symbol("alreadyTriedMainField");
|
---|
16 |
|
---|
17 | module.exports = class MainFieldPlugin {
|
---|
18 | /**
|
---|
19 | * @param {string | ResolveStepHook} source source
|
---|
20 | * @param {MainFieldOptions} options options
|
---|
21 | * @param {string | ResolveStepHook} target target
|
---|
22 | */
|
---|
23 | constructor(source, options, target) {
|
---|
24 | this.source = source;
|
---|
25 | this.options = options;
|
---|
26 | this.target = target;
|
---|
27 | }
|
---|
28 |
|
---|
29 | /**
|
---|
30 | * @param {Resolver} resolver the resolver
|
---|
31 | * @returns {void}
|
---|
32 | */
|
---|
33 | apply(resolver) {
|
---|
34 | const target = resolver.ensureHook(this.target);
|
---|
35 | resolver
|
---|
36 | .getHook(this.source)
|
---|
37 | .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => {
|
---|
38 | if (
|
---|
39 | request.path !== request.descriptionFileRoot ||
|
---|
40 | request[alreadyTriedMainField] === request.descriptionFilePath ||
|
---|
41 | !request.descriptionFilePath
|
---|
42 | )
|
---|
43 | return callback();
|
---|
44 | const filename = path.basename(request.descriptionFilePath);
|
---|
45 | let mainModule = DescriptionFileUtils.getField(
|
---|
46 | request.descriptionFileData,
|
---|
47 | this.options.name
|
---|
48 | );
|
---|
49 |
|
---|
50 | if (
|
---|
51 | !mainModule ||
|
---|
52 | typeof mainModule !== "string" ||
|
---|
53 | mainModule === "." ||
|
---|
54 | mainModule === "./"
|
---|
55 | ) {
|
---|
56 | return callback();
|
---|
57 | }
|
---|
58 | if (this.options.forceRelative && !/^\.\.?\//.test(mainModule))
|
---|
59 | mainModule = "./" + mainModule;
|
---|
60 | const obj = {
|
---|
61 | ...request,
|
---|
62 | request: mainModule,
|
---|
63 | module: false,
|
---|
64 | directory: mainModule.endsWith("/"),
|
---|
65 | [alreadyTriedMainField]: request.descriptionFilePath
|
---|
66 | };
|
---|
67 | return resolver.doResolve(
|
---|
68 | target,
|
---|
69 | obj,
|
---|
70 | "use " +
|
---|
71 | mainModule +
|
---|
72 | " from " +
|
---|
73 | this.options.name +
|
---|
74 | " in " +
|
---|
75 | filename,
|
---|
76 | resolveContext,
|
---|
77 | callback
|
---|
78 | );
|
---|
79 | });
|
---|
80 | }
|
---|
81 | };
|
---|