Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

2075 řádky
81KB

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