require.js 81 KB

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