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 LocalModule = require("./LocalModule");
|
---|
9 |
|
---|
10 | /** @typedef {import("../javascript/JavascriptParser").ParserState} ParserState */
|
---|
11 |
|
---|
12 | /**
|
---|
13 | * @param {string} parent parent module
|
---|
14 | * @param {string} mod module to resolve
|
---|
15 | * @returns {string} resolved module
|
---|
16 | */
|
---|
17 | const lookup = (parent, mod) => {
|
---|
18 | if (mod.charAt(0) !== ".") return mod;
|
---|
19 |
|
---|
20 | const path = parent.split("/");
|
---|
21 | const segments = mod.split("/");
|
---|
22 | path.pop();
|
---|
23 |
|
---|
24 | for (let i = 0; i < segments.length; i++) {
|
---|
25 | const seg = segments[i];
|
---|
26 | if (seg === "..") {
|
---|
27 | path.pop();
|
---|
28 | } else if (seg !== ".") {
|
---|
29 | path.push(seg);
|
---|
30 | }
|
---|
31 | }
|
---|
32 |
|
---|
33 | return path.join("/");
|
---|
34 | };
|
---|
35 |
|
---|
36 | /**
|
---|
37 | * @param {ParserState} state parser state
|
---|
38 | * @param {string} name name
|
---|
39 | * @returns {LocalModule} local module
|
---|
40 | */
|
---|
41 | module.exports.addLocalModule = (state, name) => {
|
---|
42 | if (!state.localModules) {
|
---|
43 | state.localModules = [];
|
---|
44 | }
|
---|
45 | const m = new LocalModule(name, state.localModules.length);
|
---|
46 | state.localModules.push(m);
|
---|
47 | return m;
|
---|
48 | };
|
---|
49 |
|
---|
50 | /**
|
---|
51 | * @param {ParserState} state parser state
|
---|
52 | * @param {string} name name
|
---|
53 | * @param {string} [namedModule] named module
|
---|
54 | * @returns {LocalModule | null} local module or null
|
---|
55 | */
|
---|
56 | module.exports.getLocalModule = (state, name, namedModule) => {
|
---|
57 | if (!state.localModules) return null;
|
---|
58 | if (namedModule) {
|
---|
59 | // resolve dependency name relative to the defining named module
|
---|
60 | name = lookup(namedModule, name);
|
---|
61 | }
|
---|
62 | for (let i = 0; i < state.localModules.length; i++) {
|
---|
63 | if (state.localModules[i].name === name) {
|
---|
64 | return state.localModules[i];
|
---|
65 | }
|
---|
66 | }
|
---|
67 | return null;
|
---|
68 | };
|
---|