Load a module

Loads a local or npm module. If the module name starts with an . a local module will be loaded.

@param  {string} module Loads a module
@return {any}      Returns the loaded module.
6029
function(file) {
        if (require.alias && require.alias[file]) {
            file = require.alias[file];
        }

        var module = {
            exports: {},
            file: file
        };

        file = require.resolve(this && this.file ? this.file : './', file);

        var requireFunc = require.bind({
            file: file
        });

        if (window.require.cache[file]) {
            if (window.require.cache[file].obj) {
                return window.require.cache[file].obj;
            }

            window.require.cache[file].fn(module, module.exports, requireFunc);
            window.require.cache[file].obj = module.exports;
            return window.require.cache[file].obj;
        }

        if (!window.require.autoload || (window.require.autoload && file.charAt(0) !== '.')) {
            throw new Error('Module ' + file + ' not found!');
        }

        var remoteFile = location.protocol
            .concat('//', location.host)
            .concat(file.substr(1));
        
        var xhr = new XMLHttpRequest();
        xhr.open('GET', remoteFile, false);
        xhr.send();
        if (xhr.status !== 200) {
            throw new Error('Could not load module "' + file + '"! Response error: ' +
                xhr.status + ' ' + xhr.statusText);
        }
        var source = xhr.responseText;

        var fn;
        try {
            //jshint evil:true
            fn = eval('(function(module, exports, require) {\n' +
                (/\.json$/.test(file) ? 'module.exports = ' : '') +
                source + '\n})\n\n//# sourceURL=' + file);
        }
        catch (err) {
            throw new Error(err + ' in ' + file);
        }

        fn(module, module.exports, require.bind(requireFunc));
        window.require.cache[file] = {
            fn: fn,
            calls: 1,
            obj: module.exports,
            loaded: true
        };

        return window.require.cache[file].obj;
    }
1231790
function isLoaded(modulesNames) {
                    var moduleLoaded = function moduleLoaded(module) {
                        var isLoaded = regModules.indexOf(module) > -1;
                        if (!isLoaded) {
                            isLoaded = !!moduleExists(module);
                        }
                        return isLoaded;
                    };
                    if (angular.isString(modulesNames)) {
                        modulesNames = [modulesNames];
                    }
                    if (angular.isArray(modulesNames)) {
                        var i, len;
                        for (i = 0, len = modulesNames.length; i < len; i++) {
                            if (!moduleLoaded(modulesNames[i])) {
                                return false;
                            }
                        }
                        return true;
                    } else {
                        throw new Error('You need to define the module(s) name(s)');
                    }
                }
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;
    }
738741
def load_module(self, mod):
        
        try:
            return sys.modules[mod]
        except KeyError:
            pass

        lib = ExtensionImporter.extension_modules[mod]
        m = imp.load_dynamic(mod, lib)
        sys.modules[mod] = m
        return m
1121861
function findNodeModule(name) {
  return loadModules()
  .then(nodeModules => {
    const nodeModule = _.find(nodeModules, (nodeModule) => { return nodeModule.getName() === name; });
    if (!nodeModule) {
      throw new Error('The node module "' + name + '" does not exists in this Myrmex project');
    }
    return nodeModule;
  });
}
442007
function getModule(parent, id) {
		if ('require' === id || 'exports' === id || 'module' === id) {
			return { id:id, loaded:true, exports:parent[id] || parent, children:[] };
		}

		id = resolve(parent, id).replace(/\.js$/i, '');
		if (modules[id]) { return modules[id]; }
		var uri = canonicalize(urls[id] ? urls[id] : path.replace(/[^\/]*$/, id + '.js')),
			module = (modules[id] = { id:id, filename:uri, uri:uri, loaded:false, children:[] });
		module.require = makeRequire(module);
		waits[id] = [];
		return module;
	}
1191387
function (options, callback) {
        options = extend({}, MODULE_LOADER_DEFAULTS, options)
        var modulesFolder = options.uri

        iterateFiles(modulesFolder, loadModule, callback, isJsFile)

        function loadModule(fileName) {
            if (options.skip && options.skip.test(fileName)) {
                return
            }
            var module = require(fileName)
            var name = path.relative(options.uri, fileName)
            options.core.add(name, module)
        }
    }
423129
function(parentModule, id, callback) {

  // Try to load the module.
  return Promise.try(function() {
    return parentModule.require(id);
  })
  // Ignore module not found errors, and decorate all others.
  .catch(function(err) {
    if (err.code !== 'MODULE_NOT_FOUND') {
      throw new KboxRequireError(id, err);
    }
  })
  // Return.
  .nodeify(callback);

}
1212518
def load_module(self, name):
        
        if name not in sys.modules:
            sys.modules[name] = getattr(maps, name.split('.')[2])
        return sys.modules[name]
1145564
def load_module(filename):
    
    path, name = os.path.split(filename)
    name, ext = os.path.splitext(name)
    (file, filename, desc) = imp.find_module(name, [path])

    try:
        return imp.load_module(name, file, filename, desc)
    finally:
        if file:
            file.close()
