[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/lib/requirejs/ -> require.js (source)

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


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1