定义模块

@param {string=} id 模块标识
@param {Array=} dependencies 依赖模块列表
@param {Function=} factory 创建模块的工厂方法
19341
function define() {
        var argsLen = arguments.length;
        if ( !argsLen ) {
            return;
        }

        var id;
        var dependencies;
        var factory = arguments[ --argsLen ];

        while ( argsLen-- ) {
            var arg = arguments[ argsLen ];

            if ( typeof arg === 'string' ) {
                id = arg;
            }
            else if ( isArray( arg ) ) {
                dependencies = arg;
            }
        }

        // 出现window不是疏忽
        // esl设计是做为browser端的loader
        // 闭包的global更多意义在于：
        //     define和require方法可以被挂到用户自定义对象中
        var opera = window.opera;

        // IE下通过current script的data-require-id获取当前id
        if (
            !id
            && document.attachEvent
            && (!(opera && opera.toString() === '[object Opera]'))
        ) {
            var currentScript = getCurrentScript();
            id = currentScript && currentScript.getAttribute('data-require-id');
        }

        if ( id ) {
            modPreDefine( id, dependencies, factory );

            // 在不远的未来尝试完成define
            // define可能是在页面中某个地方调用，不一定是在独立的文件被require装载
            if ( tryDefineTimeout ) {
                clearTimeout( tryDefineTimeout );
            }
            tryDefineTimeout = setTimeout( modAnalyse, 1 );
        }
        else {
            // 纪录到共享变量中，在load或readystatechange中处理
            // 标准浏览器下，使用匿名define时，将进入这个分支
            wait4PreDefines.push( {
                deps    : dependencies,
                factory : factory
            } );
        }
    }