392726
function unloadModule (module) {
    var found_module = false;

    registered_modules = _.reject(registered_modules, function (registered_module) {
        if (module.toLowerCase() === registered_module.module_name.toLowerCase()) {
            found_module = true;

            registered_module.dispose();
            return true;
        }
    });

    return found_module;
}
510714
def load_module(self, name):
        
        self.loaded_modules.append(name)

        try:
            __import__(name, {}, {}, [])

            mod = sys.modules[name]
            self._run_hooks(name, mod)
        except:
            self.loaded_modules.pop()

            raise

        return mod
77536
function getModule (name) {
    // create new module if it does not already exist
    if (!defined(immutableApp.modules[name])) {
        // create module
        immutableApp.modules[name] = new ImmutableAppModule(name)
        // add to list
        immutableApp.moduleNames.push(name)
    }
    // return module
    return immutableApp.modules[name]
}
454441
function loadModule(requires, fullModuleName, loadedModuleData) {
    return new Promise(function(resolve, reject) {
      // First off, try and find this module using callProcessor
      Espruino.callProcessor("getModule",
        { moduleName:fullModuleName, moduleCode:undefined, isMinified:false },
        function(data) {
          if (data.moduleCode===undefined) {
            Espruino.Core.Notifications.warning("Module "+fullModuleName+" not found");
            return resolve();
          }

          // great! it found something. Use it.
          moduleLoaded(resolve, requires, fullModuleName, data.moduleCode, loadedModuleData, data.isMinified);
        });
    });
  }
