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 DescriptionFileUtils = require("./DescriptionFileUtils");
|
---|
9 |
|
---|
10 | /** @typedef {import("./Resolver")} Resolver */
|
---|
11 | /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
|
---|
12 |
|
---|
13 | const slashCode = "/".charCodeAt(0);
|
---|
14 |
|
---|
15 | module.exports = class SelfReferencePlugin {
|
---|
16 | /**
|
---|
17 | * @param {string | ResolveStepHook} source source
|
---|
18 | * @param {string | string[]} fieldNamePath name path
|
---|
19 | * @param {string | ResolveStepHook} target target
|
---|
20 | */
|
---|
21 | constructor(source, fieldNamePath, target) {
|
---|
22 | this.source = source;
|
---|
23 | this.target = target;
|
---|
24 | this.fieldName = fieldNamePath;
|
---|
25 | }
|
---|
26 |
|
---|
27 | /**
|
---|
28 | * @param {Resolver} resolver the resolver
|
---|
29 | * @returns {void}
|
---|
30 | */
|
---|
31 | apply(resolver) {
|
---|
32 | const target = resolver.ensureHook(this.target);
|
---|
33 | resolver
|
---|
34 | .getHook(this.source)
|
---|
35 | .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => {
|
---|
36 | if (!request.descriptionFilePath) return callback();
|
---|
37 |
|
---|
38 | const req = request.request;
|
---|
39 | if (!req) return callback();
|
---|
40 |
|
---|
41 | // Feature is only enabled when an exports field is present
|
---|
42 | const exportsField = DescriptionFileUtils.getField(
|
---|
43 | request.descriptionFileData,
|
---|
44 | this.fieldName
|
---|
45 | );
|
---|
46 | if (!exportsField) return callback();
|
---|
47 |
|
---|
48 | const name = DescriptionFileUtils.getField(
|
---|
49 | request.descriptionFileData,
|
---|
50 | "name"
|
---|
51 | );
|
---|
52 | if (typeof name !== "string") return callback();
|
---|
53 |
|
---|
54 | if (
|
---|
55 | req.startsWith(name) &&
|
---|
56 | (req.length === name.length ||
|
---|
57 | req.charCodeAt(name.length) === slashCode)
|
---|
58 | ) {
|
---|
59 | const remainingRequest = `.${req.slice(name.length)}`;
|
---|
60 |
|
---|
61 | const obj = {
|
---|
62 | ...request,
|
---|
63 | request: remainingRequest,
|
---|
64 | path: /** @type {string} */ (request.descriptionFileRoot),
|
---|
65 | relativePath: "."
|
---|
66 | };
|
---|
67 |
|
---|
68 | resolver.doResolve(
|
---|
69 | target,
|
---|
70 | obj,
|
---|
71 | "self reference",
|
---|
72 | resolveContext,
|
---|
73 | callback
|
---|
74 | );
|
---|
75 | } else {
|
---|
76 | return callback();
|
---|
77 | }
|
---|
78 | });
|
---|
79 | }
|
---|
80 | };
|
---|