NoteOnMe博客平台搭建
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.

2144 line
84 KiB

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