746271
function thisModule() {
    var self = this;

    /**
     * Loads iteratively all modules at given path, builds and returns a directory of modules as tree or as list
     *
     * Go through each object, include the code, and determine its identity.
     * Tolerates non-existent files/directories by ignoring them (if 'optional' is specified)
     *
     * @param {Object} options {
        dirname			:: the path to the source directory

        mode            :: options: {list, tree}
                           - list: generate a flat key-value map of modules
                           - tree: generate a full tree of modules

        injectIdentity	:: If disabled, (explicitly set to false) don't inject an identity into the module
                           default: true

        optional		:: if enabled, fail silently and return {} when source directory does not exist
                           or cannot be read (otherwise, exit w/ an error)
                           default: false

        depth			:: the level of recursion where modules will be included
                           default is to infinity

        useVersions  :: creates a sub grouping based on version property (only valid for list mode)
                           default: 'false'

        fileNameFilter	:: only include modules whose FILENAME matches this regex,
                           if 'undefined' - include all, default 'undefined'

        relativePathFilter	:: only include modules whose RELATIVE PATH (path with filename) matches this regex
                           (relative from the entry point directory), if 'undefined' - include all,
                           default 'undefined'

        excludeDirs	    :: regex to exclude directories

        dontLoad		:: if `dontLoad` is set to true, don't run the module w/ V8 or load it into memory--
                           instead, return a tree representing the directory structure
                           (all extant file leaves are included as keys, with their value = `true`)
     }
     * @returns dictionary of modules as list or as tree
     */
    self.requireAll = function (options) {

        //================
        // check options and extend default values
        options.replaceVal = options.replaceVal || '';

        if (!options.mode) {
            options.mode = 'list';
        }

        // exclude source control directories
        if (!options.excludeDirs) {
            options.excludeDirs = /^\.(git|svn)$/;
        }

        // default for 'fileNameFilter' option
        if (!options.fileNameFilter) {
            options.fileNameFilter = /(.*)/;
        }

        var iterationInfo = {
            currentDepth: 0,
            dirName: options.dirName,
            initialDirName: options.dirName
        };


        if (options.moduleDir) {
            return  checkModuleDir(options, iterationInfo);
        }
        else {
            return doInterations(options, iterationInfo);
        }
    };

    /**
     * Parses a directory and searches for options.module subdir. If found subdir is searched for required files
     * @param options
     * @param iterationInfo
     * @returns {{}}
     */
    var checkModuleDir = function (options, iterationInfo) {
        var files;
        var modules = {};
        var result = {};

        // remember the starting directory
        try {
            files = fs.readdirSync(iterationInfo.dirName);
        } catch (e) {
            if (options.optional)
                return {};
            else
                throw new Error('Directory not found: ' + iterationInfo.dirName);
        }

        // iterate through files in the current directory
        files.forEach(function (fileName) {
            iterationInfo.dirName = iterationInfo.initialDirName + '/' + fileName + '/' + options.moduleDir;
            iterationInfo.projectDir = iterationInfo.initialDirName + '/' + fileName;
            result = _.assign(doInterations(options, iterationInfo), result);
        });

        return result;
    };

    /**
     * Parses a directory (will be then iteratively called for all subdirectories) or loads a file.
     * @param options
     * @param iterationInfo
     * @returns {{}}
     */
    var doInterations = function (options, iterationInfo) {
        var files;
        var modules = {};

        // check if the counter has reached the desired depth indicated in options.depth
        if (typeof options.depth !== 'undefined' &&
            iterationInfo.currentDepth >= options.depth) {
            return;
        }

        // remember the starting directory
        try {
            files = fs.readdirSync(iterationInfo.dirName);
        } catch (e) {
            if (options.optional)
                return {};
            else
                throw new Error('Directory not found: ' + iterationInfo.dirName);
        }

        // iterate through files in the current directory
        files.forEach(function (fileName) {
            iterationInfo.fileName = fileName;
            //get absolute path
            iterationInfo.absolutePath = rtrim(iterationInfo.dirName, '/');
            iterationInfo.absoluteFullPath = iterationInfo.absolutePath + '/' + fileName;
            //get relative path
            iterationInfo.relativePath = iterationInfo.absolutePath.replace(iterationInfo.initialDirName, '');
            iterationInfo.relativeFullPath = iterationInfo.absoluteFullPath.replace(iterationInfo.initialDirName, '');
            // make sure a slash exists on the left side of relative paths
            iterationInfo.relativePath = '/' + ltrim(iterationInfo.relativePath, '/');
            iterationInfo.relativeFullPath = '/' + ltrim(iterationInfo.relativeFullPath, '/');

            if (fs.statSync(iterationInfo.absoluteFullPath).isDirectory()) {
                processDirectory(options, iterationInfo, modules)
            }
            else {
                processFile(options, iterationInfo, modules);
            }
        });

        return modules;
    };

    /**
     * Process single file to module dictionary
     * @param options
     * @param fileName
     * @param modules
     */
    var processFile = function (options, iterationInfo, modules) {
        // filename filter
        if (options.fileNameFilter) {
            var match = iterationInfo.fileName.match(options.fileNameFilter);
            if (!match) {
                return;
            }
        }

        // Filter spec.js files
        var match = iterationInfo.fileName.match(/.spec.js/i);
        if (match) {
            return;
        }

        // relative path filter
        if (options.relativePathFilter) {
            var pathMatch = iterationInfo.relativeFullPath.match(options.relativePathFilter);
            if (!pathMatch)
                return;
        }

        //load module
        loadModule(modules, options, iterationInfo);
    };

    /**
     * Load single module
     * @param modules
     * @param options
     * @param iterationInfo
     */
    var loadModule = 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;
            }
        }
    };

    /**
     * Generates identity for a module
     * @param options
     * @param iterationInfo
     * @returns {string}
     */
    var generateIdentity = function (options, iterationInfo) {
        // Use the identity for the key name
        var identity;
        if (options.mode === 'list') {
            identity = iterationInfo.relativeFullPath;
            //identity = identity.toLowerCase();
            //find and replace all containments of '/', ':' and '\' within the string
            identity = identity.replace(/\/|\\|:/g, '');
        }
        else if (options.mode === 'tree') {
            identity = iterationInfo.fileName;
            //identity = identity.toLowerCase();
        }
        else
            throw new Error('Unknown mode');

        //remove extention
        identity = identity.substr(0, identity.lastIndexOf('.')) || identity;

        return identity;
    };

    /**
     * Processes one directory level
     * @param options :: general options
     * @param iterationInfo :: iteration options
     * @param modules :: object in which output will be loaded
     */
    var processDirectory = function (options, iterationInfo, modules) {

        // Ignore explicitly excluded directories
        if (options.excludeDirs) {
            var match = iterationInfo.fileName.match(options.excludeDirs);
            if (match)
                return;
        }

        // Recursively call requireAll on each child directory
        var subIterationInfo = _.clone(iterationInfo);
        ++subIterationInfo.depth;
        subIterationInfo.dirName = iterationInfo.absoluteFullPath;

        //process subtree recursively
        var subTreeResult = doInterations(options, subIterationInfo);

        //omit empty dirs
        if (_.isEmpty(subTreeResult))
            return;

        //add to the list or to the subtree
        if (options.mode === 'list') {
            //check uniqueness
            _.forEach(subTreeResult, function (value, index) {
                if (options.useVersions === true) {
                    modules[index] = modules[index] || {};
                    _.forEach(value, function (versionValue, versionIndex) {
                        if (modules[index][versionIndex])
                            throw new Error("Identity '" + index + "' with version '" + versionIndex + "' is already registered by module at '" + modules[index][versionIndex].absoluteFullPath + "'");
                        modules[index][versionIndex] = versionValue;
                    });
                }
                else {
                    if (modules[index])
                        throw new Error("Identity '" + index + "' is already registered by module at '" + modules[index].absoluteFullPath + "'");
                    modules[index] = value;
                }
            })
        }
        else if (options.mode === 'tree') {
            if (options.markDirectories !== false) {
                subTreeResult.isDirectory = true;
            }

            var identity = generateIdentity(options, iterationInfo);
            modules[identity] = subTreeResult;
        }
        else
            throw new Error('Unknown mode');
    };

    return self;
}
148835
function (commonModulesToLoad) {
            this._rootModule.loadModules(null, {
                page : [],
                common : commonModulesToLoad
            }, {
                fn : this._onSiteReady,
                scope : this
            });
        }
772434
function require(p) {
  var path = require.resolve(p)
  var module = require.modules[path];
  if(!module) throw("couldn't find module for: " + p);
  if(!module.exports) {
    module.exports = {};
    module.call(module.exports, module, module.exports, require.bind(path));
  }
  return module.exports;
}