require.js 79 KB

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