not really known
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.

2000 lines
78 KiB

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