1
0

require.js 81 KB

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