require-nomin.js 81 KB

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