# lib/goog/base.js

    1// Copyright 2006 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415/**16 * @fileoverview Bootstrap for the Google JS Library (Closure).17 *18 * In uncompiled mode base.js will write out Closure's deps file, unless the19 * global <code>CLOSURE_NO_DEPS</code> is set to true.  This allows projects to20 * include their own deps file(s) from different locations.21 *22 *23 * @provideGoog24 */252627/**28 * @define {boolean} Overridden to true by the compiler when --closure_pass29 *     or --mark_as_compiled is specified.30 */31var COMPILED = false;323334/**35 * Base namespace for the Closure library.  Checks to see goog is already36 * defined in the current scope before assigning to prevent clobbering if37 * base.js is loaded more than once.38 *39 * @const40 */41var goog = goog || {};424344/**45 * Reference to the global context.  In most cases this will be 'window'.46 */47goog.global = this;484950/**51 * A hook for overriding the define values in uncompiled mode.52 *53 * In uncompiled mode, {@code CLOSURE_UNCOMPILED_DEFINES} may be defined before54 * loading base.js.  If a key is defined in {@code CLOSURE_UNCOMPILED_DEFINES},55 * {@code goog.define} will use the value instead of the default value.  This56 * allows flags to be overwritten without compilation (this is normally57 * accomplished with the compiler's "define" flag).58 *59 * Example:60 * <pre>61 *   var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};62 * </pre>63 *64 * @type {Object.<string, (string|number|boolean)>|undefined}65 */66goog.global.CLOSURE_UNCOMPILED_DEFINES;676869/**70 * A hook for overriding the define values in uncompiled or compiled mode,71 * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code.  In72 * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.73 *74 * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or75 * string literals or the compiler will emit an error.76 *77 * While any @define value may be set, only those set with goog.define will be78 * effective for uncompiled code.79 *80 * Example:81 * <pre>82 *   var CLOSURE_DEFINES = {'goog.DEBUG': false};83 * </pre>84 *85 * @type {Object.<string, (string|number|boolean)>|undefined}86 */87goog.global.CLOSURE_DEFINES;888990/**91 * Returns true if the specified value is not undefined.92 * WARNING: Do not use this to test if an object has a property. Use the in93 * operator instead.94 *95 * @param {?} val Variable to test.96 * @return {boolean} Whether variable is defined.97 */98goog.isDef = function(val) {99  // void 0 always evaluates to undefined and hence we do not need to depend on100  // the definition of the global variable named 'undefined'.101  return val !== void 0;102};103104105/**106 * Builds an object structure for the provided namespace path, ensuring that107 * names that already exist are not overwritten. For example:108 * "a.b.c" -> a = {};a.b={};a.b.c={};109 * Used by goog.provide and goog.exportSymbol.110 * @param {string} name name of the object that this file defines.111 * @param {*=} opt_object the object to expose at the end of the path.112 * @param {Object=} opt_objectToExportTo The object to add the path to; default113 *     is |goog.global|.114 * @private115 */116goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {117  var parts = name.split('.');118  var cur = opt_objectToExportTo || goog.global;119120  // Internet Explorer exhibits strange behavior when throwing errors from121  // methods externed in this manner.  See the testExportSymbolExceptions in122  // base_test.html for an example.123  if (!(parts[0] in cur) && cur.execScript) {124    cur.execScript('var ' + parts[0]);125  }126127  // Certain browsers cannot parse code in the form for((a in b); c;);128  // This pattern is produced by the JSCompiler when it collapses the129  // statement above into the conditional loop below. To prevent this from130  // happening, use a for-loop and reserve the init logic as below.131132  // Parentheses added to eliminate strict JS warning in Firefox.133  for (var part; parts.length && (part = parts.shift());) {134    if (!parts.length && goog.isDef(opt_object)) {135      // last part and we have an object; use it136      cur[part] = opt_object;137    } else if (cur[part]) {138      cur = cur[part];139    } else {140      cur = cur[part] = {};141    }142  }143};144145146/**147 * Defines a named value. In uncompiled mode, the value is retreived from148 * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and149 * has the property specified, and otherwise used the defined defaultValue.150 * When compiled, the default can be overridden using compiler command-line151 * options.152 *153 * @param {string} name The distinguished name to provide.154 * @param {string|number|boolean} defaultValue155 */156goog.define = function(name, defaultValue) {157  var value = defaultValue;158  if (!COMPILED) {159    if (goog.global.CLOSURE_UNCOMPILED_DEFINES &&160        Object.prototype.hasOwnProperty.call(161            goog.global.CLOSURE_UNCOMPILED_DEFINES, name)) {162      value = goog.global.CLOSURE_UNCOMPILED_DEFINES[name];163    } else if (goog.global.CLOSURE_DEFINES &&164        Object.prototype.hasOwnProperty.call(165            goog.global.CLOSURE_DEFINES, name)) {166      value = goog.global.CLOSURE_DEFINES[name];167    }168  }169  goog.exportPath_(name, value);170};171172173/**174 * @define {boolean} DEBUG is provided as a convenience so that debugging code175 * that should not be included in a production js_binary can be easily stripped176 * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most177 * toString() methods should be declared inside an "if (goog.DEBUG)" conditional178 * because they are generally used for debugging purposes and it is difficult179 * for the JSCompiler to statically determine whether they are used.180 */181goog.DEBUG = true;182183184/**185 * @define {string} LOCALE defines the locale being used for compilation. It is186 * used to select locale specific data to be compiled in js binary. BUILD rule187 * can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler188 * option.189 *190 * Take into account that the locale code format is important. You should use191 * the canonical Unicode format with hyphen as a delimiter. Language must be192 * lowercase, Language Script - Capitalized, Region - UPPERCASE.193 * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.194 *195 * See more info about locale codes here:196 * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers197 *198 * For language codes you should use values defined by ISO 693-1. See it here199 * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from200 * this rule: the Hebrew language. For legacy reasons the old code (iw) should201 * be used instead of the new code (he), see http://wiki/Main/IIISynonyms.202 */203goog.define('goog.LOCALE', 'en');  // default to en204205206/**207 * @define {boolean} Whether this code is running on trusted sites.208 *209 * On untrusted sites, several native functions can be defined or overridden by210 * external libraries like Prototype, Datejs, and JQuery and setting this flag211 * to false forces closure to use its own implementations when possible.212 *213 * If your JavaScript can be loaded by a third party site and you are wary about214 * relying on non-standard implementations, specify215 * "--define goog.TRUSTED_SITE=false" to the JSCompiler.216 */217goog.define('goog.TRUSTED_SITE', true);218219220/**221 * @define {boolean} Whether a project is expected to be running in strict mode.222 *223 * This define can be used to trigger alternate implementations compatible with224 * running in EcmaScript Strict mode or warn about unavailable functionality.225 * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode226 */227goog.define('goog.STRICT_MODE_COMPATIBLE', false);228229230/**231 * Creates object stubs for a namespace.  The presence of one or more232 * goog.provide() calls indicate that the file defines the given233 * objects/namespaces.  Provided objects must not be null or undefined.234 * Build tools also scan for provide/require statements235 * to discern dependencies, build dependency files (see deps.js), etc.236 * @see goog.require237 * @param {string} name Namespace provided by this file in the form238 *     "goog.package.part".239 */240goog.provide = function(name) {241  if (!COMPILED) {242    // Ensure that the same namespace isn't provided twice.243    // A goog.module/goog.provide maps a goog.require to a specific file244    if (goog.isProvided_(name)) {245      throw Error('Namespace "' + name + '" already declared.');246    }247    delete goog.implicitNamespaces_[name];248249    var namespace = name;250    while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {251      if (goog.getObjectByName(namespace)) {252        break;253      }254      goog.implicitNamespaces_[namespace] = true;255    }256  }257258  goog.exportPath_(name);259};260261262/**263 * goog.module serves two purposes:264 * - marks a file that must be loaded as a module265 * - reserves a namespace (it can not also be goog.provided)266 * and has three requirements:267 * - goog.module may not be used in the same file as goog.provide.268 * - goog.module must be the first statement in the file.269 * - only one goog.module is allowed per file.270 * When a goog.module annotated file is loaded, it is loaded enclosed in271 * a strict function closure. This means that:272 * - any variable declared in a goog.module file are private to the file,273 * not global. Although the compiler is expected to inline the module.274 * - The code must obey all the rules of "strict" JavaScript.275 * - the file will be marked as "use strict"276 *277 * NOTE: unlike goog.provide, goog.module does not declare any symbols by278 * itself.279 *280 * @param {string} name Namespace provided by this file in the form281 *     "goog.package.part", is expected but not required.282 */283goog.module = function(name) {284  if (!goog.isString(name) || !name) {285    throw Error('Invalid module identifier');286  }287  if (!goog.isInModuleLoader_()) {288    throw Error('Module ' + name + ' has been loaded incorrectly.');289  }290  if (goog.moduleLoaderState_.moduleName) {291    throw Error('goog.module may only be called once per module.');292  }293294  // Store the module name for the loader.295  goog.moduleLoaderState_.moduleName = name;296  if (!COMPILED) {297    // Ensure that the same namespace isn't provided twice.298    // A goog.module/goog.provide maps a goog.require to a specific file299    if (goog.isProvided_(name)) {300      throw Error('Namespace "' + name + '" already declared.');301    }302    delete goog.implicitNamespaces_[name];303  }304};305306307/** @private {{308 *     moduleName:(string|undefined),309 *     exportTestMethods:boolean}|null}}310 */311goog.moduleLoaderState_ = null;312313314/**315 * @private316 * @return {boolean} Whether a goog.module is currently being initialized.317 */318goog.isInModuleLoader_ = function() {319  return goog.moduleLoaderState_ != null;320};321322323/**324 * Indicate that a module's exports that are known test methods should325 * be copied to the global object.  This makes the test methods visible to326 * test runners that inspect the global object.327 *328 * TODO(johnlenz): Make the test framework aware of goog.module so329 * that this isn't necessary. Alternately combine this with goog.setTestOnly330 * to minimize boiler plate.331 */332goog.module.exportTestMethods = function() {333  if (!goog.isInModuleLoader_()) {334    throw new Error('goog.module.exportTestMethods must be called from ' +335        'within a goog.module');336  }337  goog.moduleLoaderState_.exportTestMethods = true;338};339340341/**342 * Marks that the current file should only be used for testing, and never for343 * live code in production.344 *345 * In the case of unit tests, the message may optionally be an exact namespace346 * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra347 * provide (if not explicitly defined in the code).348 *349 * @param {string=} opt_message Optional message to add to the error that's350 *     raised when used in production code.351 */352goog.setTestOnly = function(opt_message) {353  if (COMPILED && !goog.DEBUG) {354    opt_message = opt_message || '';355    throw Error('Importing test-only code into non-debug environment' +356                (opt_message ? ': ' + opt_message : '.'));357  }358};359360361/**362 * Forward declares a symbol. This is an indication to the compiler that the363 * symbol may be used in the source yet is not required and may not be provided364 * in compilation.365 *366 * The most common usage of forward declaration is code that takes a type as a367 * function parameter but does not need to require it. By forward declaring368 * instead of requiring, no hard dependency is made, and (if not required369 * elsewhere) the namespace may never be required and thus, not be pulled370 * into the JavaScript binary. If it is required elsewhere, it will be type371 * checked as normal.372 *373 *374 * @param {string} name The namespace to forward declare in the form of375 *     "goog.package.part".376 */377goog.forwardDeclare = function(name) {};378379380if (!COMPILED) {381382  /**383   * Check if the given name has been goog.provided. This will return false for384   * names that are available only as implicit namespaces.385   * @param {string} name name of the object to look for.386   * @return {boolean} Whether the name has been provided.387   * @private388   */389  goog.isProvided_ = function(name) {390    return (name in goog.loadedModules_) ||391        (!goog.implicitNamespaces_[name] &&392            goog.isDefAndNotNull(goog.getObjectByName(name)));393  };394395  /**396   * Namespaces implicitly defined by goog.provide. For example,397   * goog.provide('goog.events.Event') implicitly declares that 'goog' and398   * 'goog.events' must be namespaces.399   *400   * @type {Object.<string, (boolean|undefined)>}401   * @private402   */403  goog.implicitNamespaces_ = {'goog.module': true};404405  // NOTE: We add goog.module as an implicit namespace as goog.module is defined406  // here and because the existing module package has not been moved yet out of407  // the goog.module namespace. This satisifies both the debug loader and408  // ahead-of-time dependency management.409}410411412/**413 * Returns an object based on its fully qualified external name.  The object414 * is not found if null or undefined.  If you are using a compilation pass that415 * renames property names beware that using this function will not find renamed416 * properties.417 *418 * @param {string} name The fully qualified name.419 * @param {Object=} opt_obj The object within which to look; default is420 *     |goog.global|.421 * @return {?} The value (object or primitive) or, if not found, null.422 */423goog.getObjectByName = function(name, opt_obj) {424  var parts = name.split('.');425  var cur = opt_obj || goog.global;426  for (var part; part = parts.shift(); ) {427    if (goog.isDefAndNotNull(cur[part])) {428      cur = cur[part];429    } else {430      return null;431    }432  }433  return cur;434};435436437/**438 * Globalizes a whole namespace, such as goog or goog.lang.439 *440 * @param {Object} obj The namespace to globalize.441 * @param {Object=} opt_global The object to add the properties to.442 * @deprecated Properties may be explicitly exported to the global scope, but443 *     this should no longer be done in bulk.444 */445goog.globalize = function(obj, opt_global) {446  var global = opt_global || goog.global;447  for (var x in obj) {448    global[x] = obj[x];449  }450};451452453/**454 * Adds a dependency from a file to the files it requires.455 * @param {string} relPath The path to the js file.456 * @param {Array} provides An array of strings with the names of the objects457 *                         this file provides.458 * @param {Array} requires An array of strings with the names of the objects459 *                         this file requires.460 * @param {boolean=} opt_isModule Whether this dependency must be loaded as461 *     a module as declared by goog.module.462 */463goog.addDependency = function(relPath, provides, requires, opt_isModule) {464  if (goog.DEPENDENCIES_ENABLED) {465    var provide, require;466    var path = relPath.replace(/\\/g, '/');467    var deps = goog.dependencies_;468    for (var i = 0; provide = provides[i]; i++) {469      deps.nameToPath[provide] = path;470      deps.pathIsModule[path] = !!opt_isModule;471    }472    for (var j = 0; require = requires[j]; j++) {473      if (!(path in deps.requires)) {474        deps.requires[path] = {};475      }476      deps.requires[path][require] = true;477    }478  }479};480481482483484// NOTE(nnaze): The debug DOM loader was included in base.js as an original way485// to do "debug-mode" development.  The dependency system can sometimes be486// confusing, as can the debug DOM loader's asynchronous nature.487//488// With the DOM loader, a call to goog.require() is not blocking -- the script489// will not load until some point after the current script.  If a namespace is490// needed at runtime, it needs to be defined in a previous script, or loaded via491// require() with its registered dependencies.492// User-defined namespaces may need their own deps file.  See http://go/js_deps,493// http://go/genjsdeps, or, externally, DepsWriter.494// https://developers.google.com/closure/library/docs/depswriter495//496// Because of legacy clients, the DOM loader can't be easily removed from497// base.js.  Work is being done to make it disableable or replaceable for498// different environments (DOM-less JavaScript interpreters like Rhino or V8,499// for example). See bootstrap/ for more information.500501502/**503 * @define {boolean} Whether to enable the debug loader.504 *505 * If enabled, a call to goog.require() will attempt to load the namespace by506 * appending a script tag to the DOM (if the namespace has been registered).507 *508 * If disabled, goog.require() will simply assert that the namespace has been509 * provided (and depend on the fact that some outside tool correctly ordered510 * the script).511 */512goog.define('goog.ENABLE_DEBUG_LOADER', true);513514515/**516 * @param {string} msg517 * @private518 */519goog.logToConsole_ = function(msg) {520  if (goog.global.console) {521    goog.global.console['error'](msg);522  }523};524525526/**527 * Implements a system for the dynamic resolution of dependencies that works in528 * parallel with the BUILD system. Note that all calls to goog.require will be529 * stripped by the JSCompiler when the --closure_pass option is used.530 * @see goog.provide531 * @param {string} name Namespace to include (as was given in goog.provide()) in532 *     the form "goog.package.part".533 * @return {?} If called within a goog.module file, the associated namespace or534 *     module otherwise null.535 */536goog.require = function(name) {537538  // If the object already exists we do not need do do anything.539  if (!COMPILED) {540    if (goog.isProvided_(name)) {541      if (goog.isInModuleLoader_()) {542        // goog.require only return a value with-in goog.module files.543        return name in goog.loadedModules_ ?544            goog.loadedModules_[name] :545            goog.getObjectByName(name);546      } else {547        return null;548      }549    }550551    if (goog.ENABLE_DEBUG_LOADER) {552      var path = goog.getPathFromDeps_(name);553      if (path) {554        goog.included_[path] = true;555        goog.writeScripts_();556        return null;557      }558    }559560    var errorMessage = 'goog.require could not find: ' + name;561    goog.logToConsole_(errorMessage);562563    throw Error(errorMessage);564  }565};566567568/**569 * Path for included scripts.570 * @type {string}571 */572goog.basePath = '';573574575/**576 * A hook for overriding the base path.577 * @type {string|undefined}578 */579goog.global.CLOSURE_BASE_PATH;580581582/**583 * Whether to write out Closure's deps file. By default, the deps are written.584 * @type {boolean|undefined}585 */586goog.global.CLOSURE_NO_DEPS;587588589/**590 * A function to import a single script. This is meant to be overridden when591 * Closure is being run in non-HTML contexts, such as web workers. It's defined592 * in the global scope so that it can be set before base.js is loaded, which593 * allows deps.js to be imported properly.594 *595 * The function is passed the script source, which is a relative URI. It should596 * return true if the script was imported, false otherwise.597 * @type {(function(string): boolean)|undefined}598 */599goog.global.CLOSURE_IMPORT_SCRIPT;600601602/**603 * Null function used for default values of callbacks, etc.604 * @return {void} Nothing.605 */606goog.nullFunction = function() {};607608609/**610 * The identity function. Returns its first argument.611 *612 * @param {*=} opt_returnValue The single value that will be returned.613 * @param {...*} var_args Optional trailing arguments. These are ignored.614 * @return {?} The first argument. We can't know the type -- just pass it along615 *      without type.616 * @deprecated Use goog.functions.identity instead.617 */618goog.identityFunction = function(opt_returnValue, var_args) {619  return opt_returnValue;620};621622623/**624 * When defining a class Foo with an abstract method bar(), you can do:625 * Foo.prototype.bar = goog.abstractMethod626 *627 * Now if a subclass of Foo fails to override bar(), an error will be thrown628 * when bar() is invoked.629 *630 * Note: This does not take the name of the function to override as an argument631 * because that would make it more difficult to obfuscate our JavaScript code.632 *633 * @type {!Function}634 * @throws {Error} when invoked to indicate the method should be overridden.635 */636goog.abstractMethod = function() {637  throw Error('unimplemented abstract method');638};639640641/**642 * Adds a {@code getInstance} static method that always returns the same643 * instance object.644 * @param {!Function} ctor The constructor for the class to add the static645 *     method to.646 */647goog.addSingletonGetter = function(ctor) {648  ctor.getInstance = function() {649    if (ctor.instance_) {650      return ctor.instance_;651    }652    if (goog.DEBUG) {653      // NOTE: JSCompiler can't optimize away Array#push.654      goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;655    }656    return ctor.instance_ = new ctor;657  };658};659660661/**662 * All singleton classes that have been instantiated, for testing. Don't read663 * it directly, use the {@code goog.testing.singleton} module. The compiler664 * removes this variable if unused.665 * @type {!Array.<!Function>}666 * @private667 */668goog.instantiatedSingletons_ = [];669670671/**672 * @define {boolean} Whether to load goog.modules using {@code eval} when using673 * the debug loader.  This provides a better debugging experience as the674 * source is unmodified and can be edited using Chrome Workspaces or675 * similiar.  However in some environments the use of {@code eval} is banned676 * so we provide an alternative.677 */678goog.define('goog.LOAD_MODULE_USING_EVAL', true);679680681/**682 * The registry of initialized modules:683 * the module identifier to module exports map.684 * @private @const {Object.<string, ?>}685 */686goog.loadedModules_ = {};687688689/**690 * True if goog.dependencies_ is available.691 * @const {boolean}692 */693goog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;694695696if (goog.DEPENDENCIES_ENABLED) {697  /**698   * Object used to keep track of urls that have already been added. This record699   * allows the prevention of circular dependencies.700   * @type {Object}701   * @private702   */703  goog.included_ = {};704705706  /**707   * This object is used to keep track of dependencies and other data that is708   * used for loading scripts.709   * @private710   * @type {Object}711   */712  goog.dependencies_ = {713    pathIsModule: {}, // 1 to 1714    nameToPath: {}, // many to 1715    requires: {}, // 1 to many716    // Used when resolving dependencies to prevent us from visiting file twice.717    visited: {},718    written: {} // Used to keep track of script files we have written.719  };720721722  /**723   * Tries to detect whether is in the context of an HTML document.724   * @return {boolean} True if it looks like HTML document.725   * @private726   */727  goog.inHtmlDocument_ = function() {728    var doc = goog.global.document;729    return typeof doc != 'undefined' &&730           'write' in doc;  // XULDocument misses write.731  };732733734  /**735   * Tries to detect the base path of base.js script that bootstraps Closure.736   * @private737   */738  goog.findBasePath_ = function() {739    if (goog.global.CLOSURE_BASE_PATH) {740      goog.basePath = goog.global.CLOSURE_BASE_PATH;741      return;742    } else if (!goog.inHtmlDocument_()) {743      return;744    }745    var doc = goog.global.document;746    var scripts = doc.getElementsByTagName('script');747    // Search backwards since the current script is in almost all cases the one748    // that has base.js.749    for (var i = scripts.length - 1; i >= 0; --i) {750      var src = scripts[i].src;751      var qmark = src.lastIndexOf('?');752      var l = qmark == -1 ? src.length : qmark;753      if (src.substr(l - 7, 7) == 'base.js') {754        goog.basePath = src.substr(0, l - 7);755        return;756      }757    }758  };759760761  /**762   * Imports a script if, and only if, that script hasn't already been imported.763   * (Must be called at execution time)764   * @param {string} src Script source.765   * @param {string=} opt_sourceText The optionally source text to evaluate766   * @private767   */768  goog.importScript_ = function(src, opt_sourceText) {769    var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||770        goog.writeScriptTag_;771    if (importScript(src, opt_sourceText)) {772      goog.dependencies_.written[src] = true;773    }774  };775776777  /** @const @private {boolean} */778  goog.IS_OLD_IE_ = goog.global.document &&779      goog.global.document.all && !goog.global.atob;780781782  /**783   * Given a URL initiate retrieval and execution of the module.784   * @param {string} src Script source URL.785   * @private786   */787  goog.importModule_ = function(src) {788    // In an attempt to keep browsers from timing out loading scripts using789    // synchronous XHRs, put each load in its own script block.790    var bootstrap = 'goog.retrieveAndExecModule_("' + src + '");';791792    if (goog.importScript_('', bootstrap)) {793      goog.dependencies_.written[src] = true;794    }795  };796797798  /** @private {Array.<string>} */799  goog.queuedModules_ = [];800801802  /**803   * Retrieve and execute a module.804   * @param {string} src Script source URL.805   * @private806   */807  goog.retrieveAndExecModule_ = function(src) {808    var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||809        goog.writeScriptTag_;810811    var scriptText = null;812813    var xhr = new goog.global['XMLHttpRequest']();814815    /** @this {Object} */816    xhr.onload = function() {817      scriptText = this.responseText;818    };819    xhr.open('get', src, false);820    xhr.send();821822    scriptText = xhr.responseText;823824    if (scriptText != null) {825      var execModuleScript = goog.wrapModule_(src, scriptText);826      var isOldIE = goog.IS_OLD_IE_;827      if (isOldIE) {828        goog.queuedModules_.push(execModuleScript);829      } else {830        importScript(src, execModuleScript);831      }832      goog.dependencies_.written[src] = true;833    } else {834      throw new Error('load of ' + src + 'failed');835    }836  };837838839  /**840   * Return an appropriate module text. Suitable to insert into841   * a script tag (that is unescaped).842   * @param {string} srcUrl843   * @param {string} scriptText844   * @return {string}845   * @private846   */847  goog.wrapModule_ = function(srcUrl, scriptText) {848    if (!goog.LOAD_MODULE_USING_EVAL || !goog.isDef(goog.global.JSON)) {849      return '' +850          'goog.loadModule(function(exports) {' +851          '"use strict";' +852          scriptText +853          '\n' + // terminate any trailing single line comment.854          ';return exports' +855          '});' +856          '\n//# sourceURL=' + srcUrl + '\n';857    } else {858      return '' +859          'goog.loadModule(' +860          goog.global.JSON.stringify(861              scriptText + '\n//# sourceURL=' + srcUrl + '\n') +862          ');';863    }864  };865866867  /**868   * Load any deferred goog.module loads.869   * @private870   */871  goog.loadQueuedModules_ = function() {872    var count = goog.queuedModules_.length;873    if (count > 0) {874      var queue = goog.queuedModules_;875      goog.queuedModules_ = [];876      for (var i = 0; i < count; i++) {877        var entry = queue[i];878        goog.globalEval(entry);879      }880    }881  };882883884  /**885   * @param {function(?):?|string} moduleDef The module definition.886   */887  goog.loadModule = function(moduleDef) {888    // NOTE: we allow function definitions to be either in the from889    // of a string to eval (which keeps the original source intact) or890    // in a eval forbidden environment (CSP) we allow a function definition891    // which in its body must call {@code goog.module}, and return the exports892    // of the module.893    try {894      goog.moduleLoaderState_ = {895          moduleName: undefined, exportTestMethods: false};896      var exports;897      if (goog.isFunction(moduleDef)) {898        exports = moduleDef.call(goog.global, {});899      } else if (goog.isString(moduleDef)) {900        exports = goog.loadModuleFromSource_.call(goog.global, moduleDef);901      } else {902        throw Error('Invalid module definition');903      }904905      if (Object.seal) {906        Object.seal(exports);907      }908      var moduleName = goog.moduleLoaderState_.moduleName;909      if (!goog.isString(moduleName) || !moduleName) {910        throw Error('Invalid module name \"' + moduleName + '\"');911      }912913      goog.loadedModules_[moduleName] = exports;914      if (goog.moduleLoaderState_.exportTestMethods) {915        for (var entry in exports) {916          if (entry.indexOf('test', 0) === 0 ||917              entry == 'tearDown' ||918              entry == 'setup') {919            goog.global[entry] = exports[entry];920          }921        }922      }923    } finally {924      goog.moduleLoaderState_ = null;925    }926  };927928929  /**930   * @private @const {function(string):?}931   */932  goog.loadModuleFromSource_ = function() {933    // NOTE: we avoid declaring parameters or local variables here to avoid934    // masking globals or leaking values into the module definition.935    'use strict';936    var exports = {};937    eval(arguments[0]);938    return exports;939  };940941942  /**943   * The default implementation of the import function. Writes a script tag to944   * import the script.945   *946   * @param {string} src The script url.947   * @param {string=} opt_sourceText The optionally source text to evaluate948   * @return {boolean} True if the script was imported, false otherwise.949   * @private950   */951  goog.writeScriptTag_ = function(src, opt_sourceText) {952    if (goog.inHtmlDocument_()) {953      var doc = goog.global.document;954955      // If the user tries to require a new symbol after document load,956      // something has gone terribly wrong. Doing a document.write would957      // wipe out the page.958      if (doc.readyState == 'complete') {959        // Certain test frameworks load base.js multiple times, which tries960        // to write deps.js each time. If that happens, just fail silently.961        // These frameworks wipe the page between each load of base.js, so this962        // is OK.963        var isDeps = /\bdeps.js$/.test(src);964        if (isDeps) {965          return false;966        } else {967          throw Error('Cannot write "' + src + '" after document load');968        }969      }970971      var isOldIE = goog.IS_OLD_IE_;972973      if (opt_sourceText === undefined) {974        if (!isOldIE) {975          doc.write(976              '<script type="text/javascript" src="' +977                  src + '"></' + 'script>');978        } else {979          var state = " onreadystatechange='goog.onScriptLoad_(this, " +980              ++goog.lastNonModuleScriptIndex_ + ")' ";981          doc.write(982              '<script type="text/javascript" src="' +983                  src + '"' + state + '></' + 'script>');984        }985      } else {986        doc.write(987            '<script type="text/javascript">' +988            opt_sourceText +989            '</' + 'script>');990      }991      return true;992    } else {993      return false;994    }995  };996997998  /** @private {number} */999  goog.lastNonModuleScriptIndex_ = 0;100010011002  /**1003   * A readystatechange handler for legacy IE1004   * @param {HTMLScriptElement} script1005   * @param {number} scriptIndex1006   * @return {boolean}1007   * @private1008   */1009  goog.onScriptLoad_ = function(script, scriptIndex) {1010    // for now load the modules when we reach the last script,1011    // later allow more inter-mingling.1012    if (script.readyState == 'complete' &&1013        goog.lastNonModuleScriptIndex_ == scriptIndex) {1014      goog.loadQueuedModules_();1015    }1016    return true;1017  };10181019  /**1020   * Resolves dependencies based on the dependencies added using addDependency1021   * and calls importScript_ in the correct order.1022   * @private1023   */1024  goog.writeScripts_ = function() {1025    // The scripts we need to write this time.1026    var scripts = [];1027    var seenScript = {};1028    var deps = goog.dependencies_;10291030    function visitNode(path) {1031      if (path in deps.written) {1032        return;1033      }10341035      // We have already visited this one. We can get here if we have cyclic1036      // dependencies.1037      if (path in deps.visited) {1038        if (!(path in seenScript)) {1039          seenScript[path] = true;1040          scripts.push(path);1041        }1042        return;1043      }10441045      deps.visited[path] = true;10461047      if (path in deps.requires) {1048        for (var requireName in deps.requires[path]) {1049          // If the required name is defined, we assume that it was already1050          // bootstrapped by other means.1051          if (!goog.isProvided_(requireName)) {1052            if (requireName in deps.nameToPath) {1053              visitNode(deps.nameToPath[requireName]);1054            } else {1055              throw Error('Undefined nameToPath for ' + requireName);1056            }1057          }1058        }1059      }10601061      if (!(path in seenScript)) {1062        seenScript[path] = true;1063        scripts.push(path);1064      }1065    }10661067    for (var path in goog.included_) {1068      if (!deps.written[path]) {1069        visitNode(path);1070      }1071    }10721073    // record that we are going to load all these scripts.1074    for (var i = 0; i < scripts.length; i++) {1075      var path = scripts[i];1076      goog.dependencies_.written[path] = true;1077    }10781079    // If a module is loaded synchronously then we need to1080    // clear the current inModuleLoader value, and restore it when we are1081    // done loading the current "requires".1082    var moduleState = goog.moduleLoaderState_;1083    goog.moduleLoaderState_ = null;10841085    var loadingModule = false;1086    for (var i = 0; i < scripts.length; i++) {1087      var path = scripts[i];1088      if (path) {1089        if (!deps.pathIsModule[path]) {1090          goog.importScript_(goog.basePath + path);1091        } else {1092          loadingModule = true;1093          goog.importModule_(goog.basePath + path);1094        }1095      } else {1096        goog.moduleLoaderState_ = moduleState;1097        throw Error('Undefined script input');1098      }1099    }11001101    // restore the current "module loading state"1102    goog.moduleLoaderState_ = moduleState;1103  };110411051106  /**1107   * Looks at the dependency rules and tries to determine the script file that1108   * fulfills a particular rule.1109   * @param {string} rule In the form goog.namespace.Class or project.script.1110   * @return {?string} Url corresponding to the rule, or null.1111   * @private1112   */1113  goog.getPathFromDeps_ = function(rule) {1114    if (rule in goog.dependencies_.nameToPath) {1115      return goog.dependencies_.nameToPath[rule];1116    } else {1117      return null;1118    }1119  };11201121  goog.findBasePath_();11221123  // Allow projects to manage the deps files themselves.1124  if (!goog.global.CLOSURE_NO_DEPS) {1125    goog.importScript_(goog.basePath + 'deps.js');1126  }1127}1128112911301131//==============================================================================1132// Language Enhancements1133//==============================================================================113411351136/**1137 * This is a "fixed" version of the typeof operator.  It differs from the typeof1138 * operator in such a way that null returns 'null' and arrays return 'array'.1139 * @param {*} value The value to get the type of.1140 * @return {string} The name of the type.1141 */1142goog.typeOf = function(value) {1143  var s = typeof value;1144  if (s == 'object') {1145    if (value) {1146      // Check these first, so we can avoid calling Object.prototype.toString if1147      // possible.1148      //1149      // IE improperly marshals tyepof across execution contexts, but a1150      // cross-context object will still return false for "instanceof Object".1151      if (value instanceof Array) {1152        return 'array';1153      } else if (value instanceof Object) {1154        return s;1155      }11561157      // HACK: In order to use an Object prototype method on the arbitrary1158      //   value, the compiler requires the value be cast to type Object,1159      //   even though the ECMA spec explicitly allows it.1160      var className = Object.prototype.toString.call(1161          /** @type {Object} */ (value));1162      // In Firefox 3.6, attempting to access iframe window objects' length1163      // property throws an NS_ERROR_FAILURE, so we need to special-case it1164      // here.1165      if (className == '[object Window]') {1166        return 'object';1167      }11681169      // We cannot always use constructor == Array or instanceof Array because1170      // different frames have different Array objects. In IE6, if the iframe1171      // where the array was created is destroyed, the array loses its1172      // prototype. Then dereferencing val.splice here throws an exception, so1173      // we can't use goog.isFunction. Calling typeof directly returns 'unknown'1174      // so that will work. In this case, this function will return false and1175      // most array functions will still work because the array is still1176      // array-like (supports length and []) even though it has lost its1177      // prototype.1178      // Mark Miller noticed that Object.prototype.toString1179      // allows access to the unforgeable [[Class]] property.1180      //  15.2.4.2 Object.prototype.toString ( )1181      //  When the toString method is called, the following steps are taken:1182      //      1. Get the [[Class]] property of this object.1183      //      2. Compute a string value by concatenating the three strings1184      //         "[object ", Result(1), and "]".1185      //      3. Return Result(2).1186      // and this behavior survives the destruction of the execution context.1187      if ((className == '[object Array]' ||1188           // In IE all non value types are wrapped as objects across window1189           // boundaries (not iframe though) so we have to do object detection1190           // for this edge case.1191           typeof value.length == 'number' &&1192           typeof value.splice != 'undefined' &&1193           typeof value.propertyIsEnumerable != 'undefined' &&1194           !value.propertyIsEnumerable('splice')11951196          )) {1197        return 'array';1198      }1199      // HACK: There is still an array case that fails.1200      //     function ArrayImpostor() {}1201      //     ArrayImpostor.prototype = [];1202      //     var impostor = new ArrayImpostor;1203      // this can be fixed by getting rid of the fast path1204      // (value instanceof Array) and solely relying on1205      // (value && Object.prototype.toString.vall(value) === '[object Array]')1206      // but that would require many more function calls and is not warranted1207      // unless closure code is receiving objects from untrusted sources.12081209      // IE in cross-window calls does not correctly marshal the function type1210      // (it appears just as an object) so we cannot use just typeof val ==1211      // 'function'. However, if the object has a call property, it is a1212      // function.1213      if ((className == '[object Function]' ||1214          typeof value.call != 'undefined' &&1215          typeof value.propertyIsEnumerable != 'undefined' &&1216          !value.propertyIsEnumerable('call'))) {1217        return 'function';1218      }12191220    } else {1221      return 'null';1222    }12231224  } else if (s == 'function' && typeof value.call == 'undefined') {1225    // In Safari typeof nodeList returns 'function', and on Firefox typeof1226    // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We1227    // would like to return object for those and we can detect an invalid1228    // function by making sure that the function object has a call method.1229    return 'object';1230  }1231  return s;1232};123312341235/**1236 * Returns true if the specified value is null.1237 * @param {?} val Variable to test.1238 * @return {boolean} Whether variable is null.1239 */1240goog.isNull = function(val) {1241  return val === null;1242};124312441245/**1246 * Returns true if the specified value is defined and not null.1247 * @param {?} val Variable to test.1248 * @return {boolean} Whether variable is defined and not null.1249 */1250goog.isDefAndNotNull = function(val) {1251  // Note that undefined == null.1252  return val != null;1253};125412551256/**1257 * Returns true if the specified value is an array.1258 * @param {?} val Variable to test.1259 * @return {boolean} Whether variable is an array.1260 */1261goog.isArray = function(val) {1262  return goog.typeOf(val) == 'array';1263};126412651266/**1267 * Returns true if the object looks like an array. To qualify as array like1268 * the value needs to be either a NodeList or an object with a Number length1269 * property.1270 * @param {?} val Variable to test.1271 * @return {boolean} Whether variable is an array.1272 */1273goog.isArrayLike = function(val) {1274  var type = goog.typeOf(val);1275  return type == 'array' || type == 'object' && typeof val.length == 'number';1276};127712781279/**1280 * Returns true if the object looks like a Date. To qualify as Date-like the1281 * value needs to be an object and have a getFullYear() function.1282 * @param {?} val Variable to test.1283 * @return {boolean} Whether variable is a like a Date.1284 */1285goog.isDateLike = function(val) {1286  return goog.isObject(val) && typeof val.getFullYear == 'function';1287};128812891290/**1291 * Returns true if the specified value is a string.1292 * @param {?} val Variable to test.1293 * @return {boolean} Whether variable is a string.1294 */1295goog.isString = function(val) {1296  return typeof val == 'string';1297};129812991300/**1301 * Returns true if the specified value is a boolean.1302 * @param {?} val Variable to test.1303 * @return {boolean} Whether variable is boolean.1304 */1305goog.isBoolean = function(val) {1306  return typeof val == 'boolean';1307};130813091310/**1311 * Returns true if the specified value is a number.1312 * @param {?} val Variable to test.1313 * @return {boolean} Whether variable is a number.1314 */1315goog.isNumber = function(val) {1316  return typeof val == 'number';1317};131813191320/**1321 * Returns true if the specified value is a function.1322 * @param {?} val Variable to test.1323 * @return {boolean} Whether variable is a function.1324 */1325goog.isFunction = function(val) {1326  return goog.typeOf(val) == 'function';1327};132813291330/**1331 * Returns true if the specified value is an object.  This includes arrays and1332 * functions.1333 * @param {?} val Variable to test.1334 * @return {boolean} Whether variable is an object.1335 */1336goog.isObject = function(val) {1337  var type = typeof val;1338  return type == 'object' && val != null || type == 'function';1339  // return Object(val) === val also works, but is slower, especially if val is1340  // not an object.1341};134213431344/**1345 * Gets a unique ID for an object. This mutates the object so that further calls1346 * with the same object as a parameter returns the same value. The unique ID is1347 * guaranteed to be unique across the current session amongst objects that are1348 * passed into {@code getUid}. There is no guarantee that the ID is unique or1349 * consistent across sessions. It is unsafe to generate unique ID for function1350 * prototypes.1351 *1352 * @param {Object} obj The object to get the unique ID for.1353 * @return {number} The unique ID for the object.1354 */1355goog.getUid = function(obj) {1356  // TODO(arv): Make the type stricter, do not accept null.13571358  // In Opera window.hasOwnProperty exists but always returns false so we avoid1359  // using it. As a consequence the unique ID generated for BaseClass.prototype1360  // and SubClass.prototype will be the same.1361  return obj[goog.UID_PROPERTY_] ||1362      (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);1363};136413651366/**1367 * Whether the given object is alreay assigned a unique ID.1368 *1369 * This does not modify the object.1370 *1371 * @param {Object} obj The object to check.1372 * @return {boolean} Whether there an assigned unique id for the object.1373 */1374goog.hasUid = function(obj) {1375  return !!obj[goog.UID_PROPERTY_];1376};137713781379/**1380 * Removes the unique ID from an object. This is useful if the object was1381 * previously mutated using {@code goog.getUid} in which case the mutation is1382 * undone.1383 * @param {Object} obj The object to remove the unique ID field from.1384 */1385goog.removeUid = function(obj) {1386  // TODO(arv): Make the type stricter, do not accept null.13871388  // In IE, DOM nodes are not instances of Object and throw an exception if we1389  // try to delete.  Instead we try to use removeAttribute.1390  if ('removeAttribute' in obj) {1391    obj.removeAttribute(goog.UID_PROPERTY_);1392  }1393  /** @preserveTry */1394  try {1395    delete obj[goog.UID_PROPERTY_];1396  } catch (ex) {1397  }1398};139914001401/**1402 * Name for unique ID property. Initialized in a way to help avoid collisions1403 * with other closure JavaScript on the same page.1404 * @type {string}1405 * @private1406 */1407goog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);140814091410/**1411 * Counter for UID.1412 * @type {number}1413 * @private1414 */1415goog.uidCounter_ = 0;141614171418/**1419 * Adds a hash code field to an object. The hash code is unique for the1420 * given object.1421 * @param {Object} obj The object to get the hash code for.1422 * @return {number} The hash code for the object.1423 * @deprecated Use goog.getUid instead.1424 */1425goog.getHashCode = goog.getUid;142614271428/**1429 * Removes the hash code field from an object.1430 * @param {Object} obj The object to remove the field from.1431 * @deprecated Use goog.removeUid instead.1432 */1433goog.removeHashCode = goog.removeUid;143414351436/**1437 * Clones a value. The input may be an Object, Array, or basic type. Objects and1438 * arrays will be cloned recursively.1439 *1440 * WARNINGS:1441 * <code>goog.cloneObject</code> does not detect reference loops. Objects that1442 * refer to themselves will cause infinite recursion.1443 *1444 * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies1445 * UIDs created by <code>getUid</code> into cloned results.1446 *1447 * @param {*} obj The value to clone.1448 * @return {*} A clone of the input value.1449 * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.1450 */1451goog.cloneObject = function(obj) {1452  var type = goog.typeOf(obj);1453  if (type == 'object' || type == 'array') {1454    if (obj.clone) {1455      return obj.clone();1456    }1457    var clone = type == 'array' ? [] : {};1458    for (var key in obj) {1459      clone[key] = goog.cloneObject(obj[key]);1460    }1461    return clone;1462  }14631464  return obj;1465};146614671468/**1469 * A native implementation of goog.bind.1470 * @param {Function} fn A function to partially apply.1471 * @param {Object|undefined} selfObj Specifies the object which this should1472 *     point to when the function is run.1473 * @param {...*} var_args Additional arguments that are partially applied to the1474 *     function.1475 * @return {!Function} A partially-applied form of the function bind() was1476 *     invoked as a method of.1477 * @private1478 * @suppress {deprecated} The compiler thinks that Function.prototype.bind is1479 *     deprecated because some people have declared a pure-JS version.1480 *     Only the pure-JS version is truly deprecated.1481 */1482goog.bindNative_ = function(fn, selfObj, var_args) {1483  return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));1484};148514861487/**1488 * A pure-JS implementation of goog.bind.1489 * @param {Function} fn A function to partially apply.1490 * @param {Object|undefined} selfObj Specifies the object which this should1491 *     point to when the function is run.1492 * @param {...*} var_args Additional arguments that are partially applied to the1493 *     function.1494 * @return {!Function} A partially-applied form of the function bind() was1495 *     invoked as a method of.1496 * @private1497 */1498goog.bindJs_ = function(fn, selfObj, var_args) {1499  if (!fn) {1500    throw new Error();1501  }15021503  if (arguments.length > 2) {1504    var boundArgs = Array.prototype.slice.call(arguments, 2);1505    return function() {1506      // Prepend the bound arguments to the current arguments.1507      var newArgs = Array.prototype.slice.call(arguments);1508      Array.prototype.unshift.apply(newArgs, boundArgs);1509      return fn.apply(selfObj, newArgs);1510    };15111512  } else {1513    return function() {1514      return fn.apply(selfObj, arguments);1515    };1516  }1517};151815191520/**1521 * Partially applies this function to a particular 'this object' and zero or1522 * more arguments. The result is a new function with some arguments of the first1523 * function pre-filled and the value of this 'pre-specified'.1524 *1525 * Remaining arguments specified at call-time are appended to the pre-specified1526 * ones.1527 *1528 * Also see: {@link #partial}.1529 *1530 * Usage:1531 * <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2');1532 * barMethBound('arg3', 'arg4');</pre>1533 *1534 * @param {?function(this:T, ...)} fn A function to partially apply.1535 * @param {T} selfObj Specifies the object which this should point to when the1536 *     function is run.1537 * @param {...*} var_args Additional arguments that are partially applied to the1538 *     function.1539 * @return {!Function} A partially-applied form of the function bind() was1540 *     invoked as a method of.1541 * @template T1542 * @suppress {deprecated} See above.1543 */1544goog.bind = function(fn, selfObj, var_args) {1545  // TODO(nicksantos): narrow the type signature.1546  if (Function.prototype.bind &&1547      // NOTE(nicksantos): Somebody pulled base.js into the default Chrome1548      // extension environment. This means that for Chrome extensions, they get1549      // the implementation of Function.prototype.bind that calls goog.bind1550      // instead of the native one. Even worse, we don't want to introduce a1551      // circular dependency between goog.bind and Function.prototype.bind, so1552      // we have to hack this to make sure it works correctly.1553      Function.prototype.bind.toString().indexOf('native code') != -1) {1554    goog.bind = goog.bindNative_;1555  } else {1556    goog.bind = goog.bindJs_;1557  }1558  return goog.bind.apply(null, arguments);1559};156015611562/**1563 * Like bind(), except that a 'this object' is not required. Useful when the1564 * target function is already bound.1565 *1566 * Usage:1567 * var g = partial(f, arg1, arg2);1568 * g(arg3, arg4);1569 *1570 * @param {Function} fn A function to partially apply.1571 * @param {...*} var_args Additional arguments that are partially applied to fn.1572 * @return {!Function} A partially-applied form of the function bind() was1573 *     invoked as a method of.1574 */1575goog.partial = function(fn, var_args) {1576  var args = Array.prototype.slice.call(arguments, 1);1577  return function() {1578    // Clone the array (with slice()) and append additional arguments1579    // to the existing arguments.1580    var newArgs = args.slice();1581    newArgs.push.apply(newArgs, arguments);1582    return fn.apply(this, newArgs);1583  };1584};158515861587/**1588 * Copies all the members of a source object to a target object. This method1589 * does not work on all browsers for all objects that contain keys such as1590 * toString or hasOwnProperty. Use goog.object.extend for this purpose.1591 * @param {Object} target Target.1592 * @param {Object} source Source.1593 */1594goog.mixin = function(target, source) {1595  for (var x in source) {1596    target[x] = source[x];1597  }15981599  // For IE7 or lower, the for-in-loop does not contain any properties that are1600  // not enumerable on the prototype object (for example, isPrototypeOf from1601  // Object.prototype) but also it will not include 'replace' on objects that1602  // extend String and change 'replace' (not that it is common for anyone to1603  // extend anything except Object).1604};160516061607/**1608 * @return {number} An integer value representing the number of milliseconds1609 *     between midnight, January 1, 1970 and the current time.1610 */1611goog.now = (goog.TRUSTED_SITE && Date.now) || (function() {1612  // Unary plus operator converts its operand to a number which in the case of1613  // a date is done by calling getTime().1614  return +new Date();1615});161616171618/**1619 * Evals JavaScript in the global scope.  In IE this uses execScript, other1620 * browsers use goog.global.eval. If goog.global.eval does not evaluate in the1621 * global scope (for example, in Safari), appends a script tag instead.1622 * Throws an exception if neither execScript or eval is defined.1623 * @param {string} script JavaScript string.1624 */1625goog.globalEval = function(script) {1626  if (goog.global.execScript) {1627    goog.global.execScript(script, 'JavaScript');1628  } else if (goog.global.eval) {1629    // Test to see if eval works1630    if (goog.evalWorksForGlobals_ == null) {1631      goog.global.eval('var _et_ = 1;');1632      if (typeof goog.global['_et_'] != 'undefined') {1633        delete goog.global['_et_'];1634        goog.evalWorksForGlobals_ = true;1635      } else {1636        goog.evalWorksForGlobals_ = false;1637      }1638    }16391640    if (goog.evalWorksForGlobals_) {1641      goog.global.eval(script);1642    } else {1643      var doc = goog.global.document;1644      var scriptElt = doc.createElement('script');1645      scriptElt.type = 'text/javascript';1646      scriptElt.defer = false;1647      // Note(user): can't use .innerHTML since "t('<test>')" will fail and1648      // .text doesn't work in Safari 2.  Therefore we append a text node.1649      scriptElt.appendChild(doc.createTextNode(script));1650      doc.body.appendChild(scriptElt);1651      doc.body.removeChild(scriptElt);1652    }1653  } else {1654    throw Error('goog.globalEval not available');1655  }1656};165716581659/**1660 * Indicates whether or not we can call 'eval' directly to eval code in the1661 * global scope. Set to a Boolean by the first call to goog.globalEval (which1662 * empirically tests whether eval works for globals). @see goog.globalEval1663 * @type {?boolean}1664 * @private1665 */1666goog.evalWorksForGlobals_ = null;166716681669/**1670 * Optional map of CSS class names to obfuscated names used with1671 * goog.getCssName().1672 * @type {Object|undefined}1673 * @private1674 * @see goog.setCssNameMapping1675 */1676goog.cssNameMapping_;167716781679/**1680 * Optional obfuscation style for CSS class names. Should be set to either1681 * 'BY_WHOLE' or 'BY_PART' if defined.1682 * @type {string|undefined}1683 * @private1684 * @see goog.setCssNameMapping1685 */1686goog.cssNameMappingStyle_;168716881689/**1690 * Handles strings that are intended to be used as CSS class names.1691 *1692 * This function works in tandem with @see goog.setCssNameMapping.1693 *1694 * Without any mapping set, the arguments are simple joined with a hyphen and1695 * passed through unaltered.1696 *1697 * When there is a mapping, there are two possible styles in which these1698 * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)1699 * of the passed in css name is rewritten according to the map. In the BY_WHOLE1700 * style, the full css name is looked up in the map directly. If a rewrite is1701 * not specified by the map, the compiler will output a warning.1702 *1703 * When the mapping is passed to the compiler, it will replace calls to1704 * goog.getCssName with the strings from the mapping, e.g.1705 *     var x = goog.getCssName('foo');1706 *     var y = goog.getCssName(this.baseClass, 'active');1707 *  becomes:1708 *     var x= 'foo';1709 *     var y = this.baseClass + '-active';1710 *1711 * If one argument is passed it will be processed, if two are passed only the1712 * modifier will be processed, as it is assumed the first argument was generated1713 * as a result of calling goog.getCssName.1714 *1715 * @param {string} className The class name.1716 * @param {string=} opt_modifier A modifier to be appended to the class name.1717 * @return {string} The class name or the concatenation of the class name and1718 *     the modifier.1719 */1720goog.getCssName = function(className, opt_modifier) {1721  var getMapping = function(cssName) {1722    return goog.cssNameMapping_[cssName] || cssName;1723  };17241725  var renameByParts = function(cssName) {1726    // Remap all the parts individually.1727    var parts = cssName.split('-');1728    var mapped = [];1729    for (var i = 0; i < parts.length; i++) {1730      mapped.push(getMapping(parts[i]));1731    }1732    return mapped.join('-');1733  };17341735  var rename;1736  if (goog.cssNameMapping_) {1737    rename = goog.cssNameMappingStyle_ == 'BY_WHOLE' ?1738        getMapping : renameByParts;1739  } else {1740    rename = function(a) {1741      return a;1742    };1743  }17441745  if (opt_modifier) {1746    return className + '-' + rename(opt_modifier);1747  } else {1748    return rename(className);1749  }1750};175117521753/**1754 * Sets the map to check when returning a value from goog.getCssName(). Example:1755 * <pre>1756 * goog.setCssNameMapping({1757 *   "goog": "a",1758 *   "disabled": "b",1759 * });1760 *1761 * var x = goog.getCssName('goog');1762 * // The following evaluates to: "a a-b".1763 * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')1764 * </pre>1765 * When declared as a map of string literals to string literals, the JSCompiler1766 * will replace all calls to goog.getCssName() using the supplied map if the1767 * --closure_pass flag is set.1768 *1769 * @param {!Object} mapping A map of strings to strings where keys are possible1770 *     arguments to goog.getCssName() and values are the corresponding values1771 *     that should be returned.1772 * @param {string=} opt_style The style of css name mapping. There are two valid1773 *     options: 'BY_PART', and 'BY_WHOLE'.1774 * @see goog.getCssName for a description.1775 */1776goog.setCssNameMapping = function(mapping, opt_style) {1777  goog.cssNameMapping_ = mapping;1778  goog.cssNameMappingStyle_ = opt_style;1779};178017811782/**1783 * To use CSS renaming in compiled mode, one of the input files should have a1784 * call to goog.setCssNameMapping() with an object literal that the JSCompiler1785 * can extract and use to replace all calls to goog.getCssName(). In uncompiled1786 * mode, JavaScript code should be loaded before this base.js file that declares1787 * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is1788 * to ensure that the mapping is loaded before any calls to goog.getCssName()1789 * are made in uncompiled mode.1790 *1791 * A hook for overriding the CSS name mapping.1792 * @type {Object|undefined}1793 */1794goog.global.CLOSURE_CSS_NAME_MAPPING;179517961797if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {1798  // This does not call goog.setCssNameMapping() because the JSCompiler1799  // requires that goog.setCssNameMapping() be called with an object literal.1800  goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;1801}180218031804/**1805 * Gets a localized message.1806 *1807 * This function is a compiler primitive. If you give the compiler a localized1808 * message bundle, it will replace the string at compile-time with a localized1809 * version, and expand goog.getMsg call to a concatenated string.1810 *1811 * Messages must be initialized in the form:1812 * <code>1813 * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});1814 * </code>1815 *1816 * @param {string} str Translatable string, places holders in the form {$foo}.1817 * @param {Object=} opt_values Map of place holder name to value.1818 * @return {string} message with placeholders filled.1819 */1820goog.getMsg = function(str, opt_values) {1821  if (opt_values) {1822    str = str.replace(/\{\$([^}]+)}/g, function(match, key) {1823      return key in opt_values ? opt_values[key] : match;1824    });1825  }1826  return str;1827};182818291830/**1831 * Gets a localized message. If the message does not have a translation, gives a1832 * fallback message.1833 *1834 * This is useful when introducing a new message that has not yet been1835 * translated into all languages.1836 *1837 * This function is a compiler primitive. Must be used in the form:1838 * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>1839 * where MSG_A and MSG_B were initialized with goog.getMsg.1840 *1841 * @param {string} a The preferred message.1842 * @param {string} b The fallback message.1843 * @return {string} The best translated message.1844 */1845goog.getMsgWithFallback = function(a, b) {1846  return a;1847};184818491850/**1851 * Exposes an unobfuscated global namespace path for the given object.1852 * Note that fields of the exported object *will* be obfuscated, unless they are1853 * exported in turn via this function or goog.exportProperty.1854 *1855 * Also handy for making public items that are defined in anonymous closures.1856 *1857 * ex. goog.exportSymbol('public.path.Foo', Foo);1858 *1859 * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);1860 *     public.path.Foo.staticFunction();1861 *1862 * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',1863 *                       Foo.prototype.myMethod);1864 *     new public.path.Foo().myMethod();1865 *1866 * @param {string} publicPath Unobfuscated name to export.1867 * @param {*} object Object the name should point to.1868 * @param {Object=} opt_objectToExportTo The object to add the path to; default1869 *     is goog.global.1870 */1871goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {1872  goog.exportPath_(publicPath, object, opt_objectToExportTo);1873};187418751876/**1877 * Exports a property unobfuscated into the object's namespace.1878 * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);1879 * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);1880 * @param {Object} object Object whose static property is being exported.1881 * @param {string} publicName Unobfuscated name to export.1882 * @param {*} symbol Object the name should point to.1883 */1884goog.exportProperty = function(object, publicName, symbol) {1885  object[publicName] = symbol;1886};188718881889/**1890 * Inherit the prototype methods from one constructor into another.1891 *1892 * Usage:1893 * <pre>1894 * function ParentClass(a, b) { }1895 * ParentClass.prototype.foo = function(a) { };1896 *1897 * function ChildClass(a, b, c) {1898 *   ChildClass.base(this, 'constructor', a, b);1899 * }1900 * goog.inherits(ChildClass, ParentClass);1901 *1902 * var child = new ChildClass('a', 'b', 'see');1903 * child.foo(); // This works.1904 * </pre>1905 *1906 * @param {Function} childCtor Child class.1907 * @param {Function} parentCtor Parent class.1908 */1909goog.inherits = function(childCtor, parentCtor) {1910  /** @constructor */1911  function tempCtor() {};1912  tempCtor.prototype = parentCtor.prototype;1913  childCtor.superClass_ = parentCtor.prototype;1914  childCtor.prototype = new tempCtor();1915  /** @override */1916  childCtor.prototype.constructor = childCtor;19171918  /**1919   * Calls superclass constructor/method.1920   *1921   * This function is only available if you use goog.inherits to1922   * express inheritance relationships between classes.1923   *1924   * NOTE: This is a replacement for goog.base and for superClass_1925   * property defined in childCtor.1926   *1927   * @param {!Object} me Should always be "this".1928   * @param {string} methodName The method name to call. Calling1929   *     superclass constructor can be done with the special string1930   *     'constructor'.1931   * @param {...*} var_args The arguments to pass to superclass1932   *     method/constructor.1933   * @return {*} The return value of the superclass method/constructor.1934   */1935  childCtor.base = function(me, methodName, var_args) {1936    var args = Array.prototype.slice.call(arguments, 2);1937    return parentCtor.prototype[methodName].apply(me, args);1938  };1939};194019411942/**1943 * Call up to the superclass.1944 *1945 * If this is called from a constructor, then this calls the superclass1946 * constructor with arguments 1-N.1947 *1948 * If this is called from a prototype method, then you must pass the name of the1949 * method as the second argument to this function. If you do not, you will get a1950 * runtime error. This calls the superclass' method with arguments 2-N.1951 *1952 * This function only works if you use goog.inherits to express inheritance1953 * relationships between your classes.1954 *1955 * This function is a compiler primitive. At compile-time, the compiler will do1956 * macro expansion to remove a lot of the extra overhead that this function1957 * introduces. The compiler will also enforce a lot of the assumptions that this1958 * function makes, and treat it as a compiler error if you break them.1959 *1960 * @param {!Object} me Should always be "this".1961 * @param {*=} opt_methodName The method name if calling a super method.1962 * @param {...*} var_args The rest of the arguments.1963 * @return {*} The return value of the superclass method.1964 * @suppress {es5Strict} This method can not be used in strict mode, but1965 *     all Closure Library consumers must depend on this file.1966 */1967goog.base = function(me, opt_methodName, var_args) {1968  var caller = arguments.callee.caller;19691970  if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) {1971    throw Error('arguments.caller not defined.  goog.base() cannot be used ' +1972                'with strict mode code. See ' +1973                'http://www.ecma-international.org/ecma-262/5.1/#sec-C');1974  }19751976  if (caller.superClass_) {1977    // This is a constructor. Call the superclass constructor.1978    return caller.superClass_.constructor.apply(1979        me, Array.prototype.slice.call(arguments, 1));1980  }19811982  var args = Array.prototype.slice.call(arguments, 2);1983  var foundCaller = false;1984  for (var ctor = me.constructor;1985       ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {1986    if (ctor.prototype[opt_methodName] === caller) {1987      foundCaller = true;1988    } else if (foundCaller) {1989      return ctor.prototype[opt_methodName].apply(me, args);1990    }1991  }19921993  // If we did not find the caller in the prototype chain, then one of two1994  // things happened:1995  // 1) The caller is an instance method.1996  // 2) This method was not called by the right caller.1997  if (me[opt_methodName] === caller) {1998    return me.constructor.prototype[opt_methodName].apply(me, args);1999  } else {2000    throw Error(2001        'goog.base called from a method of one name ' +2002        'to a method of a different name');2003  }2004};200520062007/**2008 * Allow for aliasing within scope functions.  This function exists for2009 * uncompiled code - in compiled code the calls will be inlined and the aliases2010 * applied.  In uncompiled code the function is simply run since the aliases as2011 * written are valid JavaScript.2012 *2013 *2014 * @param {function()} fn Function to call.  This function can contain aliases2015 *     to namespaces (e.g. "var dom = goog.dom") or classes2016 *     (e.g. "var Timer = goog.Timer").2017 */2018goog.scope = function(fn) {2019  fn.call(goog.global);2020};202120222023/*2024 * To support uncompiled, strict mode bundles that use eval to divide source2025 * like so:2026 *    eval('someSource;//# sourceUrl sourcefile.js');2027 * We need to export the globally defined symbols "goog" and "COMPILED".2028 * Exporting "goog" breaks the compiler optimizations, so we required that2029 * be defined externally.2030 * NOTE: We don't use goog.exportSymbol here because we don't want to trigger2031 * extern generation when that compiler option is enabled.2032 */2033if (!COMPILED) {2034  goog.global['COMPILED'] = COMPILED;2035}2036203720382039//==============================================================================2040// goog.defineClass implementation2041//==============================================================================20422043/**2044 * Creates a restricted form of a Closure "class":2045 *   - from the compiler's perspective, the instance returned from the2046 *     constructor is sealed (no new properties may be added).  This enables2047 *     better checks.2048 *   - the compiler will rewrite this definition to a form that is optimal2049 *     for type checking and optimization (initially this will be a more2050 *     traditional form).2051 *2052 * @param {Function} superClass The superclass, Object or null.2053 * @param {goog.defineClass.ClassDescriptor} def2054 *     An object literal describing the2055 *     the class.  It may have the following properties:2056 *     "constructor": the constructor function2057 *     "statics": an object literal containing methods to add to the constructor2058 *        as "static" methods or a function that will receive the constructor2059 *        function as its only parameter to which static properties can2060 *        be added.2061 *     all other properties are added to the prototype.2062 * @return {!Function} The class constructor.2063 */2064goog.defineClass = function(superClass, def) {2065  // TODO(johnlenz): consider making the superClass an optional parameter.2066  var constructor = def.constructor;2067  var statics = def.statics;2068  // Wrap the constructor prior to setting up the prototype and static methods.2069  if (!constructor || constructor == Object.prototype.constructor) {2070    constructor = function() {2071      throw Error('cannot instantiate an interface (no constructor defined).');2072    };2073  }20742075  var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);2076  if (superClass) {2077    goog.inherits(cls, superClass);2078  }20792080  // Remove all the properties that should not be copied to the prototype.2081  delete def.constructor;2082  delete def.statics;20832084  goog.defineClass.applyProperties_(cls.prototype, def);2085  if (statics != null) {2086    if (statics instanceof Function) {2087      statics(cls);2088    } else {2089      goog.defineClass.applyProperties_(cls, statics);2090    }2091  }20922093  return cls;2094};209520962097/**2098 * @typedef {2099 *     !Object|2100 *     {constructor:!Function}|2101 *     {constructor:!Function, statics:(Object|function(Function):void)}}2102 */2103goog.defineClass.ClassDescriptor;210421052106/**2107 * @define {boolean} Whether the instances returned by2108 * goog.defineClass should be sealed when possible.2109 */2110goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);211121122113/**2114 * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is2115 * defined, this function will wrap the constructor in a function that seals the2116 * results of the provided constructor function.2117 *2118 * @param {!Function} ctr The constructor whose results maybe be sealed.2119 * @param {Function} superClass The superclass constructor.2120 * @return {!Function} The replacement constructor.2121 * @private2122 */2123goog.defineClass.createSealingConstructor_ = function(ctr, superClass) {2124  if (goog.defineClass.SEAL_CLASS_INSTANCES &&2125      Object.seal instanceof Function) {2126    // Don't seal subclasses of unsealable-tagged legacy classes.2127    if (superClass && superClass.prototype &&2128        superClass.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_]) {2129      return ctr;2130    }2131    /** @this {*} */2132    var wrappedCtr = function() {2133      // Don't seal an instance of a subclass when it calls the constructor of2134      // its super class as there is most likely still setup to do.2135      var instance = ctr.apply(this, arguments) || this;2136      instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];2137      if (this.constructor === wrappedCtr) {2138        Object.seal(instance);2139      }2140      return instance;2141    };2142    return wrappedCtr;2143  }2144  return ctr;2145};214621472148// TODO(johnlenz): share these values with the goog.object2149/**2150 * The names of the fields that are defined on Object.prototype.2151 * @type {!Array.<string>}2152 * @private2153 * @const2154 */2155goog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [2156  'constructor',2157  'hasOwnProperty',2158  'isPrototypeOf',2159  'propertyIsEnumerable',2160  'toLocaleString',2161  'toString',2162  'valueOf'2163];216421652166// TODO(johnlenz): share this function with the goog.object2167/**2168 * @param {!Object} target The object to add properties to.2169 * @param {!Object} source The object to copy properites from.2170 * @private2171 */2172goog.defineClass.applyProperties_ = function(target, source) {2173  // TODO(johnlenz): update this to support ES5 getters/setters21742175  var key;2176  for (key in source) {2177    if (Object.prototype.hasOwnProperty.call(source, key)) {2178      target[key] = source[key];2179    }2180  }21812182  // For IE the for-in-loop does not contain any properties that are not2183  // enumerable on the prototype object (for example isPrototypeOf from2184  // Object.prototype) and it will also not include 'replace' on objects that2185  // extend String and change 'replace' (not that it is common for anyone to2186  // extend anything except Object).2187  for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {2188    key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];2189    if (Object.prototype.hasOwnProperty.call(source, key)) {2190      target[key] = source[key];2191    }2192  }2193};219421952196/**2197 * Sealing classes breaks the older idiom of assigning properties on the2198 * prototype rather than in the constructor.  As such, goog.defineClass2199 * must not seal subclasses of these old-style classes until they are fixed.2200 * Until then, this marks a class as "broken", instructing defineClass2201 * not to seal subclasses.2202 * @param {!Function} ctr The legacy constructor to tag as unsealable.2203 */2204goog.tagUnsealableClass = function(ctr) {2205  if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) {2206    ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true;2207  }2208};220922102211/**2212 * Name for unsealable tag property.2213 * @const @private {string}2214 */2215goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable';