11'use strict' ;
22
33const fs = require ( 'fs' ) ;
4+ const path = require ( 'path' ) ;
45
56const HANDLEBARS_REGEX = / \. ( h b s | h a n d l e b a r s ) $ / ;
67
8+ const NODE_MODULE_DIRECTORIES = [
9+ path . join ( __dirname , '../node_modules' ) ,
10+ path . join ( process . cwd ( ) , 'node_modules' )
11+ ] ;
12+
13+ /**
14+ * Find which node_modules directory to load package from.
15+ *
16+ * findPackagePath('doxdox-parser-dox').then(parser => {});
17+ * findPackagePath('doxdox-plugin-bootstrap').then(plugin => {});
18+ *
19+ * @param {String } pkg Package name as string.
20+ * @return {Object } Promise
21+ * @private
22+ */
23+
24+ const findPackagePath = pkg =>
25+ Promise . all ( NODE_MODULE_DIRECTORIES . map ( dir => new Promise ( resolve => {
26+
27+ const path = `${ dir } /${ pkg } ` ;
28+
29+ fs . stat ( path , ( err , stats ) => {
30+
31+ if ( err ) {
32+
33+ return resolve ( null ) ;
34+
35+ }
36+
37+ if ( stats . isDirectory ( ) ) {
38+
39+ return resolve ( path ) ;
40+
41+ }
42+
43+ return resolve ( null ) ;
44+
45+ } ) ;
46+
47+ } ) ) ) . then ( dirs => dirs . filter ( dir => dir ) ) ;
48+
749/**
850 * Load parser based on user defined choice.
951 *
@@ -17,21 +59,19 @@ const HANDLEBARS_REGEX = /\.(hbs|handlebars)$/;
1759
1860const loadParser = config => new Promise ( ( resolve , reject ) => {
1961
20- try {
62+ findPackagePath ( `doxdox-parser- ${ config . parser } ` ) . then ( plugin => {
2163
22- const parserString = `doxdox-parser- ${ config . parser } ` ;
64+ if ( plugin . length ) {
2365
24- if ( require . resolve ( parserString ) ) {
66+ resolve ( require ( plugin [ 0 ] ) ) ;
2567
26- resolve ( require ( parserString ) ) ;
27-
28- }
68+ } else {
2969
30- } catch ( err ) {
70+ reject ( 'Invalid parser specified.' ) ;
3171
32- reject ( 'Invalid parser specified.' ) ;
72+ }
3373
34- }
74+ } ) ;
3575
3676} ) ;
3777
@@ -53,21 +93,19 @@ const loadPlugin = config => new Promise((resolve, reject) => {
5393
5494 if ( err ) {
5595
56- const layoutString = `doxdox-plugin-${ config . layout } ` ;
57-
58- try {
96+ findPackagePath ( `doxdox-plugin-${ config . layout } ` ) . then ( plugin => {
5997
60- if ( require . resolve ( layoutString ) ) {
98+ if ( plugin . length ) {
6199
62- resolve ( require ( layoutString ) ) ;
100+ resolve ( require ( plugin [ 0 ] ) ) ;
63101
64- }
102+ } else {
65103
66- } catch ( err ) {
104+ reject ( 'Invalid layout specified.' ) ;
67105
68- reject ( 'Invalid layout specified.' ) ;
106+ }
69107
70- }
108+ } ) ;
71109
72110 } else if ( stats && stats . isFile ( ) && config . layout . match ( HANDLEBARS_REGEX ) ) {
73111
@@ -86,6 +124,7 @@ const loadPlugin = config => new Promise((resolve, reject) => {
86124} ) ;
87125
88126module . exports = {
127+ findPackagePath,
89128 loadParser,
90129 loadPlugin
91130} ;
0 commit comments