ams
Version:
ams - asset management system - plugin enabled build tool with jquery like API
1,201 lines (1,074 loc) • 73.8 kB
JavaScript
/** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 0.22.0 Copyright (c) 2010, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details
*/
/*jslint white: false, plusplus: false */
/*global window: false, navigator: false, document: false, importScripts: false,
jQuery: false, clearInterval: false, setInterval: false, self: false,
setTimeout: false */
var require, define;
(function () {
//Change this version number for each release.
var version = "0.22.0",
commentRegExp = /(\/\*([\s\S]*?)\*\/|\/\/(.*)$)/mg,
cjsRequireRegExp = /require\(["']([^'"\s]+)["']\)/g,
currDirRegExp = /^\.\//,
ostring = Object.prototype.toString,
ap = Array.prototype,
aps = ap.slice,
apsp = ap.splice,
isBrowser = !!(typeof window !== "undefined" && navigator && document),
isWebWorker = !isBrowser && typeof importScripts !== "undefined",
//PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is "loading", "loaded", execution,
// then "complete". The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/,
defContextName = "_",
reqWaitIdPrefix = "_r@@",
empty = {},
contexts = {},
globalDefQueue = [],
interactiveScript = null,
isDone = false,
useInteractive = false,
//Default plugins that have remapped names, if no mapping
//already exists.
requirePlugins = {
"text": "require/text",
"i18n": "require/i18n",
"order": "require/order"
},
req, cfg = {}, currentlyAddingScript, s, head, baseElement, scripts, script,
rePkg, src, m, dataMain, i, scrollIntervalId, setReadyState, ctx;
function isFunction(it) {
return ostring.call(it) === "[object Function]";
}
function isArray(it) {
return ostring.call(it) === "[object Array]";
}
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
* This is not robust in IE for transferring methods that match
* Object.prototype names, but the uses of mixin here seem unlikely to
* trigger a problem related to that.
*/
function mixin(target, source, force) {
for (var prop in source) {
if (!(prop in empty) && (!(prop in target) || force)) {
target[prop] = source[prop];
}
}
return req;
}
/**
* Used to set up package paths from a packagePaths or packages config object.
* @param {Object} packages the object to store the new package config
* @param {Array} currentPackages an array of packages to configure
* @param {String} [dir] a prefix dir to use.
*/
function configurePackageDir(packages, currentPackages, dir) {
var i, location, pkgObj;
for (i = 0; (pkgObj = currentPackages[i]); i++) {
pkgObj = typeof pkgObj === "string" ? { name: pkgObj } : pkgObj;
location = pkgObj.location;
//Add dir to the path, but avoid paths that start with a slash
//or have a colon (indicates a protocol)
if (dir && (!location || (location.indexOf("/") !== 0 && location.indexOf(":") === -1))) {
pkgObj.location = dir + "/" + (pkgObj.location || pkgObj.name);
}
//Normalize package paths.
pkgObj.location = pkgObj.location || pkgObj.name;
pkgObj.lib = pkgObj.lib || "lib";
//Remove leading dot in main, so main paths are normalized.
pkgObj.main = (pkgObj.main || "lib/main").replace(currDirRegExp, '');
packages[pkgObj.name] = pkgObj;
}
}
//Check for an existing version of require. If so, then exit out. Only allow
//one version of require to be active in a page. However, allow for a require
//config object, just exit quickly if require is an actual function.
if (typeof require !== "undefined") {
if (isFunction(require)) {
return;
} else {
//assume it is a config object.
cfg = require;
}
}
/**
* Creates a new context for use in require and define calls.
* Handle most of the heavy lifting. Do not want to use an object
* with prototype here to avoid using "this" in require, in case it
* needs to be used in more super secure envs that do not want this.
* Also there should not be that many contexts in the page. Usually just
* one for the default context, but could be extra for multiversion cases
* or if a package needs a special context for a dependency that conflicts
* with the standard context.
*/
function newContext(contextName) {
var context, resume,
config = {
waitSeconds: 7,
baseUrl: s.baseUrl || "./",
paths: {},
packages: {}
},
defQueue = [],
specified = {
"require": true,
"exports": true,
"module": true
},
urlMap = {},
defined = {},
loaded = {},
waiting = {},
waitAry = [],
waitIdCounter = 0,
managerCallbacks = {},
plugins = {},
pluginsQueue = {},
normalizedWaiting = {};
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; (part = ary[i]); i++) {
if (part === ".") {
ary.splice(i, 1);
i -= 1;
} else if (part === "..") {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @returns {String} normalized name
*/
function normalize(name, baseName) {
var pkgName, pkgConfig;
//Adjust any relative paths.
if (name.charAt(0) === ".") {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
if (config.packages[baseName]) {
//If the baseName is a package name, then just treat it as one
//name to concat the name with.
baseName = [baseName];
} else {
//Convert baseName to array, and lop off the last part,
//so that . matches that "directory" and not name of the baseName's
//module. For instance, baseName of "one/two/three", maps to
//"one/two/three.js", but we want the directory, "one/two" for
//this normalization.
baseName = baseName.split("/");
baseName = baseName.slice(0, baseName.length - 1);
}
name = baseName.concat(name.split("/"));
trimDots(name);
//Some use of packages may use a . path to reference the
//"main" module name, so normalize for that.
pkgConfig = config.packages[(pkgName = name[0])];
name = name.join("/");
if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
name = pkgName;
}
}
}
return name;
}
/**
* Creates a module mapping that includes plugin prefix, module
* name, and path. If parentModuleMap is provided it will
* also normalize the name via require.normalize()
*
* @param {String} name the module name
* @param {String} [parentModuleMap] parent module map
* for the module name, used to resolve relative names.
*
* @returns {Object}
*/
function makeModuleMap(name, parentModuleMap) {
var index = name ? name.indexOf("!") : -1,
prefix = null,
parentName = parentModuleMap ? parentModuleMap.name : null,
originalName = name,
normalizedName, url, pluginModule;
if (index !== -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
if (prefix) {
prefix = normalize(prefix, parentName);
//Allow simpler mappings for some plugins
prefix = requirePlugins[prefix] || prefix;
}
//Account for relative paths if there is a base name.
if (name) {
if (prefix) {
pluginModule = defined[prefix];
if (pluginModule) {
//Plugin is loaded, use its normalize method, otherwise,
//normalize name as usual.
if (pluginModule.normalize) {
normalizedName = pluginModule.normalize(name, function (name) {
return normalize(name, parentName);
});
} else {
normalizedName = normalize(name, parentName);
}
} else {
//Plugin is not loaded yet, so do not normalize
//the name, wait for plugin to load to see if
//it has a normalize method. To avoid possible
//ambiguity with relative names loaded from another
//plugin, use the parent's name as part of this name.
normalizedName = '__$p' + parentName + '@' + name;
}
} else {
normalizedName = normalize(name, parentName);
}
url = urlMap[normalizedName];
if (!url) {
//Calculate url for the module, if it has a name.
if (req.toModuleUrl) {
//Special logic required for a particular engine,
//like Node.
url = req.toModuleUrl(context, name, parentModuleMap);
} else {
url = context.nameToUrl(name, null, parentModuleMap);
}
//Store the URL mapping for later.
urlMap[normalizedName] = url;
}
}
return {
prefix: prefix,
name: normalizedName,
parentMap: parentModuleMap,
url: url,
originalName: originalName,
fullName: prefix ? prefix + "!" + normalizedName : normalizedName
};
}
/**
* Determine if priority loading is done. If so clear the priorityWait
*/
function isPriorityDone() {
var priorityDone = true,
priorityWait = config.priorityWait,
priorityName, i;
if (priorityWait) {
for (i = 0; (priorityName = priorityWait[i]); i++) {
if (!loaded[priorityName]) {
priorityDone = false;
break;
}
}
if (priorityDone) {
delete config.priorityWait;
}
}
return priorityDone;
}
/**
* Helper function that creates a setExports function for a "module"
* CommonJS dependency. Do this here to avoid creating a closure that
* is part of a loop.
*/
function makeSetExports(moduleObj) {
return function (exports) {
moduleObj.exports = exports;
};
}
function makeContextModuleFunc(func, relModuleMap, enableBuildCallback) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
var args = [].concat(aps.call(arguments, 0)), lastArg;
if (enableBuildCallback &&
isFunction((lastArg = args[args.length - 1]))) {
lastArg.__requireJsBuild = true;
}
args.push(relModuleMap);
return func.apply(null, args);
};
}
/**
* Helper function that creates a require function object to give to
* modules that ask for it as a dependency. It needs to be specific
* per module because of the implication of path mappings that may
* need to be relative to the module name.
*/
function makeRequire(relModuleMap, enableBuildCallback) {
var modRequire = makeContextModuleFunc(context.require, relModuleMap, enableBuildCallback);
mixin(modRequire, {
nameToUrl: makeContextModuleFunc(context.nameToUrl, relModuleMap),
toUrl: makeContextModuleFunc(context.toUrl, relModuleMap),
isDefined: makeContextModuleFunc(context.isDefined, relModuleMap),
ready: req.ready,
isBrowser: req.isBrowser
});
//Something used by node.
if (req.paths) {
modRequire.paths = req.paths;
}
return modRequire;
}
/**
* Used to update the normalized name for plugin-based dependencies
* after a plugin loads, since it can have its own normalization structure.
* @param {String} pluginName the normalized plugin module name.
*/
function updateNormalizedNames(pluginName) {
var oldFullName, oldModuleMap, moduleMap, fullName, callbacks,
i, j, k, depArray,
maps = normalizedWaiting[pluginName];
if (maps) {
for (i = 0; (oldModuleMap = maps[i]); i++) {
oldFullName = oldModuleMap.fullName;
moduleMap = makeModuleMap(oldModuleMap.originalName, oldModuleMap.parentMap);
fullName = moduleMap.fullName;
callbacks = managerCallbacks[oldFullName];
if (fullName !== oldFullName) {
//Update managerCallbacks to use the correct normalized name.
managerCallbacks[fullName] = callbacks;
delete managerCallbacks[oldFullName];
//In each manager callback, update the normalized name in the depArray.
for (j = 0; j < callbacks.length; j++) {
depArray = callbacks[j].depArray;
for (k = 0; k < depArray.length; k++) {
if (depArray[k] === oldFullName) {
depArray[k] = fullName;
}
}
}
}
}
}
delete normalizedWaiting[pluginName];
}
/*
* Queues a dependency for checking after the loader is out of a
* "paused" state, for example while a script file is being loaded
* in the browser, where it may have many modules defined in it.
*
* depName will be fully qualified, no relative . or .. path.
*/
function queueDependency(dep) {
//Make sure to load any plugin and associate the dependency
//with that plugin.
var prefix = dep.prefix,
fullName = dep.fullName;
//Do not bother if the depName is already in transit
if (specified[fullName] || fullName in defined) {
return;
}
if (prefix && !plugins[prefix]) {
//Queue up loading of the dependency, track it
//via context.plugins. Mark it as a plugin so
//that the build system will know to treat it
//special.
plugins[prefix] = undefined;
//Remember this dep that needs to have normaliztion done
//after the plugin loads.
(normalizedWaiting[prefix] || (normalizedWaiting[prefix] = []))
.push(dep);
//Register an action to do once the plugin loads, to update
//all managerCallbacks to use a properly normalized module
//name.
(managerCallbacks[prefix] ||
(managerCallbacks[prefix] = [])).push({
onDep: function (name, value) {
if (name === prefix) {
updateNormalizedNames(prefix);
}
}
});
queueDependency(makeModuleMap(prefix));
}
context.paused.push(dep);
}
function execManager(manager) {
var i, ret, waitingCallbacks,
cb = manager.callback,
fullName = manager.fullName,
args = [],
ary = manager.depArray;
//Call the callback to define the module, if necessary.
if (cb && isFunction(cb)) {
//Pull out the defined dependencies and pass the ordered
//values to the callback.
if (ary) {
for (i = 0; i < ary.length; i++) {
args.push(manager.deps[ary[i]]);
}
}
ret = req.execCb(fullName, manager.callback, args);
if (fullName) {
//If using exports and the function did not return a value,
//and the "module" object for this definition function did not
//define an exported value, then use the exports object.
if (manager.usingExports && ret === undefined && (!manager.cjsModule || !("exports" in manager.cjsModule))) {
ret = defined[fullName];
} else {
if (manager.cjsModule && "exports" in manager.cjsModule) {
ret = defined[fullName] = manager.cjsModule.exports;
} else {
if (fullName in defined && !manager.usingExports) {
return req.onError(new Error(fullName + " has already been defined"));
}
defined[fullName] = ret;
}
}
}
} else if (fullName) {
//May just be an object definition for the module. Only
//worry about defining if have a module name.
ret = defined[fullName] = cb;
}
if (fullName) {
//If anything was waiting for this module to be defined,
//notify them now.
waitingCallbacks = managerCallbacks[fullName];
if (waitingCallbacks) {
for (i = 0; i < waitingCallbacks.length; i++) {
waitingCallbacks[i].onDep(fullName, ret);
}
delete managerCallbacks[fullName];
}
}
//Clean up waiting.
if (waiting[manager.waitId]) {
delete waiting[manager.waitId];
manager.isDone = true;
context.waitCount -= 1;
if (context.waitCount === 0) {
//Clear the wait array used for cycles.
waitAry = [];
}
}
return undefined;
}
function main(inName, depArray, callback, relModuleMap) {
var moduleMap = makeModuleMap(inName, relModuleMap),
name = moduleMap.name,
fullName = moduleMap.fullName,
manager = {
//Use a wait ID because some entries are anon
//async require calls.
waitId: name || reqWaitIdPrefix + (waitIdCounter++),
depCount: 0,
depMax: 0,
prefix: moduleMap.prefix,
name: name,
fullName: fullName,
deps: {},
depArray: depArray,
callback: callback,
onDep: function (depName, value) {
if (!(depName in manager.deps)) {
manager.deps[depName] = value;
manager.depCount += 1;
if (manager.depCount === manager.depMax) {
//All done, execute!
execManager(manager);
}
}
}
},
i, depArg, depName, cjsMod;
if (fullName) {
//If module already defined for context, or already loaded,
//then leave.
if (fullName in defined || loaded[fullName] === true) {
return;
}
//Set specified/loaded here for modules that are also loaded
//as part of a layer, where onScriptLoad is not fired
//for those cases. Do this after the inline define and
//dependency tracing is done.
//Also check if auto-registry of jQuery needs to be skipped.
specified[fullName] = true;
loaded[fullName] = true;
context.jQueryDef = (fullName === "jquery");
}
//Add the dependencies to the deps field, and register for callbacks
//on the dependencies.
for (i = 0; i < depArray.length; i++) {
depArg = depArray[i];
//There could be cases like in IE, where a trailing comma will
//introduce a null dependency, so only treat a real dependency
//value as a dependency.
if (depArg) {
//Split the dependency name into plugin and name parts
depArg = makeModuleMap(depArg, (name ? moduleMap : relModuleMap));
depName = depArg.fullName;
//Fix the name in depArray to be just the name, since
//that is how it will be called back later.
depArray[i] = depName;
//Fast path CommonJS standard dependencies.
if (depName === "require") {
manager.deps[depName] = makeRequire(moduleMap);
} else if (depName === "exports") {
//CommonJS module spec 1.1
manager.deps[depName] = defined[fullName] = {};
manager.usingExports = true;
} else if (depName === "module") {
//CommonJS module spec 1.1
manager.cjsModule = cjsMod = manager.deps[depName] = {
id: name,
uri: name ? context.nameToUrl(name, null, relModuleMap) : undefined
};
cjsMod.setExports = makeSetExports(cjsMod);
} else if (depName in defined && !(depName in waiting)) {
//Module already defined, no need to wait for it.
manager.deps[depName] = defined[depName];
} else {
//A dynamic dependency.
manager.depMax += 1;
queueDependency(depArg);
//Register to get notification when dependency loads.
(managerCallbacks[depName] ||
(managerCallbacks[depName] = [])).push(manager);
}
}
}
//Do not bother tracking the manager if it is all done.
if (manager.depCount === manager.depMax) {
//All done, execute!
execManager(manager);
} else {
waiting[manager.waitId] = manager;
waitAry.push(manager);
context.waitCount += 1;
}
}
/**
* Convenience method to call main for a require.def call that was put on
* hold in the defQueue.
*/
function callDefMain(args) {
main.apply(null, args);
//Mark the module loaded. Must do it here in addition
//to doing it in require.def in case a script does
//not call require.def
loaded[args[0]] = true;
}
/**
* As of jQuery 1.4.3, it supports a readyWait property that will hold off
* calling jQuery ready callbacks until all scripts are loaded. Be sure
* to track it if readyWait is available. Also, since jQuery 1.4.3 does
* not register as a module, need to do some global inference checking.
* Even if it does register as a module, not guaranteed to be the precise
* name of the global. If a jQuery is tracked for this context, then go
* ahead and register it as a module too, if not already in process.
*/
function jQueryCheck(jqCandidate) {
if (!context.jQuery) {
var $ = jqCandidate || (typeof jQuery !== "undefined" ? jQuery : null);
if ($ && "readyWait" in $) {
context.jQuery = $;
//Manually create a "jquery" module entry if not one already
//or in process.
callDefMain(["jquery", [], function () {
return jQuery;
}]);
//Increment jQuery readyWait if ncecessary.
if (context.scriptCount) {
$.readyWait += 1;
context.jQueryIncremented = true;
}
}
}
}
function forceExec(manager, traced) {
if (manager.isDone) {
return undefined;
}
var fullName = manager.fullName,
depArray = manager.depArray,
depName, i;
if (fullName) {
if (traced[fullName]) {
return defined[fullName];
}
traced[fullName] = true;
}
//forceExec all of its dependencies.
for (i = 0; i < depArray.length; i++) {
//Some array members may be null, like if a trailing comma
//IE, so do the explicit [i] access and check if it has a value.
depName = depArray[i];
if (depName) {
if (!manager.deps[depName] && waiting[depName]) {
manager.onDep(depName, forceExec(waiting[depName], traced));
}
}
}
return fullName ? defined[fullName] : undefined;
}
/**
* Checks if all modules for a context are loaded, and if so, evaluates the
* new ones in right dependency order.
*
* @private
*/
function checkLoaded() {
var waitInterval = config.waitSeconds * 1000,
//It is possible to disable the wait interval by using waitSeconds of 0.
expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
noLoads = "", hasLoadedProp = false, stillLoading = false, prop,
err, manager;
//Determine if priority loading is done. If so clear the priority. If
//not, then do not check
if (config.priorityWait) {
if (isPriorityDone()) {
//Call resume, since it could have
//some waiting dependencies to trace.
resume();
} else {
return undefined;
}
}
//See if anything is still in flight.
for (prop in loaded) {
if (!(prop in empty)) {
hasLoadedProp = true;
if (!loaded[prop]) {
if (expired) {
noLoads += prop + " ";
} else {
stillLoading = true;
break;
}
}
}
}
//Check for exit conditions.
if (!hasLoadedProp && !context.waitCount) {
//If the loaded object had no items, then the rest of
//the work below does not need to be done.
return undefined;
}
if (expired && noLoads) {
//If wait time expired, throw error of unloaded modules.
err = new Error("require.js load timeout for modules: " + noLoads);
err.requireType = "timeout";
err.requireModules = noLoads;
return req.onError(err);
}
if (stillLoading || context.scriptCount) {
//Something is still waiting to load. Wait for it.
if (isBrowser || isWebWorker) {
setTimeout(checkLoaded, 50);
}
return undefined;
}
//If still have items in the waiting cue, but all modules have
//been loaded, then it means there are some circular dependencies
//that need to be broken.
//However, as a waiting thing is fired, then it can add items to
//the waiting cue, and those items should not be fired yet, so
//make sure to redo the checkLoaded call after breaking a single
//cycle, if nothing else loaded then this logic will pick it up
//again.
if (context.waitCount) {
//Cycle through the waitAry, and call items in sequence.
for (i = 0; (manager = waitAry[i]); i++) {
forceExec(manager, {});
}
checkLoaded();
return undefined;
}
//Check for DOM ready, and nothing is waiting across contexts.
req.checkReadyState();
return undefined;
}
function callPlugin(pluginName, dep) {
var name = dep.name,
fullName = dep.fullName;
//Do not bother if plugin is already defined.
if (fullName in defined) {
return;
}
if (!plugins[pluginName]) {
plugins[pluginName] = defined[pluginName];
}
//Only set loaded to false for tracking if it has not already been set.
if (!loaded[fullName]) {
loaded[fullName] = false;
}
//Use parentName here since the plugin's name is not reliable,
//could be some weird string with no path that actually wants to
//reference the parentName's path.
plugins[pluginName].load(name, makeRequire(dep.parentMap, true), function (ret) {
//Allow the build process to register plugin-loaded dependencies.
if (require.onPluginLoad) {
require.onPluginLoad(context, pluginName, name, ret);
}
execManager({
prefix: dep.prefix,
name: dep.name,
fullName: dep.fullName,
callback: ret
});
loaded[fullName] = true;
}, config);
}
function loadPaused(dep) {
//Renormalize dependency if its name was waiting on a plugin
//to load, which as since loaded.
if (dep.prefix && dep.name.indexOf('__$p') === 0 && defined[dep.prefix]) {
dep = makeModuleMap(dep.originalName, dep.parentMap);
}
var pluginName = dep.prefix,
fullName = dep.fullName;
//Do not bother if the dependency has already been specified.
if (specified[fullName] || fullName in defined) {
return;
} else {
specified[fullName] = true;
}
if (pluginName) {
//If plugin not loaded, wait for it.
//set up callback list. if no list, then register
//managerCallback for that plugin.
if (defined[pluginName]) {
callPlugin(pluginName, dep);
} else {
if (!pluginsQueue[pluginName]) {
pluginsQueue[pluginName] = [];
(managerCallbacks[pluginName] ||
(managerCallbacks[pluginName] = [])).push({
onDep: function (name, value) {
if (name === pluginName) {
var i, oldModuleMap, ary = pluginsQueue[pluginName];
//Now update all queued plugin actions.
for (i = 0; i < ary.length; i++) {
oldModuleMap = ary[i];
//Update the moduleMap since the
//module name may be normalized
//differently now.
callPlugin(pluginName,
makeModuleMap(oldModuleMap.originalName, oldModuleMap.parentMap));
}
delete pluginsQueue[pluginName];
}
}
});
}
pluginsQueue[pluginName].push(dep);
}
} else {
req.load(context, fullName, dep.url);
}
}
/**
* Resumes tracing of dependencies and then checks if everything is loaded.
*/
resume = function () {
var args, i, p;
if (context.scriptCount <= 0) {
//Synchronous envs will push the number below zero with the
//decrement above, be sure to set it back to zero for good measure.
//require() calls that also do not end up loading scripts could
//push the number negative too.
context.scriptCount = 0;
}
//Make sure any remaining defQueue items get properly processed.
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
return req.onError(new Error('Mismatched anonymous require.def modules'));
} else {
callDefMain(args);
}
}
//Skip the resume if current context is in priority wait.
if (config.priorityWait && !isPriorityDone()) {
return undefined;
}
while (context.paused.length) {
p = context.paused;
//Reset paused list
context.paused = [];
for (i = 0; (args = p[i]); i++) {
loadPaused(args);
}
//Move the start time for timeout forward.
context.startTime = (new Date()).getTime();
}
checkLoaded();
return undefined;
};
//Define the context object. Many of these fields are on here
//just to make debugging easier.
context = {
contextName: contextName,
config: config,
defQueue: defQueue,
waiting: waiting,
waitCount: 0,
specified: specified,
loaded: loaded,
urlMap: urlMap,
scriptCount: 0,
urlFetched: {},
defined: defined,
paused: [],
plugins: plugins,
managerCallbacks: managerCallbacks,
makeModuleMap: makeModuleMap,
normalize: normalize,
/**
* Set a configuration for the context.
* @param {Object} cfg config object to integrate.
*/
configure: function (cfg) {
var paths, packages, prop, packagePaths, requireWait;
//Make sure the baseUrl ends in a slash.
if (cfg.baseUrl) {
if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== "/") {
cfg.baseUrl += "/";
}
}
//Save off the paths and packages since they require special processing,
//they are additive.
paths = config.paths;
packages = config.packages;
//Mix in the config values, favoring the new values over
//existing ones in context.config.
mixin(config, cfg, true);
//Adjust paths if necessary.
if (cfg.paths) {
for (prop in cfg.paths) {
if (!(prop in empty)) {
paths[prop] = cfg.paths[prop];
}
}
config.paths = paths;
}
packagePaths = cfg.packagePaths;
if (packagePaths || cfg.packages) {
//Convert packagePaths into a packages config.
if (packagePaths) {
for (prop in packagePaths) {
if (!(prop in empty)) {
configurePackageDir(packages, packagePaths[prop], prop);
}
}
}
//Adjust packages if necessary.
if (cfg.packages) {
configurePackageDir(packages, cfg.packages);
}
//Done with modifications, assing packages back to context config
config.packages = packages;
}
//If priority loading is in effect, trigger the loads now
if (cfg.priority) {
//Create a separate config property that can be
//easily tested for config priority completion.
//Do this instead of wiping out the config.priority
//in case it needs to be inspected for debug purposes later.
//Hold on to requireWait value, and reset it after done
requireWait = context.requireWait;
context.requireWait = false;
context.require(cfg.priority);
context.requireWait = requireWait;
config.priorityWait = cfg.priority;
}
//If a deps array or a config callback is specified, then call
//require with those args. This is useful when require is defined as a
//config object before require.js is loaded.
if (cfg.deps || cfg.callback) {
context.require(cfg.deps || [], cfg.callback);
}
//Set up ready callback, if asked. Useful when require is defined as a
//config object before require.js is loaded.
if (cfg.ready) {
req.ready(cfg.ready);
}
},
isDefined: function (moduleName, relModuleMap) {
return makeModuleMap(moduleName, relModuleMap).fullName in defined;
},
require: function (deps, callback, relModuleMap) {
var moduleName, ret, moduleMap;
if (typeof deps === "string") {
//Synchronous access to one module. If require.get is
//available (as in the Node adapter), prefer that.
//In this case deps is the moduleName and callback is
//the relModuleMap
if (req.get) {
return req.get(context, deps, callback);
}
//Just return the module wanted. In this scenario, the
//second arg (if passed) is just the relModuleMap.
moduleName = deps;
relModuleMap = callback;
//Normalize module name, if it contains . or ..
moduleMap = makeModuleMap(moduleName, relModuleMap);
ret = defined[moduleMap.fullName];
if (ret === undefined) {
return req.onError(new Error("require: module name '" +
moduleMap.fullName +
"' has not been loaded yet for context: " +
contextName));
}
return ret;
}
main(null, deps, callback, relModuleMap);
//If the require call does not trigger anything new to load,
//then resume the dependency processing.
if (!context.requireWait) {
while (!context.scriptCount && context.paused.length) {
resume();
}
}
return undefined;
},
/**
* Internal method to transfer globalQueue items to this context's
* defQueue.
*/
takeGlobalQueue: function () {
//Push all the globalDefQueue items into the context's defQueue
if (globalDefQueue.length) {
//Array splice in the values since the context code has a
//local var ref to defQueue, so cannot just reassign the one
//on context.
apsp.apply(context.defQueue,
[context.defQueue.length - 1, 0].concat(globalDefQueue));
globalDefQueue = [];
}
},
/**
* Internal method used by environment adapters to complete a load event.
* A load event could be a script load or just a load pass from a synchronous
* load call.
* @param {String} moduleName the name of the module to potentially complete.
*/
completeLoad: function (moduleName) {
var args;
context.takeGlobalQueue();
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
args[0] = moduleName;
break;
} else if (args[0] === moduleName) {
//Found matching require.def call for this script!
break;
} else {
//Some other named require.def call, most likely the result
//of a build layer that included many require.def calls.
callDefMain(args);
args = null;
}
}
if (args) {
callDefMain(args);
} else {
//A script that does not call define(), so just simulate
//the call for it. Special exception for jQuery dynamic load.
callDefMain([moduleName, [],
moduleName === "jquery" && typeof jQuery !== "undefined" ?
function () {
return jQuery;
} : null]);
}
//Mark the script as loaded. Note that this can be different from a
//moduleName that maps to a require.def call. This line is important
//for traditional browser scripts.
loaded[moduleName] = true;
//If a global jQuery is defined, check for it. Need to do it here
//instead of main() since stock jQuery does not register as
//a module via define.
jQueryCheck();
//Doing this scriptCount decrement branching because sync envs
//need to decrement after resume, otherwise it looks like
//loading is complete after the first dependency is fetched.
//For browsers, it works fine to decrement after, but it means
//the checkLoaded setTimeout 50 ms cost is taken. To avoid
//that cost, decrement beforehand.
if (req.isAsync) {
context.scriptCount -= 1;
}
resume();
if (!req.isAsync) {
context.scriptCount -= 1;
}
},
/**
* Converts a module name + .extension into an URL path.
* *Requires* the use of a module name. It does not support using
* plain URLs like nameToUrl.
*/
toUrl: function (moduleNamePlusExt, relModuleMap) {
var index = moduleNamePlusExt.lastIndexOf("."),
ext = null;
if (index !== -1) {
ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
}
return context.nameToUrl(moduleNamePlusExt, ext, relModuleMap);
},
/**
* Converts a module name to a file path. Supports cases where
* moduleName may actually be just an URL.
*/
nameToUrl: function (moduleName, ext, relModuleMap) {
var paths, packages, pkg, pkgPath, syms, i, parentModule, url,
config = context.config;
if (moduleName.indexOf("./") === 0 || moduleName.indexOf("../") === 0) {
//A relative ID, just map it relative to relModuleMap's url
syms = relModuleMap && relModuleMap.url ? relModuleMap.url.split('/') : [];
//Pop off the file name.
if (syms.length) {
syms.pop();
}
syms = syms.concat(moduleName.split('/'));
trimDots(syms);
url = syms.join('/') +
(ext ? ext :
(req.jsExtRegExp.test(moduleName) ? "" : ".js"));
} else {
//Normalize module name if have a base relative module name to work from.
moduleName = normalize(moduleName, relModuleMap);
//If a colon is in the URL, it indicates a protocol is used and it is just
//an URL to a file, or if it starts with a slash or ends with .js, it is just a plain file.
//The slash is important for protocol-less URLs as well as full paths.
if (req.jsExtRegExp.test(moduleName)) {
//Just a plain path, not module