Debian Codegraph @

ncjsm/get-dependencies.js

raw
1 "use strict";
2
3 const uniq = require("es5-ext/array/#/uniq")
4 , ensureString = require("type/string/ensure")
5 , isObject = require("type/object/is")
6 , deferred = require("deferred")
7 , { dirname, resolve } = require("path")
8 , readFile = require("fs2/read-file")
9 , findRequires = require("find-requires")
10 , builtinModules = new Set(require("builtin-modules"))
11 , cjsResolve = require("./resolve");
12
13 const nonLocalChar = new Set([".", "/"]);
14
15 const getDirectDependencies = function (modulePath, options) {
16 return readFile(modulePath)(content => {
17 const dir = dirname(modulePath);
18 return deferred.map(
19 uniq.call(
20 findRequires(content, {
21 setupCode: `var __filename = ${ JSON.stringify(modulePath) }, __dirname = ${
22 JSON.stringify(dir)
23 };`
24 })
25 ),
26 depPath => {
27 if (!nonLocalChar.has(depPath[0])) {
28 if (options.ignoreExternal) return null;
29 if (builtinModules.has(depPath.split("/")[0])) return null;
30 }
31 return cjsResolve(dir, depPath, { silent: true })(pathData => {
32 if (pathData) return pathData.targetPath;
33 if (options.ignoreMissing) return null;
34 throw new Error(
35 `Could not resolve ${ JSON.stringify(depPath) } module, required in ${
36 JSON.stringify(modulePath)
37 }`
38 );
39 });
40 }
41 )(paths => uniq.call(paths).filter(Boolean));
42 });
43 };
44
45 module.exports = function (programPath, options = {}) {
46 if (!isObject(options)) options = {};
47 programPath = resolve(ensureString(programPath));
48 const paths = Object.create(null);
49 return (function self(modulePath) {
50 if (paths[modulePath]) return null;
51 return (paths[modulePath] = getDirectDependencies(modulePath, options).map(self));
52 })(programPath)(() => Object.keys(paths));
53 };