require.js 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084
  1. /** vim: et:ts=4:sw=4:sts=4
  2. * @license RequireJS 2.1.16 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved.
  3. * Available via the MIT or new BSD license.
  4. * see: http://github.com/jrburke/requirejs for details
  5. */
  6. //Not using strict: uneven strict support in browsers, #392, and causes
  7. //problems with requirejs.exec()/transpiler plugins that may not be strict.
  8. /*jslint regexp: true, nomen: true, sloppy: true */
  9. /*global window, navigator, document, importScripts, setTimeout, opera */
  10. var requirejs, require, define;
  11. (function (global) {
  12. var req, s, head, baseElement, dataMain, src,
  13. interactiveScript, currentlyAddingScript, mainScript, subPath,
  14. version = '2.1.16',
  15. commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
  16. cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
  17. jsSuffixRegExp = /\.js$/,
  18. currDirRegExp = /^\.\//,
  19. op = Object.prototype,
  20. ostring = op.toString,
  21. hasOwn = op.hasOwnProperty,
  22. ap = Array.prototype,
  23. apsp = ap.splice,
  24. isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
  25. isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
  26. //PS3 indicates loaded and complete, but need to wait for complete
  27. //specifically. Sequence is 'loading', 'loaded', execution,
  28. // then 'complete'. The UA check is unfortunate, but not sure how
  29. //to feature test w/o causing perf issues.
  30. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
  31. /^complete$/ : /^(complete|loaded)$/,
  32. defContextName = '_',
  33. //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
  34. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
  35. contexts = {},
  36. cfg = {},
  37. globalDefQueue = [],
  38. useInteractive = false;
  39. function isFunction(it) {
  40. return ostring.call(it) === '[object Function]';
  41. }
  42. function isArray(it) {
  43. return ostring.call(it) === '[object Array]';
  44. }
  45. /**
  46. * Helper function for iterating over an array. If the func returns
  47. * a true value, it will break out of the loop.
  48. */
  49. function each(ary, func) {
  50. if (ary) {
  51. var i;
  52. for (i = 0; i < ary.length; i += 1) {
  53. if (ary[i] && func(ary[i], i, ary)) {
  54. break;
  55. }
  56. }
  57. }
  58. }
  59. /**
  60. * Helper function for iterating over an array backwards. If the func
  61. * returns a true value, it will break out of the loop.
  62. */
  63. function eachReverse(ary, func) {
  64. if (ary) {
  65. var i;
  66. for (i = ary.length - 1; i > -1; i -= 1) {
  67. if (ary[i] && func(ary[i], i, ary)) {
  68. break;
  69. }
  70. }
  71. }
  72. }
  73. function hasProp(obj, prop) {
  74. return hasOwn.call(obj, prop);
  75. }
  76. function getOwn(obj, prop) {
  77. return hasProp(obj, prop) && obj[prop];
  78. }
  79. /**
  80. * Cycles over properties in an object and calls a function for each
  81. * property value. If the function returns a truthy value, then the
  82. * iteration is stopped.
  83. */
  84. function eachProp(obj, func) {
  85. var prop;
  86. for (prop in obj) {
  87. if (hasProp(obj, prop)) {
  88. if (func(obj[prop], prop)) {
  89. break;
  90. }
  91. }
  92. }
  93. }
  94. /**
  95. * Simple function to mix in properties from source into target,
  96. * but only if target does not already have a property of the same name.
  97. */
  98. function mixin(target, source, force, deepStringMixin) {
  99. if (source) {
  100. eachProp(source, function (value, prop) {
  101. if (force || !hasProp(target, prop)) {
  102. if (deepStringMixin && typeof value === 'object' && value &&
  103. !isArray(value) && !isFunction(value) &&
  104. !(value instanceof RegExp)) {
  105. if (!target[prop]) {
  106. target[prop] = {};
  107. }
  108. mixin(target[prop], value, force, deepStringMixin);
  109. } else {
  110. target[prop] = value;
  111. }
  112. }
  113. });
  114. }
  115. return target;
  116. }
  117. //Similar to Function.prototype.bind, but the 'this' object is specified
  118. //first, since it is easier to read/figure out what 'this' will be.
  119. function bind(obj, fn) {
  120. return function () {
  121. return fn.apply(obj, arguments);
  122. };
  123. }
  124. function scripts() {
  125. return document.getElementsByTagName('script');
  126. }
  127. function defaultOnError(err) {
  128. throw err;
  129. }
  130. //Allow getting a global that is expressed in
  131. //dot notation, like 'a.b.c'.
  132. function getGlobal(value) {
  133. if (!value) {
  134. return value;
  135. }
  136. var g = global;
  137. each(value.split('.'), function (part) {
  138. g = g[part];
  139. });
  140. return g;
  141. }
  142. /**
  143. * Constructs an error with a pointer to an URL with more information.
  144. * @param {String} id the error ID that maps to an ID on a web page.
  145. * @param {String} message human readable error.
  146. * @param {Error} [err] the original error, if there is one.
  147. *
  148. * @returns {Error}
  149. */
  150. function makeError(id, msg, err, requireModules) {
  151. var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
  152. e.requireType = id;
  153. e.requireModules = requireModules;
  154. if (err) {
  155. e.originalError = err;
  156. }
  157. return e;
  158. }
  159. if (typeof define !== 'undefined') {
  160. //If a define is already in play via another AMD loader,
  161. //do not overwrite.
  162. return;
  163. }
  164. if (typeof requirejs !== 'undefined') {
  165. if (isFunction(requirejs)) {
  166. //Do not overwrite an existing requirejs instance.
  167. return;
  168. }
  169. cfg = requirejs;
  170. requirejs = undefined;
  171. }
  172. //Allow for a require config object
  173. if (typeof require !== 'undefined' && !isFunction(require)) {
  174. //assume it is a config object.
  175. cfg = require;
  176. require = undefined;
  177. }
  178. function newContext(contextName) {
  179. var inCheckLoaded, Module, context, handlers,
  180. checkLoadedTimeoutId,
  181. config = {
  182. //Defaults. Do not set a default for map
  183. //config to speed up normalize(), which
  184. //will run faster if there is no default.
  185. waitSeconds: 7,
  186. baseUrl: './',
  187. paths: {},
  188. bundles: {},
  189. pkgs: {},
  190. shim: {},
  191. config: {}
  192. },
  193. registry = {},
  194. //registry of just enabled modules, to speed
  195. //cycle breaking code when lots of modules
  196. //are registered, but not activated.
  197. enabledRegistry = {},
  198. undefEvents = {},
  199. defQueue = [],
  200. defined = {},
  201. urlFetched = {},
  202. bundlesMap = {},
  203. requireCounter = 1,
  204. unnormalizedCounter = 1;
  205. /**
  206. * Trims the . and .. from an array of path segments.
  207. * It will keep a leading path segment if a .. will become
  208. * the first path segment, to help with module name lookups,
  209. * which act like paths, but can be remapped. But the end result,
  210. * all paths that use this function should look normalized.
  211. * NOTE: this method MODIFIES the input array.
  212. * @param {Array} ary the array of path segments.
  213. */
  214. function trimDots(ary) {
  215. var i, part;
  216. for (i = 0; i < ary.length; i++) {
  217. part = ary[i];
  218. if (part === '.') {
  219. ary.splice(i, 1);
  220. i -= 1;
  221. } else if (part === '..') {
  222. // If at the start, or previous value is still ..,
  223. // keep them so that when converted to a path it may
  224. // still work when converted to a path, even though
  225. // as an ID it is less than ideal. In larger point
  226. // releases, may be better to just kick out an error.
  227. if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') {
  228. continue;
  229. } else if (i > 0) {
  230. ary.splice(i - 1, 2);
  231. i -= 2;
  232. }
  233. }
  234. }
  235. }
  236. /**
  237. * Given a relative module name, like ./something, normalize it to
  238. * a real name that can be mapped to a path.
  239. * @param {String} name the relative name
  240. * @param {String} baseName a real name that the name arg is relative
  241. * to.
  242. * @param {Boolean} applyMap apply the map config to the value. Should
  243. * only be done if this normalization is for a dependency ID.
  244. * @returns {String} normalized name
  245. */
  246. function normalize(name, baseName, applyMap) {
  247. var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
  248. foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
  249. baseParts = (baseName && baseName.split('/')),
  250. map = config.map,
  251. starMap = map && map['*'];
  252. //Adjust any relative paths.
  253. if (name) {
  254. name = name.split('/');
  255. lastIndex = name.length - 1;
  256. // If wanting node ID compatibility, strip .js from end
  257. // of IDs. Have to do this here, and not in nameToUrl
  258. // because node allows either .js or non .js to map
  259. // to same file.
  260. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
  261. name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
  262. }
  263. // Starts with a '.' so need the baseName
  264. if (name[0].charAt(0) === '.' && baseParts) {
  265. //Convert baseName to array, and lop off the last part,
  266. //so that . matches that 'directory' and not name of the baseName's
  267. //module. For instance, baseName of 'one/two/three', maps to
  268. //'one/two/three.js', but we want the directory, 'one/two' for
  269. //this normalization.
  270. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
  271. name = normalizedBaseParts.concat(name);
  272. }
  273. trimDots(name);
  274. name = name.join('/');
  275. }
  276. //Apply map config if available.
  277. if (applyMap && map && (baseParts || starMap)) {
  278. nameParts = name.split('/');
  279. outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
  280. nameSegment = nameParts.slice(0, i).join('/');
  281. if (baseParts) {
  282. //Find the longest baseName segment match in the config.
  283. //So, do joins on the biggest to smallest lengths of baseParts.
  284. for (j = baseParts.length; j > 0; j -= 1) {
  285. mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
  286. //baseName segment has config, find if it has one for
  287. //this name.
  288. if (mapValue) {
  289. mapValue = getOwn(mapValue, nameSegment);
  290. if (mapValue) {
  291. //Match, update name to the new value.
  292. foundMap = mapValue;
  293. foundI = i;
  294. break outerLoop;
  295. }
  296. }
  297. }
  298. }
  299. //Check for a star map match, but just hold on to it,
  300. //if there is a shorter segment match later in a matching
  301. //config, then favor over this star map.
  302. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
  303. foundStarMap = getOwn(starMap, nameSegment);
  304. starI = i;
  305. }
  306. }
  307. if (!foundMap && foundStarMap) {
  308. foundMap = foundStarMap;
  309. foundI = starI;
  310. }
  311. if (foundMap) {
  312. nameParts.splice(0, foundI, foundMap);
  313. name = nameParts.join('/');
  314. }
  315. }
  316. // If the name points to a package's name, use
  317. // the package main instead.
  318. pkgMain = getOwn(config.pkgs, name);
  319. return pkgMain ? pkgMain : name;
  320. }
  321. function removeScript(name) {
  322. if (isBrowser) {
  323. each(scripts(), function (scriptNode) {
  324. if (scriptNode.getAttribute('data-requiremodule') === name &&
  325. scriptNode.getAttribute('data-requirecontext') === context.contextName) {
  326. scriptNode.parentNode.removeChild(scriptNode);
  327. return true;
  328. }
  329. });
  330. }
  331. }
  332. function hasPathFallback(id) {
  333. var pathConfig = getOwn(config.paths, id);
  334. if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
  335. //Pop off the first array value, since it failed, and
  336. //retry
  337. pathConfig.shift();
  338. context.require.undef(id);
  339. //Custom require that does not do map translation, since
  340. //ID is "absolute", already mapped/resolved.
  341. context.makeRequire(null, {
  342. skipMap: true
  343. })([id]);
  344. return true;
  345. }
  346. }
  347. //Turns a plugin!resource to [plugin, resource]
  348. //with the plugin being undefined if the name
  349. //did not have a plugin prefix.
  350. function splitPrefix(name) {
  351. var prefix,
  352. index = name ? name.indexOf('!') : -1;
  353. if (index > -1) {
  354. prefix = name.substring(0, index);
  355. name = name.substring(index + 1, name.length);
  356. }
  357. return [prefix, name];
  358. }
  359. /**
  360. * Creates a module mapping that includes plugin prefix, module
  361. * name, and path. If parentModuleMap is provided it will
  362. * also normalize the name via require.normalize()
  363. *
  364. * @param {String} name the module name
  365. * @param {String} [parentModuleMap] parent module map
  366. * for the module name, used to resolve relative names.
  367. * @param {Boolean} isNormalized: is the ID already normalized.
  368. * This is true if this call is done for a define() module ID.
  369. * @param {Boolean} applyMap: apply the map config to the ID.
  370. * Should only be true if this map is for a dependency.
  371. *
  372. * @returns {Object}
  373. */
  374. function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
  375. var url, pluginModule, suffix, nameParts,
  376. prefix = null,
  377. parentName = parentModuleMap ? parentModuleMap.name : null,
  378. originalName = name,
  379. isDefine = true,
  380. normalizedName = '';
  381. //If no name, then it means it is a require call, generate an
  382. //internal name.
  383. if (!name) {
  384. isDefine = false;
  385. name = '_@r' + (requireCounter += 1);
  386. }
  387. nameParts = splitPrefix(name);
  388. prefix = nameParts[0];
  389. name = nameParts[1];
  390. if (prefix) {
  391. prefix = normalize(prefix, parentName, applyMap);
  392. pluginModule = getOwn(defined, prefix);
  393. }
  394. //Account for relative paths if there is a base name.
  395. if (name) {
  396. if (prefix) {
  397. if (pluginModule && pluginModule.normalize) {
  398. //Plugin is loaded, use its normalize method.
  399. normalizedName = pluginModule.normalize(name, function (name) {
  400. return normalize(name, parentName, applyMap);
  401. });
  402. } else {
  403. // If nested plugin references, then do not try to
  404. // normalize, as it will not normalize correctly. This
  405. // places a restriction on resourceIds, and the longer
  406. // term solution is not to normalize until plugins are
  407. // loaded and all normalizations to allow for async
  408. // loading of a loader plugin. But for now, fixes the
  409. // common uses. Details in #1131
  410. normalizedName = name.indexOf('!') === -1 ?
  411. normalize(name, parentName, applyMap) :
  412. name;
  413. }
  414. } else {
  415. //A regular module.
  416. normalizedName = normalize(name, parentName, applyMap);
  417. //Normalized name may be a plugin ID due to map config
  418. //application in normalize. The map config values must
  419. //already be normalized, so do not need to redo that part.
  420. nameParts = splitPrefix(normalizedName);
  421. prefix = nameParts[0];
  422. normalizedName = nameParts[1];
  423. isNormalized = true;
  424. url = context.nameToUrl(normalizedName);
  425. }
  426. }
  427. //If the id is a plugin id that cannot be determined if it needs
  428. //normalization, stamp it with a unique ID so two matching relative
  429. //ids that may conflict can be separate.
  430. suffix = prefix && !pluginModule && !isNormalized ?
  431. '_unnormalized' + (unnormalizedCounter += 1) :
  432. '';
  433. return {
  434. prefix: prefix,
  435. name: normalizedName,
  436. parentMap: parentModuleMap,
  437. unnormalized: !!suffix,
  438. url: url,
  439. originalName: originalName,
  440. isDefine: isDefine,
  441. id: (prefix ?
  442. prefix + '!' + normalizedName :
  443. normalizedName) + suffix
  444. };
  445. }
  446. function getModule(depMap) {
  447. var id = depMap.id,
  448. mod = getOwn(registry, id);
  449. if (!mod) {
  450. mod = registry[id] = new context.Module(depMap);
  451. }
  452. return mod;
  453. }
  454. function on(depMap, name, fn) {
  455. var id = depMap.id,
  456. mod = getOwn(registry, id);
  457. if (hasProp(defined, id) &&
  458. (!mod || mod.defineEmitComplete)) {
  459. if (name === 'defined') {
  460. fn(defined[id]);
  461. }
  462. } else {
  463. mod = getModule(depMap);
  464. if (mod.error && name === 'error') {
  465. fn(mod.error);
  466. } else {
  467. mod.on(name, fn);
  468. }
  469. }
  470. }
  471. function onError(err, errback) {
  472. var ids = err.requireModules,
  473. notified = false;
  474. if (errback) {
  475. errback(err);
  476. } else {
  477. each(ids, function (id) {
  478. var mod = getOwn(registry, id);
  479. if (mod) {
  480. //Set error on module, so it skips timeout checks.
  481. mod.error = err;
  482. if (mod.events.error) {
  483. notified = true;
  484. mod.emit('error', err);
  485. }
  486. }
  487. });
  488. if (!notified) {
  489. req.onError(err);
  490. }
  491. }
  492. }
  493. /**
  494. * Internal method to transfer globalQueue items to this context's
  495. * defQueue.
  496. */
  497. function takeGlobalQueue() {
  498. //Push all the globalDefQueue items into the context's defQueue
  499. if (globalDefQueue.length) {
  500. //Array splice in the values since the context code has a
  501. //local var ref to defQueue, so cannot just reassign the one
  502. //on context.
  503. apsp.apply(defQueue,
  504. [defQueue.length, 0].concat(globalDefQueue));
  505. globalDefQueue = [];
  506. }
  507. }
  508. handlers = {
  509. 'require': function (mod) {
  510. if (mod.require) {
  511. return mod.require;
  512. } else {
  513. return (mod.require = context.makeRequire(mod.map));
  514. }
  515. },
  516. 'exports': function (mod) {
  517. mod.usingExports = true;
  518. if (mod.map.isDefine) {
  519. if (mod.exports) {
  520. return (defined[mod.map.id] = mod.exports);
  521. } else {
  522. return (mod.exports = defined[mod.map.id] = {});
  523. }
  524. }
  525. },
  526. 'module': function (mod) {
  527. if (mod.module) {
  528. return mod.module;
  529. } else {
  530. return (mod.module = {
  531. id: mod.map.id,
  532. uri: mod.map.url,
  533. config: function () {
  534. return getOwn(config.config, mod.map.id) || {};
  535. },
  536. exports: mod.exports || (mod.exports = {})
  537. });
  538. }
  539. }
  540. };
  541. function cleanRegistry(id) {
  542. //Clean up machinery used for waiting modules.
  543. delete registry[id];
  544. delete enabledRegistry[id];
  545. }
  546. function breakCycle(mod, traced, processed) {
  547. var id = mod.map.id;
  548. if (mod.error) {
  549. mod.emit('error', mod.error);
  550. } else {
  551. traced[id] = true;
  552. each(mod.depMaps, function (depMap, i) {
  553. var depId = depMap.id,
  554. dep = getOwn(registry, depId);
  555. //Only force things that have not completed
  556. //being defined, so still in the registry,
  557. //and only if it has not been matched up
  558. //in the module already.
  559. if (dep && !mod.depMatched[i] && !processed[depId]) {
  560. if (getOwn(traced, depId)) {
  561. mod.defineDep(i, defined[depId]);
  562. mod.check(); //pass false?
  563. } else {
  564. breakCycle(dep, traced, processed);
  565. }
  566. }
  567. });
  568. processed[id] = true;
  569. }
  570. }
  571. function checkLoaded() {
  572. var err, usingPathFallback,
  573. waitInterval = config.waitSeconds * 1000,
  574. //It is possible to disable the wait interval by using waitSeconds of 0.
  575. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
  576. noLoads = [],
  577. reqCalls = [],
  578. stillLoading = false,
  579. needCycleCheck = true;
  580. //Do not bother if this call was a result of a cycle break.
  581. if (inCheckLoaded) {
  582. return;
  583. }
  584. inCheckLoaded = true;
  585. //Figure out the state of all the modules.
  586. eachProp(enabledRegistry, function (mod) {
  587. var map = mod.map,
  588. modId = map.id;
  589. //Skip things that are not enabled or in error state.
  590. if (!mod.enabled) {
  591. return;
  592. }
  593. if (!map.isDefine) {
  594. reqCalls.push(mod);
  595. }
  596. if (!mod.error) {
  597. //If the module should be executed, and it has not
  598. //been inited and time is up, remember it.
  599. if (!mod.inited && expired) {
  600. if (hasPathFallback(modId)) {
  601. usingPathFallback = true;
  602. stillLoading = true;
  603. } else {
  604. noLoads.push(modId);
  605. removeScript(modId);
  606. }
  607. } else if (!mod.inited && mod.fetched && map.isDefine) {
  608. stillLoading = true;
  609. if (!map.prefix) {
  610. //No reason to keep looking for unfinished
  611. //loading. If the only stillLoading is a
  612. //plugin resource though, keep going,
  613. //because it may be that a plugin resource
  614. //is waiting on a non-plugin cycle.
  615. return (needCycleCheck = false);
  616. }
  617. }
  618. }
  619. });
  620. if (expired && noLoads.length) {
  621. //If wait time expired, throw error of unloaded modules.
  622. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
  623. err.contextName = context.contextName;
  624. return onError(err);
  625. }
  626. //Not expired, check for a cycle.
  627. if (needCycleCheck) {
  628. each(reqCalls, function (mod) {
  629. breakCycle(mod, {}, {});
  630. });
  631. }
  632. //If still waiting on loads, and the waiting load is something
  633. //other than a plugin resource, or there are still outstanding
  634. //scripts, then just try back later.
  635. if ((!expired || usingPathFallback) && stillLoading) {
  636. //Something is still waiting to load. Wait for it, but only
  637. //if a timeout is not already in effect.
  638. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
  639. checkLoadedTimeoutId = setTimeout(function () {
  640. checkLoadedTimeoutId = 0;
  641. checkLoaded();
  642. }, 50);
  643. }
  644. }
  645. inCheckLoaded = false;
  646. }
  647. Module = function (map) {
  648. this.events = getOwn(undefEvents, map.id) || {};
  649. this.map = map;
  650. this.shim = getOwn(config.shim, map.id);
  651. this.depExports = [];
  652. this.depMaps = [];
  653. this.depMatched = [];
  654. this.pluginMaps = {};
  655. this.depCount = 0;
  656. /* this.exports this.factory
  657. this.depMaps = [],
  658. this.enabled, this.fetched
  659. */
  660. };
  661. Module.prototype = {
  662. init: function (depMaps, factory, errback, options) {
  663. options = options || {};
  664. //Do not do more inits if already done. Can happen if there
  665. //are multiple define calls for the same module. That is not
  666. //a normal, common case, but it is also not unexpected.
  667. if (this.inited) {
  668. return;
  669. }
  670. this.factory = factory;
  671. if (errback) {
  672. //Register for errors on this module.
  673. this.on('error', errback);
  674. } else if (this.events.error) {
  675. //If no errback already, but there are error listeners
  676. //on this module, set up an errback to pass to the deps.
  677. errback = bind(this, function (err) {
  678. this.emit('error', err);
  679. });
  680. }
  681. //Do a copy of the dependency array, so that
  682. //source inputs are not modified. For example
  683. //"shim" deps are passed in here directly, and
  684. //doing a direct modification of the depMaps array
  685. //would affect that config.
  686. this.depMaps = depMaps && depMaps.slice(0);
  687. this.errback = errback;
  688. //Indicate this module has be initialized
  689. this.inited = true;
  690. this.ignore = options.ignore;
  691. //Could have option to init this module in enabled mode,
  692. //or could have been previously marked as enabled. However,
  693. //the dependencies are not known until init is called. So
  694. //if enabled previously, now trigger dependencies as enabled.
  695. if (options.enabled || this.enabled) {
  696. //Enable this module and dependencies.
  697. //Will call this.check()
  698. this.enable();
  699. } else {
  700. this.check();
  701. }
  702. },
  703. defineDep: function (i, depExports) {
  704. //Because of cycles, defined callback for a given
  705. //export can be called more than once.
  706. if (!this.depMatched[i]) {
  707. this.depMatched[i] = true;
  708. this.depCount -= 1;
  709. this.depExports[i] = depExports;
  710. }
  711. },
  712. fetch: function () {
  713. if (this.fetched) {
  714. return;
  715. }
  716. this.fetched = true;
  717. context.startTime = (new Date()).getTime();
  718. var map = this.map;
  719. //If the manager is for a plugin managed resource,
  720. //ask the plugin to load it now.
  721. if (this.shim) {
  722. context.makeRequire(this.map, {
  723. enableBuildCallback: true
  724. })(this.shim.deps || [], bind(this, function () {
  725. return map.prefix ? this.callPlugin() : this.load();
  726. }));
  727. } else {
  728. //Regular dependency.
  729. return map.prefix ? this.callPlugin() : this.load();
  730. }
  731. },
  732. load: function () {
  733. var url = this.map.url;
  734. //Regular dependency.
  735. if (!urlFetched[url]) {
  736. urlFetched[url] = true;
  737. context.load(this.map.id, url);
  738. }
  739. },
  740. /**
  741. * Checks if the module is ready to define itself, and if so,
  742. * define it.
  743. */
  744. check: function () {
  745. if (!this.enabled || this.enabling) {
  746. return;
  747. }
  748. var err, cjsModule,
  749. id = this.map.id,
  750. depExports = this.depExports,
  751. exports = this.exports,
  752. factory = this.factory;
  753. if (!this.inited) {
  754. this.fetch();
  755. } else if (this.error) {
  756. this.emit('error', this.error);
  757. } else if (!this.defining) {
  758. //The factory could trigger another require call
  759. //that would result in checking this module to
  760. //define itself again. If already in the process
  761. //of doing that, skip this work.
  762. this.defining = true;
  763. if (this.depCount < 1 && !this.defined) {
  764. if (isFunction(factory)) {
  765. //If there is an error listener, favor passing
  766. //to that instead of throwing an error. However,
  767. //only do it for define()'d modules. require
  768. //errbacks should not be called for failures in
  769. //their callbacks (#699). However if a global
  770. //onError is set, use that.
  771. if ((this.events.error && this.map.isDefine) ||
  772. req.onError !== defaultOnError) {
  773. try {
  774. exports = context.execCb(id, factory, depExports, exports);
  775. } catch (e) {
  776. err = e;
  777. }
  778. } else {
  779. exports = context.execCb(id, factory, depExports, exports);
  780. }
  781. // Favor return value over exports. If node/cjs in play,
  782. // then will not have a return value anyway. Favor
  783. // module.exports assignment over exports object.
  784. if (this.map.isDefine && exports === undefined) {
  785. cjsModule = this.module;
  786. if (cjsModule) {
  787. exports = cjsModule.exports;
  788. } else if (this.usingExports) {
  789. //exports already set the defined value.
  790. exports = this.exports;
  791. }
  792. }
  793. if (err) {
  794. err.requireMap = this.map;
  795. err.requireModules = this.map.isDefine ? [this.map.id] : null;
  796. err.requireType = this.map.isDefine ? 'define' : 'require';
  797. return onError((this.error = err));
  798. }
  799. } else {
  800. //Just a literal value
  801. exports = factory;
  802. }
  803. this.exports = exports;
  804. if (this.map.isDefine && !this.ignore) {
  805. defined[id] = exports;
  806. if (req.onResourceLoad) {
  807. req.onResourceLoad(context, this.map, this.depMaps);
  808. }
  809. }
  810. //Clean up
  811. cleanRegistry(id);
  812. this.defined = true;
  813. }
  814. //Finished the define stage. Allow calling check again
  815. //to allow define notifications below in the case of a
  816. //cycle.
  817. this.defining = false;
  818. if (this.defined && !this.defineEmitted) {
  819. this.defineEmitted = true;
  820. this.emit('defined', this.exports);
  821. this.defineEmitComplete = true;
  822. }
  823. }
  824. },
  825. callPlugin: function () {
  826. var map = this.map,
  827. id = map.id,
  828. //Map already normalized the prefix.
  829. pluginMap = makeModuleMap(map.prefix);
  830. //Mark this as a dependency for this plugin, so it
  831. //can be traced for cycles.
  832. this.depMaps.push(pluginMap);
  833. on(pluginMap, 'defined', bind(this, function (plugin) {
  834. var load, normalizedMap, normalizedMod,
  835. bundleId = getOwn(bundlesMap, this.map.id),
  836. name = this.map.name,
  837. parentName = this.map.parentMap ? this.map.parentMap.name : null,
  838. localRequire = context.makeRequire(map.parentMap, {
  839. enableBuildCallback: true
  840. });
  841. //If current map is not normalized, wait for that
  842. //normalized name to load instead of continuing.
  843. if (this.map.unnormalized) {
  844. //Normalize the ID if the plugin allows it.
  845. if (plugin.normalize) {
  846. name = plugin.normalize(name, function (name) {
  847. return normalize(name, parentName, true);
  848. }) || '';
  849. }
  850. //prefix and name should already be normalized, no need
  851. //for applying map config again either.
  852. normalizedMap = makeModuleMap(map.prefix + '!' + name,
  853. this.map.parentMap);
  854. on(normalizedMap,
  855. 'defined', bind(this, function (value) {
  856. this.init([], function () { return value; }, null, {
  857. enabled: true,
  858. ignore: true
  859. });
  860. }));
  861. normalizedMod = getOwn(registry, normalizedMap.id);
  862. if (normalizedMod) {
  863. //Mark this as a dependency for this plugin, so it
  864. //can be traced for cycles.
  865. this.depMaps.push(normalizedMap);
  866. if (this.events.error) {
  867. normalizedMod.on('error', bind(this, function (err) {
  868. this.emit('error', err);
  869. }));
  870. }
  871. normalizedMod.enable();
  872. }
  873. return;
  874. }
  875. //If a paths config, then just load that file instead to
  876. //resolve the plugin, as it is built into that paths layer.
  877. if (bundleId) {
  878. this.map.url = context.nameToUrl(bundleId);
  879. this.load();
  880. return;
  881. }
  882. load = bind(this, function (value) {
  883. this.init([], function () { return value; }, null, {
  884. enabled: true
  885. });
  886. });
  887. load.error = bind(this, function (err) {
  888. this.inited = true;
  889. this.error = err;
  890. err.requireModules = [id];
  891. //Remove temp unnormalized modules for this module,
  892. //since they will never be resolved otherwise now.
  893. eachProp(registry, function (mod) {
  894. if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
  895. cleanRegistry(mod.map.id);
  896. }
  897. });
  898. onError(err);
  899. });
  900. //Allow plugins to load other code without having to know the
  901. //context or how to 'complete' the load.
  902. load.fromText = bind(this, function (text, textAlt) {
  903. /*jslint evil: true */
  904. var moduleName = map.name,
  905. moduleMap = makeModuleMap(moduleName),
  906. hasInteractive = useInteractive;
  907. //As of 2.1.0, support just passing the text, to reinforce
  908. //fromText only being called once per resource. Still
  909. //support old style of passing moduleName but discard
  910. //that moduleName in favor of the internal ref.
  911. if (textAlt) {
  912. text = textAlt;
  913. }
  914. //Turn off interactive script matching for IE for any define
  915. //calls in the text, then turn it back on at the end.
  916. if (hasInteractive) {
  917. useInteractive = false;
  918. }
  919. //Prime the system by creating a module instance for
  920. //it.
  921. getModule(moduleMap);
  922. //Transfer any config to this other module.
  923. if (hasProp(config.config, id)) {
  924. config.config[moduleName] = config.config[id];
  925. }
  926. try {
  927. req.exec(text);
  928. } catch (e) {
  929. return onError(makeError('fromtexteval',
  930. 'fromText eval for ' + id +
  931. ' failed: ' + e,
  932. e,
  933. [id]));
  934. }
  935. if (hasInteractive) {
  936. useInteractive = true;
  937. }
  938. //Mark this as a dependency for the plugin
  939. //resource
  940. this.depMaps.push(moduleMap);
  941. //Support anonymous modules.
  942. context.completeLoad(moduleName);
  943. //Bind the value of that module to the value for this
  944. //resource ID.
  945. localRequire([moduleName], load);
  946. });
  947. //Use parentName here since the plugin's name is not reliable,
  948. //could be some weird string with no path that actually wants to
  949. //reference the parentName's path.
  950. plugin.load(map.name, localRequire, load, config);
  951. }));
  952. context.enable(pluginMap, this);
  953. this.pluginMaps[pluginMap.id] = pluginMap;
  954. },
  955. enable: function () {
  956. enabledRegistry[this.map.id] = this;
  957. this.enabled = true;
  958. //Set flag mentioning that the module is enabling,
  959. //so that immediate calls to the defined callbacks
  960. //for dependencies do not trigger inadvertent load
  961. //with the depCount still being zero.
  962. this.enabling = true;
  963. //Enable each dependency
  964. each(this.depMaps, bind(this, function (depMap, i) {
  965. var id, mod, handler;
  966. if (typeof depMap === 'string') {
  967. //Dependency needs to be converted to a depMap
  968. //and wired up to this module.
  969. depMap = makeModuleMap(depMap,
  970. (this.map.isDefine ? this.map : this.map.parentMap),
  971. false,
  972. !this.skipMap);
  973. this.depMaps[i] = depMap;
  974. handler = getOwn(handlers, depMap.id);
  975. if (handler) {
  976. this.depExports[i] = handler(this);
  977. return;
  978. }
  979. this.depCount += 1;
  980. on(depMap, 'defined', bind(this, function (depExports) {
  981. this.defineDep(i, depExports);
  982. this.check();
  983. }));
  984. if (this.errback) {
  985. on(depMap, 'error', bind(this, this.errback));
  986. } else if (this.events.error) {
  987. // No direct errback on this module, but something
  988. // else is listening for errors, so be sure to
  989. // propagate the error correctly.
  990. on(depMap, 'error', bind(this, function(err) {
  991. this.emit('error', err);
  992. }));
  993. }
  994. }
  995. id = depMap.id;
  996. mod = registry[id];
  997. //Skip special modules like 'require', 'exports', 'module'
  998. //Also, don't call enable if it is already enabled,
  999. //important in circular dependency cases.
  1000. if (!hasProp(handlers, id) && mod && !mod.enabled) {
  1001. context.enable(depMap, this);
  1002. }
  1003. }));
  1004. //Enable each plugin that is used in
  1005. //a dependency
  1006. eachProp(this.pluginMaps, bind(this, function (pluginMap) {
  1007. var mod = getOwn(registry, pluginMap.id);
  1008. if (mod && !mod.enabled) {
  1009. context.enable(pluginMap, this);
  1010. }
  1011. }));
  1012. this.enabling = false;
  1013. this.check();
  1014. },
  1015. on: function (name, cb) {
  1016. var cbs = this.events[name];
  1017. if (!cbs) {
  1018. cbs = this.events[name] = [];
  1019. }
  1020. cbs.push(cb);
  1021. },
  1022. emit: function (name, evt) {
  1023. each(this.events[name], function (cb) {
  1024. cb(evt);
  1025. });
  1026. if (name === 'error') {
  1027. //Now that the error handler was triggered, remove
  1028. //the listeners, since this broken Module instance
  1029. //can stay around for a while in the registry.
  1030. delete this.events[name];
  1031. }
  1032. }
  1033. };
  1034. function callGetModule(args) {
  1035. //Skip modules already defined.
  1036. if (!hasProp(defined, args[0])) {
  1037. getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
  1038. }
  1039. }
  1040. function removeListener(node, func, name, ieName) {
  1041. //Favor detachEvent because of IE9
  1042. //issue, see attachEvent/addEventListener comment elsewhere
  1043. //in this file.
  1044. if (node.detachEvent && !isOpera) {
  1045. //Probably IE. If not it will throw an error, which will be
  1046. //useful to know.
  1047. if (ieName) {
  1048. node.detachEvent(ieName, func);
  1049. }
  1050. } else {
  1051. node.removeEventListener(name, func, false);
  1052. }
  1053. }
  1054. /**
  1055. * Given an event from a script node, get the requirejs info from it,
  1056. * and then removes the event listeners on the node.
  1057. * @param {Event} evt
  1058. * @returns {Object}
  1059. */
  1060. function getScriptData(evt) {
  1061. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1062. //all old browsers will be supported, but this one was easy enough
  1063. //to support and still makes sense.
  1064. var node = evt.currentTarget || evt.srcElement;
  1065. //Remove the listeners once here.
  1066. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
  1067. removeListener(node, context.onScriptError, 'error');
  1068. return {
  1069. node: node,
  1070. id: node && node.getAttribute('data-requiremodule')
  1071. };
  1072. }
  1073. function intakeDefines() {
  1074. var args;
  1075. //Any defined modules in the global queue, intake them now.
  1076. takeGlobalQueue();
  1077. //Make sure any remaining defQueue items get properly processed.
  1078. while (defQueue.length) {
  1079. args = defQueue.shift();
  1080. if (args[0] === null) {
  1081. return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
  1082. } else {
  1083. //args are id, deps, factory. Should be normalized by the
  1084. //define() function.
  1085. callGetModule(args);
  1086. }
  1087. }
  1088. }
  1089. context = {
  1090. config: config,
  1091. contextName: contextName,
  1092. registry: registry,
  1093. defined: defined,
  1094. urlFetched: urlFetched,
  1095. defQueue: defQueue,
  1096. Module: Module,
  1097. makeModuleMap: makeModuleMap,
  1098. nextTick: req.nextTick,
  1099. onError: onError,
  1100. /**
  1101. * Set a configuration for the context.
  1102. * @param {Object} cfg config object to integrate.
  1103. */
  1104. configure: function (cfg) {
  1105. //Make sure the baseUrl ends in a slash.
  1106. if (cfg.baseUrl) {
  1107. if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
  1108. cfg.baseUrl += '/';
  1109. }
  1110. }
  1111. //Save off the paths since they require special processing,
  1112. //they are additive.
  1113. var shim = config.shim,
  1114. objs = {
  1115. paths: true,
  1116. bundles: true,
  1117. config: true,
  1118. map: true
  1119. };
  1120. eachProp(cfg, function (value, prop) {
  1121. if (objs[prop]) {
  1122. if (!config[prop]) {
  1123. config[prop] = {};
  1124. }
  1125. mixin(config[prop], value, true, true);
  1126. } else {
  1127. config[prop] = value;
  1128. }
  1129. });
  1130. //Reverse map the bundles
  1131. if (cfg.bundles) {
  1132. eachProp(cfg.bundles, function (value, prop) {
  1133. each(value, function (v) {
  1134. if (v !== prop) {
  1135. bundlesMap[v] = prop;
  1136. }
  1137. });
  1138. });
  1139. }
  1140. //Merge shim
  1141. if (cfg.shim) {
  1142. eachProp(cfg.shim, function (value, id) {
  1143. //Normalize the structure
  1144. if (isArray(value)) {
  1145. value = {
  1146. deps: value
  1147. };
  1148. }
  1149. if ((value.exports || value.init) && !value.exportsFn) {
  1150. value.exportsFn = context.makeShimExports(value);
  1151. }
  1152. shim[id] = value;
  1153. });
  1154. config.shim = shim;
  1155. }
  1156. //Adjust packages if necessary.
  1157. if (cfg.packages) {
  1158. each(cfg.packages, function (pkgObj) {
  1159. var location, name;
  1160. pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
  1161. name = pkgObj.name;
  1162. location = pkgObj.location;
  1163. if (location) {
  1164. config.paths[name] = pkgObj.location;
  1165. }
  1166. //Save pointer to main module ID for pkg name.
  1167. //Remove leading dot in main, so main paths are normalized,
  1168. //and remove any trailing .js, since different package
  1169. //envs have different conventions: some use a module name,
  1170. //some use a file name.
  1171. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
  1172. .replace(currDirRegExp, '')
  1173. .replace(jsSuffixRegExp, '');
  1174. });
  1175. }
  1176. //If there are any "waiting to execute" modules in the registry,
  1177. //update the maps for them, since their info, like URLs to load,
  1178. //may have changed.
  1179. eachProp(registry, function (mod, id) {
  1180. //If module already has init called, since it is too
  1181. //late to modify them, and ignore unnormalized ones
  1182. //since they are transient.
  1183. if (!mod.inited && !mod.map.unnormalized) {
  1184. mod.map = makeModuleMap(id);
  1185. }
  1186. });
  1187. //If a deps array or a config callback is specified, then call
  1188. //require with those args. This is useful when require is defined as a
  1189. //config object before require.js is loaded.
  1190. if (cfg.deps || cfg.callback) {
  1191. context.require(cfg.deps || [], cfg.callback);
  1192. }
  1193. },
  1194. makeShimExports: function (value) {
  1195. function fn() {
  1196. var ret;
  1197. if (value.init) {
  1198. ret = value.init.apply(global, arguments);
  1199. }
  1200. return ret || (value.exports && getGlobal(value.exports));
  1201. }
  1202. return fn;
  1203. },
  1204. makeRequire: function (relMap, options) {
  1205. options = options || {};
  1206. function localRequire(deps, callback, errback) {
  1207. var id, map, requireMod;
  1208. if (options.enableBuildCallback && callback && isFunction(callback)) {
  1209. callback.__requireJsBuild = true;
  1210. }
  1211. if (typeof deps === 'string') {
  1212. if (isFunction(callback)) {
  1213. //Invalid call
  1214. return onError(makeError('requireargs', 'Invalid require call'), errback);
  1215. }
  1216. //If require|exports|module are requested, get the
  1217. //value for them from the special handlers. Caveat:
  1218. //this only works while module is being defined.
  1219. if (relMap && hasProp(handlers, deps)) {
  1220. return handlers[deps](registry[relMap.id]);
  1221. }
  1222. //Synchronous access to one module. If require.get is
  1223. //available (as in the Node adapter), prefer that.
  1224. if (req.get) {
  1225. return req.get(context, deps, relMap, localRequire);
  1226. }
  1227. //Normalize module name, if it contains . or ..
  1228. map = makeModuleMap(deps, relMap, false, true);
  1229. id = map.id;
  1230. if (!hasProp(defined, id)) {
  1231. return onError(makeError('notloaded', 'Module name "' +
  1232. id +
  1233. '" has not been loaded yet for context: ' +
  1234. contextName +
  1235. (relMap ? '' : '. Use require([])')));
  1236. }
  1237. return defined[id];
  1238. }
  1239. //Grab defines waiting in the global queue.
  1240. intakeDefines();
  1241. //Mark all the dependencies as needing to be loaded.
  1242. context.nextTick(function () {
  1243. //Some defines could have been added since the
  1244. //require call, collect them.
  1245. intakeDefines();
  1246. requireMod = getModule(makeModuleMap(null, relMap));
  1247. //Store if map config should be applied to this require
  1248. //call for dependencies.
  1249. requireMod.skipMap = options.skipMap;
  1250. requireMod.init(deps, callback, errback, {
  1251. enabled: true
  1252. });
  1253. checkLoaded();
  1254. });
  1255. return localRequire;
  1256. }
  1257. mixin(localRequire, {
  1258. isBrowser: isBrowser,
  1259. /**
  1260. * Converts a module name + .extension into an URL path.
  1261. * *Requires* the use of a module name. It does not support using
  1262. * plain URLs like nameToUrl.
  1263. */
  1264. toUrl: function (moduleNamePlusExt) {
  1265. var ext,
  1266. index = moduleNamePlusExt.lastIndexOf('.'),
  1267. segment = moduleNamePlusExt.split('/')[0],
  1268. isRelative = segment === '.' || segment === '..';
  1269. //Have a file extension alias, and it is not the
  1270. //dots from a relative path.
  1271. if (index !== -1 && (!isRelative || index > 1)) {
  1272. ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
  1273. moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
  1274. }
  1275. return context.nameToUrl(normalize(moduleNamePlusExt,
  1276. relMap && relMap.id, true), ext, true);
  1277. },
  1278. defined: function (id) {
  1279. return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
  1280. },
  1281. specified: function (id) {
  1282. id = makeModuleMap(id, relMap, false, true).id;
  1283. return hasProp(defined, id) || hasProp(registry, id);
  1284. }
  1285. });
  1286. //Only allow undef on top level require calls
  1287. if (!relMap) {
  1288. localRequire.undef = function (id) {
  1289. //Bind any waiting define() calls to this context,
  1290. //fix for #408
  1291. takeGlobalQueue();
  1292. var map = makeModuleMap(id, relMap, true),
  1293. mod = getOwn(registry, id);
  1294. removeScript(id);
  1295. delete defined[id];
  1296. delete urlFetched[map.url];
  1297. delete undefEvents[id];
  1298. //Clean queued defines too. Go backwards
  1299. //in array so that the splices do not
  1300. //mess up the iteration.
  1301. eachReverse(defQueue, function(args, i) {
  1302. if(args[0] === id) {
  1303. defQueue.splice(i, 1);
  1304. }
  1305. });
  1306. if (mod) {
  1307. //Hold on to listeners in case the
  1308. //module will be attempted to be reloaded
  1309. //using a different config.
  1310. if (mod.events.defined) {
  1311. undefEvents[id] = mod.events;
  1312. }
  1313. cleanRegistry(id);
  1314. }
  1315. };
  1316. }
  1317. return localRequire;
  1318. },
  1319. /**
  1320. * Called to enable a module if it is still in the registry
  1321. * awaiting enablement. A second arg, parent, the parent module,
  1322. * is passed in for context, when this method is overridden by
  1323. * the optimizer. Not shown here to keep code compact.
  1324. */
  1325. enable: function (depMap) {
  1326. var mod = getOwn(registry, depMap.id);
  1327. if (mod) {
  1328. getModule(depMap).enable();
  1329. }
  1330. },
  1331. /**
  1332. * Internal method used by environment adapters to complete a load event.
  1333. * A load event could be a script load or just a load pass from a synchronous
  1334. * load call.
  1335. * @param {String} moduleName the name of the module to potentially complete.
  1336. */
  1337. completeLoad: function (moduleName) {
  1338. var found, args, mod,
  1339. shim = getOwn(config.shim, moduleName) || {},
  1340. shExports = shim.exports;
  1341. takeGlobalQueue();
  1342. while (defQueue.length) {
  1343. args = defQueue.shift();
  1344. if (args[0] === null) {
  1345. args[0] = moduleName;
  1346. //If already found an anonymous module and bound it
  1347. //to this name, then this is some other anon module
  1348. //waiting for its completeLoad to fire.
  1349. if (found) {
  1350. break;
  1351. }
  1352. found = true;
  1353. } else if (args[0] === moduleName) {
  1354. //Found matching define call for this script!
  1355. found = true;
  1356. }
  1357. callGetModule(args);
  1358. }
  1359. //Do this after the cycle of callGetModule in case the result
  1360. //of those calls/init calls changes the registry.
  1361. mod = getOwn(registry, moduleName);
  1362. if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
  1363. if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
  1364. if (hasPathFallback(moduleName)) {
  1365. return;
  1366. } else {
  1367. return onError(makeError('nodefine',
  1368. 'No define call for ' + moduleName,
  1369. null,
  1370. [moduleName]));
  1371. }
  1372. } else {
  1373. //A script that does not call define(), so just simulate
  1374. //the call for it.
  1375. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
  1376. }
  1377. }
  1378. checkLoaded();
  1379. },
  1380. /**
  1381. * Converts a module name to a file path. Supports cases where
  1382. * moduleName may actually be just an URL.
  1383. * Note that it **does not** call normalize on the moduleName,
  1384. * it is assumed to have already been normalized. This is an
  1385. * internal API, not a public one. Use toUrl for the public API.
  1386. */
  1387. nameToUrl: function (moduleName, ext, skipExt) {
  1388. var paths, syms, i, parentModule, url,
  1389. parentPath, bundleId,
  1390. pkgMain = getOwn(config.pkgs, moduleName);
  1391. if (pkgMain) {
  1392. moduleName = pkgMain;
  1393. }
  1394. bundleId = getOwn(bundlesMap, moduleName);
  1395. if (bundleId) {
  1396. return context.nameToUrl(bundleId, ext, skipExt);
  1397. }
  1398. //If a colon is in the URL, it indicates a protocol is used and it is just
  1399. //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
  1400. //or ends with .js, then assume the user meant to use an url and not a module id.
  1401. //The slash is important for protocol-less URLs as well as full paths.
  1402. if (req.jsExtRegExp.test(moduleName)) {
  1403. //Just a plain path, not module name lookup, so just return it.
  1404. //Add extension if it is included. This is a bit wonky, only non-.js things pass
  1405. //an extension, this method probably needs to be reworked.
  1406. url = moduleName + (ext || '');
  1407. } else {
  1408. //A module that needs to be converted to a path.
  1409. paths = config.paths;
  1410. syms = moduleName.split('/');
  1411. //For each module name segment, see if there is a path
  1412. //registered for it. Start with most specific name
  1413. //and work up from it.
  1414. for (i = syms.length; i > 0; i -= 1) {
  1415. parentModule = syms.slice(0, i).join('/');
  1416. parentPath = getOwn(paths, parentModule);
  1417. if (parentPath) {
  1418. //If an array, it means there are a few choices,
  1419. //Choose the one that is desired
  1420. if (isArray(parentPath)) {
  1421. parentPath = parentPath[0];
  1422. }
  1423. syms.splice(0, i, parentPath);
  1424. break;
  1425. }
  1426. }
  1427. //Join the path parts together, then figure out if baseUrl is needed.
  1428. url = syms.join('/');
  1429. url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
  1430. url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
  1431. }
  1432. return config.urlArgs ? url +
  1433. ((url.indexOf('?') === -1 ? '?' : '&') +
  1434. config.urlArgs) : url;
  1435. },
  1436. //Delegates to req.load. Broken out as a separate function to
  1437. //allow overriding in the optimizer.
  1438. load: function (id, url) {
  1439. req.load(context, id, url);
  1440. },
  1441. /**
  1442. * Executes a module callback function. Broken out as a separate function
  1443. * solely to allow the build system to sequence the files in the built
  1444. * layer in the right sequence.
  1445. *
  1446. * @private
  1447. */
  1448. execCb: function (name, callback, args, exports) {
  1449. return callback.apply(exports, args);
  1450. },
  1451. /**
  1452. * callback for script loads, used to check status of loading.
  1453. *
  1454. * @param {Event} evt the event from the browser for the script
  1455. * that was loaded.
  1456. */
  1457. onScriptLoad: function (evt) {
  1458. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1459. //all old browsers will be supported, but this one was easy enough
  1460. //to support and still makes sense.
  1461. if (evt.type === 'load' ||
  1462. (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
  1463. //Reset interactive script so a script node is not held onto for
  1464. //to long.
  1465. interactiveScript = null;
  1466. //Pull out the name of the module and the context.
  1467. var data = getScriptData(evt);
  1468. context.completeLoad(data.id);
  1469. }
  1470. },
  1471. /**
  1472. * Callback for script errors.
  1473. */
  1474. onScriptError: function (evt) {
  1475. var data = getScriptData(evt);
  1476. if (!hasPathFallback(data.id)) {
  1477. return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
  1478. }
  1479. }
  1480. };
  1481. context.require = context.makeRequire();
  1482. return context;
  1483. }
  1484. /**
  1485. * Main entry point.
  1486. *
  1487. * If the only argument to require is a string, then the module that
  1488. * is represented by that string is fetched for the appropriate context.
  1489. *
  1490. * If the first argument is an array, then it will be treated as an array
  1491. * of dependency string names to fetch. An optional function callback can
  1492. * be specified to execute when all of those dependencies are available.
  1493. *
  1494. * Make a local req variable to help Caja compliance (it assumes things
  1495. * on a require that are not standardized), and to give a short
  1496. * name for minification/local scope use.
  1497. */
  1498. req = requirejs = function (deps, callback, errback, optional) {
  1499. //Find the right context, use default
  1500. var context, config,
  1501. contextName = defContextName;
  1502. // Determine if have config object in the call.
  1503. if (!isArray(deps) && typeof deps !== 'string') {
  1504. // deps is a config object
  1505. config = deps;
  1506. if (isArray(callback)) {
  1507. // Adjust args if there are dependencies
  1508. deps = callback;
  1509. callback = errback;
  1510. errback = optional;
  1511. } else {
  1512. deps = [];
  1513. }
  1514. }
  1515. if (config && config.context) {
  1516. contextName = config.context;
  1517. }
  1518. context = getOwn(contexts, contextName);
  1519. if (!context) {
  1520. context = contexts[contextName] = req.s.newContext(contextName);
  1521. }
  1522. if (config) {
  1523. context.configure(config);
  1524. }
  1525. return context.require(deps, callback, errback);
  1526. };
  1527. /**
  1528. * Support require.config() to make it easier to cooperate with other
  1529. * AMD loaders on globally agreed names.
  1530. */
  1531. req.config = function (config) {
  1532. return req(config);
  1533. };
  1534. /**
  1535. * Execute something after the current tick
  1536. * of the event loop. Override for other envs
  1537. * that have a better solution than setTimeout.
  1538. * @param {Function} fn function to execute later.
  1539. */
  1540. req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
  1541. setTimeout(fn, 4);
  1542. } : function (fn) { fn(); };
  1543. /**
  1544. * Export require as a global, but only if it does not already exist.
  1545. */
  1546. if (!require) {
  1547. require = req;
  1548. }
  1549. req.version = version;
  1550. //Used to filter out dependencies that are already paths.
  1551. req.jsExtRegExp = /^\/|:|\?|\.js$/;
  1552. req.isBrowser = isBrowser;
  1553. s = req.s = {
  1554. contexts: contexts,
  1555. newContext: newContext
  1556. };
  1557. //Create default context.
  1558. req({});
  1559. //Exports some context-sensitive methods on global require.
  1560. each([
  1561. 'toUrl',
  1562. 'undef',
  1563. 'defined',
  1564. 'specified'
  1565. ], function (prop) {
  1566. //Reference from contexts instead of early binding to default context,
  1567. //so that during builds, the latest instance of the default context
  1568. //with its config gets used.
  1569. req[prop] = function () {
  1570. var ctx = contexts[defContextName];
  1571. return ctx.require[prop].apply(ctx, arguments);
  1572. };
  1573. });
  1574. if (isBrowser) {
  1575. head = s.head = document.getElementsByTagName('head')[0];
  1576. //If BASE tag is in play, using appendChild is a problem for IE6.
  1577. //When that browser dies, this can be removed. Details in this jQuery bug:
  1578. //http://dev.jquery.com/ticket/2709
  1579. baseElement = document.getElementsByTagName('base')[0];
  1580. if (baseElement) {
  1581. head = s.head = baseElement.parentNode;
  1582. }
  1583. }
  1584. /**
  1585. * Any errors that require explicitly generates will be passed to this
  1586. * function. Intercept/override it if you want custom error handling.
  1587. * @param {Error} err the error object.
  1588. */
  1589. req.onError = defaultOnError;
  1590. /**
  1591. * Creates the node for the load command. Only used in browser envs.
  1592. */
  1593. req.createNode = function (config, moduleName, url) {
  1594. var node = config.xhtml ?
  1595. document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
  1596. document.createElement('script');
  1597. node.type = config.scriptType || 'text/javascript';
  1598. node.charset = 'utf-8';
  1599. node.async = true;
  1600. return node;
  1601. };
  1602. /**
  1603. * Does the request to load a module for the browser case.
  1604. * Make this a separate function to allow other environments
  1605. * to override it.
  1606. *
  1607. * @param {Object} context the require context to find state.
  1608. * @param {String} moduleName the name of the module.
  1609. * @param {Object} url the URL to the module.
  1610. */
  1611. req.load = function (context, moduleName, url) {
  1612. var config = (context && context.config) || {},
  1613. node;
  1614. if (isBrowser) {
  1615. //In the browser so use a script tag
  1616. node = req.createNode(config, moduleName, url);
  1617. node.setAttribute('data-requirecontext', context.contextName);
  1618. node.setAttribute('data-requiremodule', moduleName);
  1619. //Set up load listener. Test attachEvent first because IE9 has
  1620. //a subtle issue in its addEventListener and script onload firings
  1621. //that do not match the behavior of all other browsers with
  1622. //addEventListener support, which fire the onload event for a
  1623. //script right after the script execution. See:
  1624. //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
  1625. //UNFORTUNATELY Opera implements attachEvent but does not follow the script
  1626. //script execution mode.
  1627. if (node.attachEvent &&
  1628. //Check if node.attachEvent is artificially added by custom script or
  1629. //natively supported by browser
  1630. //read https://github.com/jrburke/requirejs/issues/187
  1631. //if we can NOT find [native code] then it must NOT natively supported.
  1632. //in IE8, node.attachEvent does not have toString()
  1633. //Note the test for "[native code" with no closing brace, see:
  1634. //https://github.com/jrburke/requirejs/issues/273
  1635. !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
  1636. !isOpera) {
  1637. //Probably IE. IE (at least 6-8) do not fire
  1638. //script onload right after executing the script, so
  1639. //we cannot tie the anonymous define call to a name.
  1640. //However, IE reports the script as being in 'interactive'
  1641. //readyState at the time of the define call.
  1642. useInteractive = true;
  1643. node.attachEvent('onreadystatechange', context.onScriptLoad);
  1644. //It would be great to add an error handler here to catch
  1645. //404s in IE9+. However, onreadystatechange will fire before
  1646. //the error handler, so that does not help. If addEventListener
  1647. //is used, then IE will fire error before load, but we cannot
  1648. //use that pathway given the connect.microsoft.com issue
  1649. //mentioned above about not doing the 'script execute,
  1650. //then fire the script load event listener before execute
  1651. //next script' that other browsers do.
  1652. //Best hope: IE10 fixes the issues,
  1653. //and then destroys all installs of IE 6-9.
  1654. //node.attachEvent('onerror', context.onScriptError);
  1655. } else {
  1656. node.addEventListener('load', context.onScriptLoad, false);
  1657. node.addEventListener('error', context.onScriptError, false);
  1658. }
  1659. node.src = url;
  1660. //For some cache cases in IE 6-8, the script executes before the end
  1661. //of the appendChild execution, so to tie an anonymous define
  1662. //call to the module name (which is stored on the node), hold on
  1663. //to a reference to this node, but clear after the DOM insertion.
  1664. currentlyAddingScript = node;
  1665. if (baseElement) {
  1666. head.insertBefore(node, baseElement);
  1667. } else {
  1668. head.appendChild(node);
  1669. }
  1670. currentlyAddingScript = null;
  1671. return node;
  1672. } else if (isWebWorker) {
  1673. try {
  1674. //In a web worker, use importScripts. This is not a very
  1675. //efficient use of importScripts, importScripts will block until
  1676. //its script is downloaded and evaluated. However, if web workers
  1677. //are in play, the expectation that a build has been done so that
  1678. //only one script needs to be loaded anyway. This may need to be
  1679. //reevaluated if other use cases become common.
  1680. importScripts(url);
  1681. //Account for anonymous modules
  1682. context.completeLoad(moduleName);
  1683. } catch (e) {
  1684. context.onError(makeError('importscripts',
  1685. 'importScripts failed for ' +
  1686. moduleName + ' at ' + url,
  1687. e,
  1688. [moduleName]));
  1689. }
  1690. }
  1691. };
  1692. function getInteractiveScript() {
  1693. if (interactiveScript && interactiveScript.readyState === 'interactive') {
  1694. return interactiveScript;
  1695. }
  1696. eachReverse(scripts(), function (script) {
  1697. if (script.readyState === 'interactive') {
  1698. return (interactiveScript = script);
  1699. }
  1700. });
  1701. return interactiveScript;
  1702. }
  1703. //Look for a data-main script attribute, which could also adjust the baseUrl.
  1704. if (isBrowser && !cfg.skipDataMain) {
  1705. //Figure out baseUrl. Get it from the script tag with require.js in it.
  1706. eachReverse(scripts(), function (script) {
  1707. //Set the 'head' where we can append children by
  1708. //using the script's parent.
  1709. if (!head) {
  1710. head = script.parentNode;
  1711. }
  1712. //Look for a data-main attribute to set main script for the page
  1713. //to load. If it is there, the path to data main becomes the
  1714. //baseUrl, if it is not already set.
  1715. dataMain = script.getAttribute('data-main');
  1716. if (dataMain) {
  1717. //Preserve dataMain in case it is a path (i.e. contains '?')
  1718. mainScript = dataMain;
  1719. //Set final baseUrl if there is not already an explicit one.
  1720. if (!cfg.baseUrl) {
  1721. //Pull off the directory of data-main for use as the
  1722. //baseUrl.
  1723. src = mainScript.split('/');
  1724. mainScript = src.pop();
  1725. subPath = src.length ? src.join('/') + '/' : './';
  1726. cfg.baseUrl = subPath;
  1727. }
  1728. //Strip off any trailing .js since mainScript is now
  1729. //like a module name.
  1730. mainScript = mainScript.replace(jsSuffixRegExp, '');
  1731. //If mainScript is still a path, fall back to dataMain
  1732. if (req.jsExtRegExp.test(mainScript)) {
  1733. mainScript = dataMain;
  1734. }
  1735. //Put the data-main script in the files to load.
  1736. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
  1737. return true;
  1738. }
  1739. });
  1740. }
  1741. /**
  1742. * The function that handles definitions of modules. Differs from
  1743. * require() in that a string for the module should be the first argument,
  1744. * and the function to execute after dependencies are loaded should
  1745. * return a value to define the module corresponding to the first argument's
  1746. * name.
  1747. */
  1748. define = function (name, deps, callback) {
  1749. var node, context;
  1750. //Allow for anonymous modules
  1751. if (typeof name !== 'string') {
  1752. //Adjust args appropriately
  1753. callback = deps;
  1754. deps = name;
  1755. name = null;
  1756. }
  1757. //This module may not have dependencies
  1758. if (!isArray(deps)) {
  1759. callback = deps;
  1760. deps = null;
  1761. }
  1762. //If no name, and callback is a function, then figure out if it a
  1763. //CommonJS thing with dependencies.
  1764. if (!deps && isFunction(callback)) {
  1765. deps = [];
  1766. //Remove comments from the callback string,
  1767. //look for require calls, and pull them into the dependencies,
  1768. //but only if there are function args.
  1769. if (callback.length) {
  1770. callback
  1771. .toString()
  1772. .replace(commentRegExp, '')
  1773. .replace(cjsRequireRegExp, function (match, dep) {
  1774. deps.push(dep);
  1775. });
  1776. //May be a CommonJS thing even without require calls, but still
  1777. //could use exports, and module. Avoid doing exports and module
  1778. //work though if it just needs require.
  1779. //REQUIRES the function to expect the CommonJS variables in the
  1780. //order listed below.
  1781. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
  1782. }
  1783. }
  1784. //If in IE 6-8 and hit an anonymous define() call, do the interactive
  1785. //work.
  1786. if (useInteractive) {
  1787. node = currentlyAddingScript || getInteractiveScript();
  1788. if (node) {
  1789. if (!name) {
  1790. name = node.getAttribute('data-requiremodule');
  1791. }
  1792. context = contexts[node.getAttribute('data-requirecontext')];
  1793. }
  1794. }
  1795. //Always save off evaluating the def call until the script onload handler.
  1796. //This allows multiple modules to be in a file without prematurely
  1797. //tracing dependencies, and allows for anonymous module support,
  1798. //where the module name is not known until the script onload event
  1799. //occurs. If no context, use the global queue, and get it processed
  1800. //in the onscript load callback.
  1801. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
  1802. };
  1803. define.amd = {
  1804. jQuery: true
  1805. };
  1806. /**
  1807. * Executes the text. Normally just uses eval, but can be modified
  1808. * to use a better, environment-specific call. Only used for transpiling
  1809. * loader plugins, not for plain JS modules.
  1810. * @param {String} text the text to execute/evaluate.
  1811. */
  1812. req.exec = function (text) {
  1813. /*jslint evil: true */
  1814. return eval(text);
  1815. };
  1816. //Set up with config info.
  1817. req(cfg);
  1818. }(this));