Find or create a flapjack based on a relative path from the project root
@param modulePath
@param moduleStack
@param options
@returns {{}}
352028
function create(modulePath, moduleStack, options) {

        // the 'FromPlugin' suffix is used when a project wants to override a plugin module
        if (modulePath === /.*FromPlugin/) {
            modulePath = modulePath.substring(0, modulePath.length - 10);
        }
        modulePath = modulePath.toLowerCase();

        // first check the cache to see if we already loaded it
        if (this.cache[modulePath]) {
            return this.cache[modulePath];
        }

        // if module not in server modules, return null
        var flapjack = this.serverModules[modulePath];
        if (!flapjack) {
            return null;
        }

        // switch to server if exists
        flapjack = flapjack.server ? flapjack.server : flapjack;

        // if flapjack is not a function, just return it (i.e. its just a normal require()
        if (!_.isFunction(flapjack)) {
            this.cache[modulePath] = flapjack;
            return flapjack;
        }

        this.cache[modulePath] = this.injector.injectFlapjack(flapjack, moduleStack, options);
        return this.cache[modulePath];
    }
431548
function loadModule (baseLoader, fromDir, fromFile, item, opts) {
      var modulePath = item.from;
      var possibilities = util.resolveModulePath(modulePath, fromDir);
      for (var i = 0, p; p = possibilities[i]; ++i) {
        var path = possibilities[i].path;
        if (!opts.reload && (path in jsio.__modules)) {
          return possibilities[i];
        }

        if (path in failedFetch) { possibilities.splice(i--, 1); }
      }

      if (!possibilities.length) {
        if (opts.suppressErrors) { return false; }
        var e = new Error('Could not import `' + item.from + '`'
            + "\tImport Stack:\n"
            + "\t\t" + processStack().join("\n\t\t"));
        e.jsioLogged = true;
        e.code = MODULE_NOT_FOUND;
        throw e;
      }

      var moduleDef = findModule(possibilities);
      if (!moduleDef) {
        if (opts.suppressErrors) { return false; }
        var paths = [];
        for (var i = 0, p; p = possibilities[i]; ++i) { paths.push(p.path); }
        var e = new Error("Could not import `" + modulePath + "`\n"
          + "\tlooked in:\n"
            + "\t\t" + paths.join('\n\t\t') + "\n"
            + "\tImport Stack:\n"
            + "\t\t" + processStack().join("\n\t\t"));
        e.code = MODULE_NOT_FOUND;
        throw e;
      }

      // a (potentially) nicer way to refer to a module -- how it was referenced in code when it was first imported
      moduleDef.friendlyPath = modulePath;

      // cache the base module's path in the path cache so we don't have to
      // try out all paths the next time we see the same base module.
      if (moduleDef.baseMod && !(moduleDef.baseMod in jsioPath.cache)) {
        jsioPath.cache[moduleDef.baseMod] = moduleDef.basePath;
      }

      // don't apply the standard preprocessors to base.js.  If we're reloading
      // the source code, always apply them.  We also don't want to run them
      // if they've been run once -- moduleDef.pre is set to true already
      // if we're reading the code from the source cache.
      if (modulePath != 'base' && (opts.reload || !opts.dontPreprocess && !moduleDef.pre)) {
        moduleDef.pre = true;

        applyPreprocessors(fromDir, moduleDef, ["import", "inlineSlice"], opts);
      }

      // any additional preprocessors?
      if (opts.preprocessors) {
        applyPreprocessors(fromDir, moduleDef, opts.preprocessors, opts);
      }

      return moduleDef;
    }
