You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2142 lines
84 KiB

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