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.
 
 
 

2106 lines
82 KiB

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