1116332
function generateDependenciesFiles ({ suffix, factories, entryFolder }) {
  const braceOpen = '{' // a hack to be able to create a single brace open character in handlebars

  // a map containing:
  // {
  //   'sqrt': true,
  //   'subset': true,
  //   ...
  // }
  const exists = {}
  Object.keys(factories).forEach(factoryName => {
    const factory = factories[factoryName]
    exists[factory.fn] = true
  })

  mkdirSyncIfNotExists(path.join(entryFolder, 'dependencies' + suffix))

  const data = {
    suffix,
    factories: Object.keys(factories).map((factoryName) => {
      const factory = factories[factoryName]

      return {
        suffix,
        factoryName,
        braceOpen,
        name: getDependenciesName(factoryName, factories), // FIXME: rename name with dependenciesName, and functionName with name
        fileName: './dependencies' + suffix + '/' + getDependenciesFileName(factoryName) + '.generated',
        eslintComment: factoryName === 'createSQRT1_2'
          ? ' // eslint-disable-line camelcase'
          : undefined,

        dependencies: factory.dependencies
          .map(stripOptionalNotation)
          .filter(dependency => !IGNORED_DEPENDENCIES[dependency])
          .filter(dependency => {
            if (!exists[dependency]) {
              if (factory.dependencies.indexOf(dependency) !== -1) {
                throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`)
              }

              return false
            }

            return true
          })
          .map(dependency => {
            const factoryName = findFactoryName(factories, dependency)
            const name = getDependenciesName(factoryName, factories)
            const fileName = './' + getDependenciesFileName(factoryName) + '.generated'

            return {
              suffix,
              name,
              fileName
            }
          })
      }
    })
  }

  // generate a file for every dependency
  data.factories.forEach(factoryData => {
    const generatedFactory = dependenciesFileTemplate(factoryData)

    const p = path.join(entryFolder, factoryData.fileName + '.js')
    fs.writeFileSync(p, generatedFactory)
  })

  // generate a file with links to all dependencies
  const generated = dependenciesIndexTemplate(data)
  fs.writeFileSync(path.join(entryFolder, 'dependencies' + suffix + '.generated.js'), generated)
}
134825
function collectDependenciesIds(ast) {
	var ids = [];

	visitRequireArgument(ast, function(argument) {
		ids.push(argument.value);
	});

	return ids;
}
860723
function init(app) {
    var keys = Object.keys(DependenciesMap);
    var allDeps = _.uniq(_.flatten(_.values(DependenciesMap)));

    allDeps.forEach(function (d) {
        if (!_.contains(keys, d)) {
            throw new Error("Unresolved dependency: " + d)
        }
    });


    keys.forEach(function (k) {
        var dep = DependenciesMap[k];
        if (_.contains(dep, k)) {
            throw new Error('Circular dependency: key: ' + k);
        }

        if (dep.length == 0) {
            HandlerArray.push(getHandler(app, k, PluginsData[k]));
        }
    });

    async.series(HandlerArray, function (err, end) {
        if (err)
            throw err;

        saveSchemas(app);
    });
}
408618
function (id) {
            this.cleanCache();

            // store id to identify changes during callback execution
            if (this._changed) {
                this._changed[id] = true;
            }

            if (this.__delegateMapping) {
                this.__delegateMapping[id].$dispose();
                delete this.__delegateMapping[id];
                this.__idMgr.releaseId(id);
            }
        }
263964
function (name, factory, config) {
            name = addIndexAndRemoveJsExtFromName(name);

            var mods = Env.mods,
                module = mods[name];

            if (module && module.factory !== undefined) {
                S.log(name + ' is defined more than once', 'warn');
                return;
            }

            // 没有 use，静态载入的 add 可能执行
            Utils.createModuleInfo(name);

            module = mods[name];

            // 注意：通过 S.add(name[, factory[, config]]) 注册的代码，无论是页面中的代码，
            // 还是 js 文件里的代码，add 执行时，都意味着该模块已经 LOADED
            mix(module, {
                name: name,
                status: LOADED,
                factory: factory
            });

            mix(module, config);
        }
292662
function loadModule(moduleId) {
        // 加载过的模块，就不要再继续了
        if (loadingModules[moduleId] || modModules[moduleId]) {
            return;
        }
        loadingModules[moduleId] = 1;

        // 初始化相关 shim 的配置
        var shimConf = requireConf.shim[moduleId];
        if (shimConf instanceof Array) {
            requireConf.shim[moduleId] = shimConf = {
                deps: shimConf
            };
        }

        // shim依赖的模块需要自动标识为shim
        // 无论是纯正的shim模块还是hybird模块
        var shimDeps = shimConf && (shimConf.deps || []);
        if (shimDeps) {
            each(shimDeps, function (dep) {
                if (!requireConf.shim[dep]) {
                    requireConf.shim[dep] = {};
                }
            });
            actualGlobalRequire(shimDeps, load);
        }
        else {
            load();
        }

        /**
         * 发送请求去加载模块
         *
         * @inner
         */
        function load() {
            /* eslint-disable no-use-before-define */
            var bundleModuleId = bundlesIndex[moduleId];
            createScript(bundleModuleId || moduleId, loaded);
            /* eslint-enable no-use-before-define */
        }

        /**
         * script标签加载完成的事件处理函数
         *
         * @inner
         */
        function loaded() {
            if (shimConf) {
                var exports;
                if (typeof shimConf.init === 'function') {
                    exports = shimConf.init.apply(
                        global,
                        modGetModulesExports(shimDeps, BUILDIN_MODULE)
                    );
                }

                if (exports == null && shimConf.exports) {
                    exports = global;
                    each(
                        shimConf.exports.split('.'),
                        function (prop) {
                            exports = exports[prop];
                            return !!exports;
                        }
                    );
                }

                globalDefine(moduleId, shimDeps, function () { 
                    return exports || {};
                });
            }
            else {
                modCompletePreDefine(moduleId);
            }

            modAutoDefine();
        }
    }
1107835
function require(parent, id, fn) {
		if (fn) { return ensure(parent, id, fn); }
		var module = getModule(parent, id);
		if (!module.loaded) { throw new Error(id + ' not found'); }
		if (!('exports' in module)) {
			module.parent = parent; // first module to actually require this one is parent

			// if define was passed a non-function, just assign it to exports
			if ('function' !== typeof factories[id = module.id]) { module.exports = factories[id]; }
			else {
				module.exports = {};
				fn = map(module.children.slice(0, factories[id].length), // don't require prematurely on wrapped commonjs
						function(child) { return require(module, child.id); });
				if ((fn = factories[id].apply(global, fn))) { module.exports = fn; } // if something was returned, export it instead
			}
		}
		return module.exports;
	}
429764
function (dependencies, extension) {
            if (dependencies) {
                for (var i = dependencies.length - 1; i >= 0; i--) {
                    this.addDependency(dependencies[i], extension);
                }
            }
        }
428859
async function recDependencies(dependencies, root) {
    let url;

    // TODO think about doing this in parallel using promises

    for (const dependency of Reflect.ownKeys(dependencies)) {
        const range = dependencies[dependency];
        url = `${constants.FIREBASE_DATABASE_URL}/package/${dependency}/versions.json`;
        const versions = await request({
            url,
            method: "GET",
            json: true,
            headers: {
                "content-type": "application/json",
            },
        });

        // Translate db versions to semver versions
        const semverVersions = {};
        for (const version of Reflect.ownKeys(versions)) {
            semverVersions[version.replace(/_/g, '.')] = true;
        }
        const semverMatch = semver.maxSatisfying(Reflect.ownKeys(semverVersions), range);
        const match = semverMatch.replace(/\./g, '_');
        const versionKey = `${dependency}_${match}`;

        // Set result
        if (dependencies[dependency]) {
            Reflect.deleteProperty(dependencies, dependency);
        }
        dependencies[versionKey] = true;

        // check if in dependency list yet
        if (!depencyList[versionKey]) {
            // Resolve new dependencies
            url = `${constants.FIREBASE_DATABASE_URL}/package/${dependency}/version/${match}/dependencies.json`;
            const newDependencies = await request({
                url,
                method: "GET",
                json: true,
                headers: {
                    "content-type": "application/json",
                },
            });

            // Add to dependencyList
            depencyList[versionKey] = {};

            // Resolve new dependencies
            if (newDependencies) {
                depencyList[versionKey].dependencies = await recDependencies(newDependencies);
            }
        }

        if (root) {
            depencyList[versionKey].isRootDependency = true;
        }
        depencyList[versionKey].packageName = dependency;
        depencyList[versionKey].version = match;
    }
    return dependencies;
}
690306
function fetchUnmetDependencies() {
        var runAgain = false;
        for (var id in dependencyMap) {
            _.forEach(dependencyMap[id], function (depId) {
                if (!dependencyMap[depId] && !injectedMap[depId]) {
                    try {
                        loadExternalModule(id, depId);
                    } catch (err) {
                        throw new Error('Error loading dependency ' + depId + ' for ' + id + ': ' + err.message);
                    }

                    runAgain = true;
                }
            });
        }

        if (runAgain) { //continue until all we don't have any more unmet dependencies
            fetchUnmetDependencies();
        }
    }
1242057
function createLocalRequire(baseId) {
        var requiredCache = {};

        function req(requireId, callback) {
            if (typeof requireId === 'string') {
                if (!requiredCache[requireId]) {
                    var topLevelId = normalize(requireId, baseId);

                    // 根据 https://github.com/amdjs/amdjs-api/wiki/require
                    // It MUST throw an error if the module has not
                    // already been loaded and evaluated.
                    modTryInvokeFactory(topLevelId);
                    if (!modIs(topLevelId, MODULE_DEFINED)) {
                        throw new Error('[MODULE_MISS]"' + topLevelId + '" is not exists!');
                    }

                    requiredCache[requireId] = modModules[topLevelId].exports;
                }

                return requiredCache[requireId];
            }
            else if (requireId instanceof Array) {
                // 分析是否有resource，取出pluginModule先
                var pureModules = [];
                var normalizedIds = [];

                each(
                    requireId,
                    function (id, i) {
                        var idInfo = parseId(id);
                        var absId = normalize(idInfo.mod, baseId);
                        var resId = idInfo.res;
                        var normalizedId = absId;

                        if (resId) {
                            var trueResId = absId + '!' + resId;
                            if (resId.indexOf('.') !== 0 && bundlesIndex[trueResId]) {
                                absId = normalizedId = trueResId;
                            }
                            else {
                                normalizedId = null;
                            }
                        }

                        normalizedIds[i] = normalizedId;
                        modFlagAutoDefine(absId);
                        pureModules.push(absId);
                    }
                );

                // 加载模块
                nativeAsyncRequire(
                    pureModules,
                    function () {
                        /* jshint ignore:start */
                        each(normalizedIds, function (id, i) {
                            if (id == null) {
                                id = normalizedIds[i] = normalize(requireId[i], baseId);
                                modFlagAutoDefine(id);
                            }
                        });
                        /* jshint ignore:end */

                        // modAutoDefine中，factory invoke可能发生错误
                        // 从而导致nativeAsyncRequire没有被调用，callback没挂上
                        // 所以nativeAsyncRequire要先运行
                        nativeAsyncRequire(normalizedIds, callback, baseId);
                        modAutoDefine();
                    },
                    baseId
                );
                modAutoDefine();
            }
        }

        /**
         * 将[module ID] + '.extension'格式的字符串转换成url
         *
         * @inner
         * @param {string} id 符合描述格式的源字符串
         * @return {string} url
         */
        req.toUrl = function (id) {
            return toUrl(id, baseId || '');
        };

        return req;
    }
365911
function(factory, options) {
			this.base(options);
			this.factory = factory;
			this.callback(this.callbacks.init);	
			this.callback(this.callbacks.create);
		}
628457
function(data, done) {
            try {
                // Retrieve all the dependencies
                _.forEach(data._dependencies || {}, function(value, key) {
                    if(this.sandbox[key] !== undefined) {
                        // Do nothing if the dependency is already defined
                        return;
                    }

                    this.sandbox[key] = module.parent.require(value);
                }.bind(this));

                // Remove the dependencies property
                delete data._dependencies;
            }
            catch(e) {
                // Stop execution and return the MODULE_NOT_FOUND error
                return done(e);
            }

            // Iterate over all the data objects
            async.eachSeries(Object.keys(data), function(key, next) {
                _this.result[key] = {};

                var value = data[key];

                try {
                    if(!value._model) {
                        // Throw an error if the model could not be found
                        throw new Error('Please provide a _model property that describes which database model should be used.');
                    }

                    var modelName = value._model;

                    // Remove model and unique properties
                    delete value._model;

                    // retrieve the model depending on the name provided
                    var Model = mongoose.model(modelName);

                    async.series([
                        function(callback) {
                            if(_this.options.dropCollections === true) {
                                // Drop the collection
                                mongoose.connection.db.dropCollection(Model.collection.name, function(err) {
                                    callback();
                                });
                            }
                            else {
                                callback();
                            }
                        },
                        function(callback) {
                            async.eachSeries(Object.keys(value), function(k, innerNext) {
                                var modelData = value[k],
                                    data = _this._unwind(modelData);

                                // Create the model
                                Model.create(data, function(err, result) {
                                    if(err) {
                                        // Do not stop execution if an error occurs
                                        return innerNext(err);
                                    }

                                    _this.result[key][k] = result;

                                    innerNext();
                                });
                            }, callback);
                        }
                    ], next);
                }
                catch(err) {
                    // If the model does not exist, stop the execution
                    return next(err);
                }
            }, function(err) {
                if(err) {
                    // Make sure to not return the result
                    return done(err);
                }

                done(undefined, _this.result);
            });
        }
243429
function define(id, deps, exp) {
		if (!exp) { exp = deps; deps = [ 'require', 'exports', 'module' ]; }
		var module = getModule(undefined, id);
		module.children = map(deps, function(dep) { return getModule(module, dep); });
		module.loaded = true;
		factories[id] = exp;
		fireWaits(module);
	}
256399
private function prepareBindingClosure($id, $blueprint, $dependencies = null): Closure
    {
        if ($this->bindings[$id]['singleton']) {
            return $this->prepareSingletonBindingClosure($id, $blueprint, $dependencies);
        }

        return $this->preparePrototypeBindingClosure($id, $blueprint, $dependencies);
    }
996023
function(id) {
    if (id && (id = id.trim())) {

      // js embend 同名.html 而 同名.html 又开启了依赖同名.js，然后就出现了，自己依赖自己了。
      // 所以这里做了 id !== this.id 的判断
      if (id !== this.id && !~this.requires.indexOf(id)) {
        this.requires.push(id);
      }

      // 如果在异步依赖中，则需要把它删了。
      var idx;
      if (~(idx = this.asyncs.indexOf(id))) {
        this.asyncs.splice(idx, 1);
      }

      return id;
    }
    return false;
  }