[79a0317] | 1 | /*
|
---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
| 3 | Author Ivan Kopeykin @vankop
|
---|
| 4 | */
|
---|
| 5 |
|
---|
| 6 | "use strict";
|
---|
| 7 |
|
---|
| 8 | const forEachBail = require("./forEachBail");
|
---|
| 9 |
|
---|
| 10 | /** @typedef {import("./Resolver")} Resolver */
|
---|
| 11 | /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
|
---|
| 12 | /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
|
---|
| 13 |
|
---|
| 14 | class RootsPlugin {
|
---|
| 15 | /**
|
---|
| 16 | * @param {string | ResolveStepHook} source source hook
|
---|
| 17 | * @param {Set<string>} roots roots
|
---|
| 18 | * @param {string | ResolveStepHook} target target hook
|
---|
| 19 | */
|
---|
| 20 | constructor(source, roots, target) {
|
---|
| 21 | this.roots = Array.from(roots);
|
---|
| 22 | this.source = source;
|
---|
| 23 | this.target = target;
|
---|
| 24 | }
|
---|
| 25 |
|
---|
| 26 | /**
|
---|
| 27 | * @param {Resolver} resolver the resolver
|
---|
| 28 | * @returns {void}
|
---|
| 29 | */
|
---|
| 30 | apply(resolver) {
|
---|
| 31 | const target = resolver.ensureHook(this.target);
|
---|
| 32 |
|
---|
| 33 | resolver
|
---|
| 34 | .getHook(this.source)
|
---|
| 35 | .tapAsync("RootsPlugin", (request, resolveContext, callback) => {
|
---|
| 36 | const req = request.request;
|
---|
| 37 | if (!req) return callback();
|
---|
| 38 | if (!req.startsWith("/")) return callback();
|
---|
| 39 |
|
---|
| 40 | forEachBail(
|
---|
| 41 | this.roots,
|
---|
| 42 | /**
|
---|
| 43 | * @param {string} root root
|
---|
| 44 | * @param {(err?: null|Error, result?: null|ResolveRequest) => void} callback callback
|
---|
| 45 | * @returns {void}
|
---|
| 46 | */
|
---|
| 47 | (root, callback) => {
|
---|
| 48 | const path = resolver.join(root, req.slice(1));
|
---|
| 49 | /** @type {ResolveRequest} */
|
---|
| 50 | const obj = {
|
---|
| 51 | ...request,
|
---|
| 52 | path,
|
---|
| 53 | relativePath: request.relativePath && path
|
---|
| 54 | };
|
---|
| 55 | resolver.doResolve(
|
---|
| 56 | target,
|
---|
| 57 | obj,
|
---|
| 58 | `root path ${root}`,
|
---|
| 59 | resolveContext,
|
---|
| 60 | callback
|
---|
| 61 | );
|
---|
| 62 | },
|
---|
| 63 | callback
|
---|
| 64 | );
|
---|
| 65 | });
|
---|
| 66 | }
|
---|
| 67 | }
|
---|
| 68 |
|
---|
| 69 | module.exports = RootsPlugin;
|
---|