322346
function getAdditionalModulePaths(options = {}) {
  const baseUrl = options.baseUrl;

  // We need to explicitly check for null and undefined (and not a falsy value) because
  // TypeScript treats an empty string as `.`.
  if (baseUrl == null) {
    // If there's no baseUrl set we respect NODE_PATH
    // Note that NODE_PATH is deprecated and will be removed
    // in the next major release of create-react-app.

    const nodePath = process.env.NODE_PATH || '';
    return nodePath.split(path.delimiter).filter(Boolean);
  }

  const baseUrlResolved = path.resolve(paths.appPath, baseUrl);

  // We don't need to do anything if `baseUrl` is set to `node_modules`. This is
  // the default behavior.
  if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
    return null;
  }

  // Allow the user set the `baseUrl` to `appSrc`.
  if (path.relative(paths.appSrc, baseUrlResolved) === '') {
    return [paths.appSrc];
  }

  // Otherwise, throw an error.
  throw new Error(
    chalk.red.bold(
      "Your project's `baseUrl` can only be set to `src` or `node_modules`." +
        ' Create React App does not support other values at this time.'
    )
  );
}
330518
function findModulePath(moduleName, currentState) {
    const cwd = currentState.get('cwd');

    if (currentState.get('global')) {
        return path.join(cwd, moduleName);
    }

    // Module._nodeModulePaths does not include some places the node module resolver searches, such as
    // the global prefix or other special directories. This is desirable because if a module is missing
    // in the project directory we want to be sure to report it as missing.
    // We can't use require.resolve because it fails if the module doesn't have an entry point.
    const nodeModulesPaths = Module._nodeModulePaths(cwd);
    const possibleModulePaths = nodeModulesPaths.map(x => path.join(x, moduleName));
    const modulePath = possibleModulePaths.find(pathExists.sync);

    // if no existing path was found, return the first tried path anyway
    return modulePath || path.join(cwd, moduleName);
}
64106
function resolveModulePath(relativeToFile, modulePath) {
  if (!isLocalModule(modulePath)) {
    return modulePath;
  }

  const alias = getModuleResolverAlias();
  const matched = _.find(_.keys(alias), k => _.startsWith(modulePath, k));

  let res = null;
  if (matched) {
    const resolveTo = alias[matched];
    const relativePath = modulePath.replace(new RegExp(`^${matched}`), '').replace(/^\//, '');
    res = paths.map(resolveTo, relativePath);
    // res = utils.joinPath(utils.getProjectRoot(), resolveTo, relativePath);
  } else {
    res = paths.join(path.dirname(relativeToFile), modulePath);
  }

  let relPath = res.replace(paths.getProjectRoot(), '').replace(/^\/?/, '');
  if (vio.dirExists(relPath)) {
    // if import from a folder, then resolve to index.js
    relPath = paths.join(relPath, 'index');
  }
  return relPath;
}
1040587
function transform(flapjack, options) {
    var filePath    = options.filePath;
    var names       = this.parseNames(filePath, options.prefix, options.appName);
    var uipart      = this.loadUIPart(names.appShortName, filePath);

    // if there is no client side module for this ui part, return resolved
    if (!uipart.view || uipart.serverOnly || uipart.abstract) { return null; }

    // use the uipart to get the directive scope (for partials), view html and controller
    var scope = uipart.scope ? JSON.stringify(uipart.scope) : null;
    var html = this.getHtml(uipart, options);

    if (options.htmlOnly) {
        return html;
    }

    options.isPage = names.isPage;
    var ctrlTemplateModel = this.getCtrlTemplateModel(uipart, options);

    // combine all the data we have into one templateModel that will go into the template
    var templateModel = _.extend(ctrlTemplateModel, names, { directiveScope: scope, viewHtml: html });

    //TODO: refactor this; complete hack to add initialModel to sideviews
    if (names.controllerName.match(/Sideview/)) {
        templateModel.params = templateModel.params || [];
        templateModel.convertedParams = templateModel.convertedParams || [];
        templateModel.params.push('initialModel');
        templateModel.convertedParams.push('initialModel');
    }

    // return the generated code
    return this.template(templateModel);
}
938916
File findNodeModulesNearestMatch(File requiringFile, String requireText) throws IOException {
        if ( requiringFile == null )
            return null;
        if ( !requireText.startsWith(".") ) {
            File f = new File(requiringFile, "node_modules/" + requireText);
            if (f.exists())
                return new File(TimeStampedFileCache.getCanonicalPath(f));
            f = new File(requiringFile, "node_modules/" + requireText + ".js");
            if (f.exists())
                return new File(TimeStampedFileCache.getCanonicalPath(f));
            return findNodeModulesNearestMatch(requiringFile.getParentFile(), requireText);
        } else {
            File f = new File(requiringFile.getParentFile(),requireText);
            if ( ! f.exists() )
                f =  new File(requiringFile.getParentFile(),requireText+".js");
            if ( f.exists() )
                return new File(TimeStampedFileCache.getCanonicalPath(f));
        }
        return null;
    }
998348
function(kbox, id, app, callback) {

  if (typeof callback === 'undefined' && typeof app === 'function') {
    callback = app;
    app = undefined;
  }

  // Get global config.
  var globalConfig = kbox.core.deps.lookup('globalConfig');

  // List of dirs that we care about.
  var dirs = [
    globalConfig.srcRoot,
    globalConfig.sysPluginRoot,
    globalConfig.userPluginRoot
  ];
  if (app) {
    dirs.push(app.config.appRoot);
  }

  // Each dir could have any of these sub dirs.
  var subDirs = [
    'node_modules',
    'plugins'
  ];

  // Helper function that lodash should be ashamed for not having. :P
  var flattenMap = function(elts, iterator) {
    return _(elts)
    .chain()
    .map(iterator)
    .flatten()
    .value();
  };

  // Map dirs to full list of paths.
  var paths = flattenMap(dirs, function(dir) {
    return _.map(subDirs, function(subDir) {
      return path.join(dir, subDir, id, 'index.js');
    });
  });

  // Filter paths by existance.
  return Promise.filter(paths, fs.existsSync)
  .all()
  // Grabs the last path so that we load things from SRC -> SYS -> USER
  .then(function(paths) {
    return _.last(paths);
  })
  // If a path exists try to require it.
  .then(function(path) {
    if (path) {
      return Promise.try(function() {
        return require(path);
      })
      .catch(function(err) {
        // Decorate the error.
        throw new KboxRequireError(path, err);
      });
    }
  })
  // Return.
  .nodeify(callback);

}
823232
function adaptModulePath(modulePath, state) {
  // const fileName = state.file.opts.filename;
  const options = getStateOptions(state);
  const filesMap = createFilesMap(options);
  const rootPath = getRootPath(options);

  let module = determineContext(modulePath, options);

  // Do not generate infinite cyrcular references on empty nodes
  if (!module.file) {
    return null;
  }

  // Safeguard against circular calls
  if (lastIn === lastOut) {
    return null;
  }

  // Remove relative path prefix before replace
  const absoluteModule = path.isAbsolute(module.file);

  // Try to replace aliased module
  let found = false;
  let constantModulePart;
  filesMap.keys.filter((k) => {
    const d = filesMap.contents[k];
    let idx = module.file.search(d.regexp);

    if (!found && idx > -1) {
      // throw `Found ${d} in ${module.file}`
      // constantModulePart = module.file.slice(0, idx) || './';
      constantModulePart = './';

      if (module.file[idx] === '/') {
        idx += 1;
      }

      const value = d.value[0] === '.' && idx > 0 ? d.value.slice(2) : d.value;
      // const value = d.value;

      // Replace the alias with it's path and continue
      module.file = `${module.file.slice(0, idx) || ''}${value}${module.file.slice(idx + d.expose.length) || ''}`;
      found = true;


      // Revaluate npm and react flags based on the new mapping
      module = determineContext(module.file, options);

      return true;
    }

    return false;
  });

  // Leave NPM modules as resolved, do not remap and ignore wrongfully formatted strings of form require('npm:')
  if (module.npm) {
    return module.file || null;
  }

  // Do not touch direct requires to npm modules (non annotated)
  if (module.file.indexOf('./') !== 0 && module.file.indexOf('/') !== 0) {
    return null;
  }

  // Check if any substitution took place
  if (found) {
    // Module alias substituted
    if (!path.isAbsolute(module.file)) {
      if (!absoluteModule && module.file[0] !== '.') {
        // Add the relative notation back
        module.file = `./${module.file}`;
      }
    }
  }

  // Do not break node_modules required by name
  if (!found && module.file[0] !== '.') {
    if (reactOsFileInfer(options)) {
      const aux2 = mapForReact(module.file);

      if (aux2 !== module.file) {
        return aux2;
      }
    }

    return null;
  }

  // Enforce absolute paths on absolute mode
  if (rootPath) {
    if (!path.isAbsolute(module.file)) {
      module.file = path.join(rootPath, module.file);

      if (reactOsFileInfer(options)) {
        return mapForReact(module.file);
      }

      return module.file;
    }

    // After the node is replaced the visitor will be called again.
    // Without this condition these functions will generate a circular loop.
    return null;
  }

  // throw `Gets here: ${JSON.stringify(module.file)}`;

  // Do not bother with relative paths that are not aliased
  if (!found) {
    return null;
  }

  let moduleMapped = mapToRelative(module.file, constantModulePart, options);
  if (moduleMapped.indexOf('./') !== 0) {
    moduleMapped = `./${moduleMapped}`;
  }

  // throw JSON.stringify({
  //   moduleMapped, modulePath, module, constantModulePart
  // }, null, 2);
  return moduleMapped !== modulePath ? moduleMapped : null;
}
1007717
public static ModuleConfig getModuleConfig( String modulePath, ServletContext context )
    {
        return ( ModuleConfig ) context.getAttribute( Globals.MODULE_KEY + modulePath );
    }
422469
ModuleConfig findActionInStack(String actionPath)
    {
        for ( int i = _stack.size() - 1; i >= 0; --i )
        {
            ModuleConfig moduleConfig = ((PushedPageFlow) _stack.elementAt(i)).getPageFlow().getModuleConfig();
            
            if (moduleConfig.findActionConfig(actionPath) != null) {
                return moduleConfig;
            }
        }
    
        return null;
    }
1028868
function requireWrapper(baseModule, moduleId)
{
  var componentPath
      // translate module to path alias
    , modulePath = this.checkPath(moduleId)
      // get first part of the module path
    , component = (modulePath || '').split('/')[0]
    ;

  // shortcut for `empty:` path
  if (modulePath == 'empty:')
  {
    return {};
  }

  // check if name and path belong to the app or to node_modules
  if (component && component[0] != '.')
  {
    // - existing file vs. node_modules case
    if (component == modulePath)
    {
      componentPath = path.resolve(this.basePath, modulePath + '.js');
    }
    // - existing folder vs. node_modules member case
    else
    {
      componentPath = path.resolve(this.basePath, component);
    }

    if (fs.existsSync(componentPath))
    {
      // everything fits nicely, get the full thing
      // file might not exist at this point
      // but its legit developer's error
      modulePath = path.resolve(this.basePath, modulePath);
    }
  }

  if (this.disableCache)
  {
    delete require.cache[require.resolve(modulePath)];
  }

  return baseModule.require(modulePath);
}
1341159
function getUiPart(modulePath, options) {
        var rootDir = this.injector.rootDir;
        var tplDir = (options && options.tplDir) || 'dist' + delim + 'tpls';
        var pathParts = modulePath.split(delim);
        var appName = pathParts[1];
        var len = modulePath.length;
        var filePath, fullModulePath, uipart, viewObj;

        // filePath has .js, modulePath does not
        if (modulePath.substring(len - 3) === '.js') {
            filePath = rootDir + delim + modulePath;
            fullModulePath = rootDir + delim + modulePath.substring(0, len - 3);
        }
        else {
            filePath = rootDir + delim + modulePath + '.js';
            fullModulePath = rootDir + delim + modulePath;
        }

        // if exists, get it
        if (fs.existsSync(filePath)) {
            uipart = this.injector.require(fullModulePath);
        }
        // else if in an app folder, try the common folder
        else if (appName !== 'common') {
            fullModulePath = fullModulePath.replace(delim + appName + delim, delim + 'common' + delim);
            uipart = this.injector.require(fullModulePath);
            appName = 'common';
        }

        // if no view, check to see if precompiled in tpl dir
        var viewFile = fullModulePath.replace(
            delim + 'app' + delim + appName + delim,
            delim + tplDir + delim + appName + delim
        );
        if (!uipart.view && fs.existsSync(viewFile + '.js')) {
            viewObj = this.injector.require(viewFile);
            uipart.view = function () {
                return viewObj;
            };
        }

        return uipart;
    }
399629
function ConfigFromPath (superConfig, project, version) {
  ConfigFromPath.super_.call(this, superConfig, project, version);

  var strictNS = simpleWrapNS(this.ns);
  strictNS.env = simpleWrapNS(createNamespace(superConfig.getEnvConfig()));

  var files = superConfig._resolvePaths(project, version);
  var loaded = {};

  var generateLoad = function (f) {
    return function (otherVersion) {
      debug('load(%s) in %s', otherVersion, f);
      var dir = path.dirname(f);
      var otherFile = path.resolve(dir, otherVersion + '.js');
      if (loaded[otherFile]) {
        throw new Error('load(' + version + ') conflict in file ' + f);
      }
      try {
        require(otherFile)(strictNS, generateLoad(otherFile));
      } catch (err) {
        if (err.code === 'MODULE_NOT_FOUND') {
          throw new Error('load(' + version + ') fail in file ' + f);
        } else {
          throw err;
        }
      }
    };
  };
  files.forEach(function (f) {
    debug('load %s', f);
    var init = require(f);
    loaded[f] = true;
    if (typeof init !== 'function') {
      throw new Error('bad config file format, `module.exports` must be a function: ' + f);
    }
    init(strictNS, generateLoad(f));
  });

  var loadedFiles = Object.keys(loaded);
  if (loadedFiles.length < 1) {
    throw new Error('cannot find any config files for ' + project + '.' + version);
  } else {
    loadedFiles.forEach(function (f) {
      delete require.cache[f];
    });
  }

  this._loadFinish();
  debug('done');
}
220652
function injectFlapjack(flapjack, moduleStack, options) {
        options = options || {};

        // if server is false, then return null
        var moduleInfo = annotations.getModuleInfo(flapjack);
        if (moduleInfo && moduleInfo.server === false && !options.test) {
            return null;
        }

        // param map is combo of param map set by user, params discovered and current annotation
        var aliases = _.extend({}, this.aliases, annotations.getServerAliases(flapjack, null));
        var params = annotations.getParameters(flapjack);
        var deps = options.dependencies || {};
        var paramModules = [];
        var me = this;

        // loop through the params so we can collect the object that will be injected
        _.each(params, function (param) {
            var dep = deps[param];

            // if mapping exists, switch to the mapping (ex. pancakes -> lib/pancakes)
            if (aliases[param]) {
                param = aliases[param];
            }

            // either get the module from the input dependencies or recursively call inject
            try {
                paramModules.push(dep || deps[param] || me.loadModule(param, moduleStack));
            }
            catch (ex) {
                var errMsg = ex.stack || ex;
                throw new Error('While injecting function, ran into invalid parameter.\nparam: ' + param +
                '\nstack: ' + JSON.stringify(moduleStack) + '\nfunction: ' +
                flapjack.toString().substring(0, 100) + '...\nerror: ' + errMsg);
            }
        });

        // call the flapjack function passing in the array of modules as parameters
        return flapjack.apply(null, paramModules);
    }
345828
function (modules, options, iterationInfo) {
        // load module into memory (unless `dontLoad` is true)

        var module = true;

        //default is options.dontLoad === false
        if (options.dontLoad !== true) {
            //if module is to be loaded
            module = require(iterationInfo.absoluteFullPath);

            // If a module is found but was loaded as 'undefined', don't include it (since it's probably unusable)
            if (typeof module === 'undefined') {
                throw new Error('Invalid module:' + iterationInfo.absoluteFullPath);
            }

            var identity;
            //var name;
            var version;

            if (options.useVersions === true) {
                if (module.version) {
                    version = module.version;
                }
                else {
                    version = '1.0';
                }
            }

            if (module.identity) {
                identity = module.identity;
                //name = identity;
            }
            else {
                identity = generateIdentity(options, iterationInfo);
                //name = identity;
            }

            //consider default options.injectIdentity === true
            if (options.injectIdentity !== false) {
                module.fileName = iterationInfo.fileName;
                module.projectDir = iterationInfo.projectDir;
                module.relativePath = iterationInfo.relativePath;
                module.relativeFullPath = iterationInfo.relativeFullPath;
                module.absolutePath = iterationInfo.absolutePath;
                module.absoluteFullPath = iterationInfo.absoluteFullPath;
                module.identity = identity;
                //module.name = name;
                if (options.useVersions === true) {
                    module.version = version;
                }
            }
            else {
                identity = generateIdentity(options, iterationInfo);
            }

            //check if identity is unique within the collection and add to dictionary
            if (options.useVersions === true) {
                if (modules[identity] && modules[identity][version]) {
                    var anotherModule = modules[identity][version];
                    throw new Error("Identity '" + identity + "' with version '" + version + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
                }
                modules[identity] = modules[identity] || {};
                modules[identity][version] = module;
            }
            else {
                var anotherModule = modules[identity];
                if (anotherModule) {
                    throw new Error("Identity '" + identity + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
                }
                modules[identity] = module;
            }
        }
    }
1341849
function importerSync(options, handler) {
    var modulePath, recursive = false, parent = '';

    if (typeof options === 'string') {
        modulePath = options;

    } else {
        modulePath = options.path;
        recursive = options.recursive || recursive;
        parent = options.parent || parent;
        if (!modulePath) throw new Error("module directory path must be given.");
    }

    // absolute path? or relevant path?
    if (modulePath.indexOf('/') != 0) {
        // relevant. join with parent module's path
        modulePath = path.join(path.dirname(module.parent.parent.filename), modulePath);
    }

    var files = fs.readdirSync(modulePath);
    for (var i in files) {
        var name = files[i];

        if (recursive && fs.lstatSync(path.join(modulePath, name)).isDirectory()) {
            importerSync({
                path: path.join(modulePath, name),
                recursive: true,
                parent: path.join(parent, name)
            }, handler);
            continue;
        }
        if (name.lastIndexOf('.js') != name.length - 3) continue;

        name = name.substring(0, name.lastIndexOf('.')); // remove ext
        var moduleObj = require(path.join(modulePath, name));
        if (handler) handler(moduleObj, path.join(parent, name));
    }
}