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 at |
6 | // |
7 | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | // |
9 | // Unless required by applicable law or agreed to in writing, software |
10 | // 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 and |
13 | // limitations under the License. |
14 | |
15 | /** |
16 | * @fileoverview Bootstrap for the Google JS Library (Closure). |
17 | * |
18 | * In uncompiled mode base.js will write out Closure's deps file, unless the |
19 | * global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects to |
20 | * include their own deps file(s) from different locations. |
21 | * |
22 | * |
23 | * @provideGoog |
24 | */ |
25 | |
26 | |
27 | /** |
28 | * @define {boolean} Overridden to true by the compiler when --closure_pass |
29 | * or --mark_as_compiled is specified. |
30 | */ |
31 | var COMPILED = false; |
32 | |
33 | |
34 | /** |
35 | * Base namespace for the Closure library. Checks to see goog is already |
36 | * defined in the current scope before assigning to prevent clobbering if |
37 | * base.js is loaded more than once. |
38 | * |
39 | * @const |
40 | */ |
41 | var goog = goog || {}; |
42 | |
43 | |
44 | /** |
45 | * Reference to the global context. In most cases this will be 'window'. |
46 | */ |
47 | goog.global = this; |
48 | |
49 | |
50 | /** |
51 | * A hook for overriding the define values in uncompiled mode. |
52 | * |
53 | * In uncompiled mode, {@code CLOSURE_UNCOMPILED_DEFINES} may be defined before |
54 | * 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. This |
56 | * allows flags to be overwritten without compilation (this is normally |
57 | * 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 | */ |
66 | goog.global.CLOSURE_UNCOMPILED_DEFINES; |
67 | |
68 | |
69 | /** |
70 | * A hook for overriding the define values in uncompiled or compiled mode, |
71 | * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In |
72 | * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence. |
73 | * |
74 | * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or |
75 | * 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 be |
78 | * 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 | */ |
87 | goog.global.CLOSURE_DEFINES; |
88 | |
89 | |
90 | /** |
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 in |
93 | * operator instead. |
94 | * |
95 | * @param {?} val Variable to test. |
96 | * @return {boolean} Whether variable is defined. |
97 | */ |
98 | goog.isDef = function(val) { |
99 | // void 0 always evaluates to undefined and hence we do not need to depend on |
100 | // the definition of the global variable named 'undefined'. |
101 | return val !== void 0; |
102 | }; |
103 | |
104 | |
105 | /** |
106 | * Builds an object structure for the provided namespace path, ensuring that |
107 | * 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; default |
113 | * is |goog.global|. |
114 | * @private |
115 | */ |
116 | goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) { |
117 | var parts = name.split('.'); |
118 | var cur = opt_objectToExportTo || goog.global; |
119 | |
120 | // Internet Explorer exhibits strange behavior when throwing errors from |
121 | // methods externed in this manner. See the testExportSymbolExceptions in |
122 | // base_test.html for an example. |
123 | if (!(parts[0] in cur) && cur.execScript) { |
124 | cur.execScript('var ' + parts[0]); |
125 | } |
126 | |
127 | // Certain browsers cannot parse code in the form for((a in b); c;); |
128 | // This pattern is produced by the JSCompiler when it collapses the |
129 | // statement above into the conditional loop below. To prevent this from |
130 | // happening, use a for-loop and reserve the init logic as below. |
131 | |
132 | // 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 it |
136 | cur[part] = opt_object; |
137 | } else if (cur[part]) { |
138 | cur = cur[part]; |
139 | } else { |
140 | cur = cur[part] = {}; |
141 | } |
142 | } |
143 | }; |
144 | |
145 | |
146 | /** |
147 | * Defines a named value. In uncompiled mode, the value is retreived from |
148 | * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and |
149 | * has the property specified, and otherwise used the defined defaultValue. |
150 | * When compiled, the default can be overridden using compiler command-line |
151 | * options. |
152 | * |
153 | * @param {string} name The distinguished name to provide. |
154 | * @param {string|number|boolean} defaultValue |
155 | */ |
156 | goog.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 | }; |
171 | |
172 | |
173 | /** |
174 | * @define {boolean} DEBUG is provided as a convenience so that debugging code |
175 | * that should not be included in a production js_binary can be easily stripped |
176 | * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most |
177 | * toString() methods should be declared inside an "if (goog.DEBUG)" conditional |
178 | * because they are generally used for debugging purposes and it is difficult |
179 | * for the JSCompiler to statically determine whether they are used. |
180 | */ |
181 | goog.DEBUG = true; |
182 | |
183 | |
184 | /** |
185 | * @define {string} LOCALE defines the locale being used for compilation. It is |
186 | * used to select locale specific data to be compiled in js binary. BUILD rule |
187 | * can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler |
188 | * option. |
189 | * |
190 | * Take into account that the locale code format is important. You should use |
191 | * the canonical Unicode format with hyphen as a delimiter. Language must be |
192 | * 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_Identifiers |
197 | * |
198 | * For language codes you should use values defined by ISO 693-1. See it here |
199 | * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from |
200 | * this rule: the Hebrew language. For legacy reasons the old code (iw) should |
201 | * be used instead of the new code (he), see http://wiki/Main/IIISynonyms. |
202 | */ |
203 | goog.define('goog.LOCALE', 'en'); // default to en |
204 | |
205 | |
206 | /** |
207 | * @define {boolean} Whether this code is running on trusted sites. |
208 | * |
209 | * On untrusted sites, several native functions can be defined or overridden by |
210 | * external libraries like Prototype, Datejs, and JQuery and setting this flag |
211 | * 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 about |
214 | * relying on non-standard implementations, specify |
215 | * "--define goog.TRUSTED_SITE=false" to the JSCompiler. |
216 | */ |
217 | goog.define('goog.TRUSTED_SITE', true); |
218 | |
219 | |
220 | /** |
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 with |
224 | * 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_mode |
226 | */ |
227 | goog.define('goog.STRICT_MODE_COMPATIBLE', false); |
228 | |
229 | |
230 | /** |
231 | * Creates object stubs for a namespace. The presence of one or more |
232 | * goog.provide() calls indicate that the file defines the given |
233 | * objects/namespaces. Provided objects must not be null or undefined. |
234 | * Build tools also scan for provide/require statements |
235 | * to discern dependencies, build dependency files (see deps.js), etc. |
236 | * @see goog.require |
237 | * @param {string} name Namespace provided by this file in the form |
238 | * "goog.package.part". |
239 | */ |
240 | goog.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 file |
244 | if (goog.isProvided_(name)) { |
245 | throw Error('Namespace "' + name + '" already declared.'); |
246 | } |
247 | delete goog.implicitNamespaces_[name]; |
248 | |
249 | 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 | } |
257 | |
258 | goog.exportPath_(name); |
259 | }; |
260 | |
261 | |
262 | /** |
263 | * goog.module serves two purposes: |
264 | * - marks a file that must be loaded as a module |
265 | * - 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 in |
271 | * 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 by |
278 | * itself. |
279 | * |
280 | * @param {string} name Namespace provided by this file in the form |
281 | * "goog.package.part", is expected but not required. |
282 | */ |
283 | goog.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 | } |
293 | |
294 | // 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 file |
299 | if (goog.isProvided_(name)) { |
300 | throw Error('Namespace "' + name + '" already declared.'); |
301 | } |
302 | delete goog.implicitNamespaces_[name]; |
303 | } |
304 | }; |
305 | |
306 | |
307 | /** @private {{ |
308 | * moduleName:(string|undefined), |
309 | * exportTestMethods:boolean}|null}} |
310 | */ |
311 | goog.moduleLoaderState_ = null; |
312 | |
313 | |
314 | /** |
315 | * @private |
316 | * @return {boolean} Whether a goog.module is currently being initialized. |
317 | */ |
318 | goog.isInModuleLoader_ = function() { |
319 | return goog.moduleLoaderState_ != null; |
320 | }; |
321 | |
322 | |
323 | /** |
324 | * Indicate that a module's exports that are known test methods should |
325 | * be copied to the global object. This makes the test methods visible to |
326 | * test runners that inspect the global object. |
327 | * |
328 | * TODO(johnlenz): Make the test framework aware of goog.module so |
329 | * that this isn't necessary. Alternately combine this with goog.setTestOnly |
330 | * to minimize boiler plate. |
331 | */ |
332 | goog.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 | }; |
339 | |
340 | |
341 | /** |
342 | * Marks that the current file should only be used for testing, and never for |
343 | * live code in production. |
344 | * |
345 | * In the case of unit tests, the message may optionally be an exact namespace |
346 | * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra |
347 | * provide (if not explicitly defined in the code). |
348 | * |
349 | * @param {string=} opt_message Optional message to add to the error that's |
350 | * raised when used in production code. |
351 | */ |
352 | goog.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 | }; |
359 | |
360 | |
361 | /** |
362 | * Forward declares a symbol. This is an indication to the compiler that the |
363 | * symbol may be used in the source yet is not required and may not be provided |
364 | * in compilation. |
365 | * |
366 | * The most common usage of forward declaration is code that takes a type as a |
367 | * function parameter but does not need to require it. By forward declaring |
368 | * instead of requiring, no hard dependency is made, and (if not required |
369 | * elsewhere) the namespace may never be required and thus, not be pulled |
370 | * into the JavaScript binary. If it is required elsewhere, it will be type |
371 | * checked as normal. |
372 | * |
373 | * |
374 | * @param {string} name The namespace to forward declare in the form of |
375 | * "goog.package.part". |
376 | */ |
377 | goog.forwardDeclare = function(name) {}; |
378 | |
379 | |
380 | if (!COMPILED) { |
381 | |
382 | /** |
383 | * Check if the given name has been goog.provided. This will return false for |
384 | * 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 | * @private |
388 | */ |
389 | goog.isProvided_ = function(name) { |
390 | return (name in goog.loadedModules_) || |
391 | (!goog.implicitNamespaces_[name] && |
392 | goog.isDefAndNotNull(goog.getObjectByName(name))); |
393 | }; |
394 | |
395 | /** |
396 | * Namespaces implicitly defined by goog.provide. For example, |
397 | * goog.provide('goog.events.Event') implicitly declares that 'goog' and |
398 | * 'goog.events' must be namespaces. |
399 | * |
400 | * @type {Object.<string, (boolean|undefined)>} |
401 | * @private |
402 | */ |
403 | goog.implicitNamespaces_ = {'goog.module': true}; |
404 | |
405 | // NOTE: We add goog.module as an implicit namespace as goog.module is defined |
406 | // here and because the existing module package has not been moved yet out of |
407 | // the goog.module namespace. This satisifies both the debug loader and |
408 | // ahead-of-time dependency management. |
409 | } |
410 | |
411 | |
412 | /** |
413 | * Returns an object based on its fully qualified external name. The object |
414 | * is not found if null or undefined. If you are using a compilation pass that |
415 | * renames property names beware that using this function will not find renamed |
416 | * properties. |
417 | * |
418 | * @param {string} name The fully qualified name. |
419 | * @param {Object=} opt_obj The object within which to look; default is |
420 | * |goog.global|. |
421 | * @return {?} The value (object or primitive) or, if not found, null. |
422 | */ |
423 | goog.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 | }; |
435 | |
436 | |
437 | /** |
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, but |
443 | * this should no longer be done in bulk. |
444 | */ |
445 | goog.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 | }; |
451 | |
452 | |
453 | /** |
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 objects |
457 | * this file provides. |
458 | * @param {Array} requires An array of strings with the names of the objects |
459 | * this file requires. |
460 | * @param {boolean=} opt_isModule Whether this dependency must be loaded as |
461 | * a module as declared by goog.module. |
462 | */ |
463 | goog.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 | }; |
480 | |
481 | |
482 | |
483 | |
484 | // NOTE(nnaze): The debug DOM loader was included in base.js as an original way |
485 | // to do "debug-mode" development. The dependency system can sometimes be |
486 | // 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 script |
489 | // will not load until some point after the current script. If a namespace is |
490 | // needed at runtime, it needs to be defined in a previous script, or loaded via |
491 | // 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/depswriter |
495 | // |
496 | // Because of legacy clients, the DOM loader can't be easily removed from |
497 | // base.js. Work is being done to make it disableable or replaceable for |
498 | // different environments (DOM-less JavaScript interpreters like Rhino or V8, |
499 | // for example). See bootstrap/ for more information. |
500 | |
501 | |
502 | /** |
503 | * @define {boolean} Whether to enable the debug loader. |
504 | * |
505 | * If enabled, a call to goog.require() will attempt to load the namespace by |
506 | * 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 been |
509 | * provided (and depend on the fact that some outside tool correctly ordered |
510 | * the script). |
511 | */ |
512 | goog.define('goog.ENABLE_DEBUG_LOADER', true); |
513 | |
514 | |
515 | /** |
516 | * @param {string} msg |
517 | * @private |
518 | */ |
519 | goog.logToConsole_ = function(msg) { |
520 | if (goog.global.console) { |
521 | goog.global.console['error'](msg); |
522 | } |
523 | }; |
524 | |
525 | |
526 | /** |
527 | * Implements a system for the dynamic resolution of dependencies that works in |
528 | * parallel with the BUILD system. Note that all calls to goog.require will be |
529 | * stripped by the JSCompiler when the --closure_pass option is used. |
530 | * @see goog.provide |
531 | * @param {string} name Namespace to include (as was given in goog.provide()) in |
532 | * the form "goog.package.part". |
533 | * @return {?} If called within a goog.module file, the associated namespace or |
534 | * module otherwise null. |
535 | */ |
536 | goog.require = function(name) { |
537 | |
538 | // 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 | } |
550 | |
551 | 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 | } |
559 | |
560 | var errorMessage = 'goog.require could not find: ' + name; |
561 | goog.logToConsole_(errorMessage); |
562 | |
563 | throw Error(errorMessage); |
564 | } |
565 | }; |
566 | |
567 | |
568 | /** |
569 | * Path for included scripts. |
570 | * @type {string} |
571 | */ |
572 | goog.basePath = ''; |
573 | |
574 | |
575 | /** |
576 | * A hook for overriding the base path. |
577 | * @type {string|undefined} |
578 | */ |
579 | goog.global.CLOSURE_BASE_PATH; |
580 | |
581 | |
582 | /** |
583 | * Whether to write out Closure's deps file. By default, the deps are written. |
584 | * @type {boolean|undefined} |
585 | */ |
586 | goog.global.CLOSURE_NO_DEPS; |
587 | |
588 | |
589 | /** |
590 | * A function to import a single script. This is meant to be overridden when |
591 | * Closure is being run in non-HTML contexts, such as web workers. It's defined |
592 | * in the global scope so that it can be set before base.js is loaded, which |
593 | * allows deps.js to be imported properly. |
594 | * |
595 | * The function is passed the script source, which is a relative URI. It should |
596 | * return true if the script was imported, false otherwise. |
597 | * @type {(function(string): boolean)|undefined} |
598 | */ |
599 | goog.global.CLOSURE_IMPORT_SCRIPT; |
600 | |
601 | |
602 | /** |
603 | * Null function used for default values of callbacks, etc. |
604 | * @return {void} Nothing. |
605 | */ |
606 | goog.nullFunction = function() {}; |
607 | |
608 | |
609 | /** |
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 along |
615 | * without type. |
616 | * @deprecated Use goog.functions.identity instead. |
617 | */ |
618 | goog.identityFunction = function(opt_returnValue, var_args) { |
619 | return opt_returnValue; |
620 | }; |
621 | |
622 | |
623 | /** |
624 | * When defining a class Foo with an abstract method bar(), you can do: |
625 | * Foo.prototype.bar = goog.abstractMethod |
626 | * |
627 | * Now if a subclass of Foo fails to override bar(), an error will be thrown |
628 | * when bar() is invoked. |
629 | * |
630 | * Note: This does not take the name of the function to override as an argument |
631 | * 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 | */ |
636 | goog.abstractMethod = function() { |
637 | throw Error('unimplemented abstract method'); |
638 | }; |
639 | |
640 | |
641 | /** |
642 | * Adds a {@code getInstance} static method that always returns the same |
643 | * instance object. |
644 | * @param {!Function} ctor The constructor for the class to add the static |
645 | * method to. |
646 | */ |
647 | goog.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 | }; |
659 | |
660 | |
661 | /** |
662 | * All singleton classes that have been instantiated, for testing. Don't read |
663 | * it directly, use the {@code goog.testing.singleton} module. The compiler |
664 | * removes this variable if unused. |
665 | * @type {!Array.<!Function>} |
666 | * @private |
667 | */ |
668 | goog.instantiatedSingletons_ = []; |
669 | |
670 | |
671 | /** |
672 | * @define {boolean} Whether to load goog.modules using {@code eval} when using |
673 | * the debug loader. This provides a better debugging experience as the |
674 | * source is unmodified and can be edited using Chrome Workspaces or |
675 | * similiar. However in some environments the use of {@code eval} is banned |
676 | * so we provide an alternative. |
677 | */ |
678 | goog.define('goog.LOAD_MODULE_USING_EVAL', true); |
679 | |
680 | |
681 | /** |
682 | * The registry of initialized modules: |
683 | * the module identifier to module exports map. |
684 | * @private @const {Object.<string, ?>} |
685 | */ |
686 | goog.loadedModules_ = {}; |
687 | |
688 | |
689 | /** |
690 | * True if goog.dependencies_ is available. |
691 | * @const {boolean} |
692 | */ |
693 | goog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER; |
694 | |
695 | |
696 | if (goog.DEPENDENCIES_ENABLED) { |
697 | /** |
698 | * Object used to keep track of urls that have already been added. This record |
699 | * allows the prevention of circular dependencies. |
700 | * @type {Object} |
701 | * @private |
702 | */ |
703 | goog.included_ = {}; |
704 | |
705 | |
706 | /** |
707 | * This object is used to keep track of dependencies and other data that is |
708 | * used for loading scripts. |
709 | * @private |
710 | * @type {Object} |
711 | */ |
712 | goog.dependencies_ = { |
713 | pathIsModule: {}, // 1 to 1 |
714 | nameToPath: {}, // many to 1 |
715 | requires: {}, // 1 to many |
716 | // 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 | }; |
720 | |
721 | |
722 | /** |
723 | * Tries to detect whether is in the context of an HTML document. |
724 | * @return {boolean} True if it looks like HTML document. |
725 | * @private |
726 | */ |
727 | goog.inHtmlDocument_ = function() { |
728 | var doc = goog.global.document; |
729 | return typeof doc != 'undefined' && |
730 | 'write' in doc; // XULDocument misses write. |
731 | }; |
732 | |
733 | |
734 | /** |
735 | * Tries to detect the base path of base.js script that bootstraps Closure. |
736 | * @private |
737 | */ |
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 one |
748 | // 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 | }; |
759 | |
760 | |
761 | /** |
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 evaluate |
766 | * @private |
767 | */ |
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 | }; |
775 | |
776 | |
777 | /** @const @private {boolean} */ |
778 | goog.IS_OLD_IE_ = goog.global.document && |
779 | goog.global.document.all && !goog.global.atob; |
780 | |
781 | |
782 | /** |
783 | * Given a URL initiate retrieval and execution of the module. |
784 | * @param {string} src Script source URL. |
785 | * @private |
786 | */ |
787 | goog.importModule_ = function(src) { |
788 | // In an attempt to keep browsers from timing out loading scripts using |
789 | // synchronous XHRs, put each load in its own script block. |
790 | var bootstrap = 'goog.retrieveAndExecModule_("' + src + '");'; |
791 | |
792 | if (goog.importScript_('', bootstrap)) { |
793 | goog.dependencies_.written[src] = true; |
794 | } |
795 | }; |
796 | |
797 | |
798 | /** @private {Array.<string>} */ |
799 | goog.queuedModules_ = []; |
800 | |
801 | |
802 | /** |
803 | * Retrieve and execute a module. |
804 | * @param {string} src Script source URL. |
805 | * @private |
806 | */ |
807 | goog.retrieveAndExecModule_ = function(src) { |
808 | var importScript = goog.global.CLOSURE_IMPORT_SCRIPT || |
809 | goog.writeScriptTag_; |
810 | |
811 | var scriptText = null; |
812 | |
813 | var xhr = new goog.global['XMLHttpRequest'](); |
814 | |
815 | /** @this {Object} */ |
816 | xhr.onload = function() { |
817 | scriptText = this.responseText; |
818 | }; |
819 | xhr.open('get', src, false); |
820 | xhr.send(); |
821 | |
822 | scriptText = xhr.responseText; |
823 | |
824 | 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 | }; |
837 | |
838 | |
839 | /** |
840 | * Return an appropriate module text. Suitable to insert into |
841 | * a script tag (that is unescaped). |
842 | * @param {string} srcUrl |
843 | * @param {string} scriptText |
844 | * @return {string} |
845 | * @private |
846 | */ |
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 | }; |
865 | |
866 | |
867 | /** |
868 | * Load any deferred goog.module loads. |
869 | * @private |
870 | */ |
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 | }; |
882 | |
883 | |
884 | /** |
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 from |
889 | // of a string to eval (which keeps the original source intact) or |
890 | // in a eval forbidden environment (CSP) we allow a function definition |
891 | // which in its body must call {@code goog.module}, and return the exports |
892 | // 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 | } |
904 | |
905 | 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 | } |
912 | |
913 | 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 | }; |
927 | |
928 | |
929 | /** |
930 | * @private @const {function(string):?} |
931 | */ |
932 | goog.loadModuleFromSource_ = function() { |
933 | // NOTE: we avoid declaring parameters or local variables here to avoid |
934 | // masking globals or leaking values into the module definition. |
935 | 'use strict'; |
936 | var exports = {}; |
937 | eval(arguments[0]); |
938 | return exports; |
939 | }; |
940 | |
941 | |
942 | /** |
943 | * The default implementation of the import function. Writes a script tag to |
944 | * import the script. |
945 | * |
946 | * @param {string} src The script url. |
947 | * @param {string=} opt_sourceText The optionally source text to evaluate |
948 | * @return {boolean} True if the script was imported, false otherwise. |
949 | * @private |
950 | */ |
951 | goog.writeScriptTag_ = function(src, opt_sourceText) { |
952 | if (goog.inHtmlDocument_()) { |
953 | var doc = goog.global.document; |
954 | |
955 | // If the user tries to require a new symbol after document load, |
956 | // something has gone terribly wrong. Doing a document.write would |
957 | // wipe out the page. |
958 | if (doc.readyState == 'complete') { |
959 | // Certain test frameworks load base.js multiple times, which tries |
960 | // 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 this |
962 | // 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 | } |
970 | |
971 | var isOldIE = goog.IS_OLD_IE_; |
972 | |
973 | 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 | }; |
996 | |
997 | |
998 | /** @private {number} */ |
999 | goog.lastNonModuleScriptIndex_ = 0; |
1000 | |
1001 | |
1002 | /** |
1003 | * A readystatechange handler for legacy IE |
1004 | * @param {HTMLScriptElement} script |
1005 | * @param {number} scriptIndex |
1006 | * @return {boolean} |
1007 | * @private |
1008 | */ |
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 | }; |
1018 | |
1019 | /** |
1020 | * Resolves dependencies based on the dependencies added using addDependency |
1021 | * and calls importScript_ in the correct order. |
1022 | * @private |
1023 | */ |
1024 | goog.writeScripts_ = function() { |
1025 | // The scripts we need to write this time. |
1026 | var scripts = []; |
1027 | var seenScript = {}; |
1028 | var deps = goog.dependencies_; |
1029 | |
1030 | function visitNode(path) { |
1031 | if (path in deps.written) { |
1032 | return; |
1033 | } |
1034 | |
1035 | // We have already visited this one. We can get here if we have cyclic |
1036 | // dependencies. |
1037 | if (path in deps.visited) { |
1038 | if (!(path in seenScript)) { |
1039 | seenScript[path] = true; |
1040 | scripts.push(path); |
1041 | } |
1042 | return; |
1043 | } |
1044 | |
1045 | deps.visited[path] = true; |
1046 | |
1047 | 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 already |
1050 | // 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 | } |
1060 | |
1061 | if (!(path in seenScript)) { |
1062 | seenScript[path] = true; |
1063 | scripts.push(path); |
1064 | } |
1065 | } |
1066 | |
1067 | for (var path in goog.included_) { |
1068 | if (!deps.written[path]) { |
1069 | visitNode(path); |
1070 | } |
1071 | } |
1072 | |
1073 | // 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 | } |
1078 | |
1079 | // If a module is loaded synchronously then we need to |
1080 | // clear the current inModuleLoader value, and restore it when we are |
1081 | // done loading the current "requires". |
1082 | var moduleState = goog.moduleLoaderState_; |
1083 | goog.moduleLoaderState_ = null; |
1084 | |
1085 | 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 | } |
1100 | |
1101 | // restore the current "module loading state" |
1102 | goog.moduleLoaderState_ = moduleState; |
1103 | }; |
1104 | |
1105 | |
1106 | /** |
1107 | * Looks at the dependency rules and tries to determine the script file that |
1108 | * 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 | * @private |
1112 | */ |
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 | }; |
1120 | |
1121 | goog.findBasePath_(); |
1122 | |
1123 | // Allow projects to manage the deps files themselves. |
1124 | if (!goog.global.CLOSURE_NO_DEPS) { |
1125 | goog.importScript_(goog.basePath + 'deps.js'); |
1126 | } |
1127 | } |
1128 | |
1129 | |
1130 | |
1131 | //============================================================================== |
1132 | // Language Enhancements |
1133 | //============================================================================== |
1134 | |
1135 | |
1136 | /** |
1137 | * This is a "fixed" version of the typeof operator. It differs from the typeof |
1138 | * 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 | */ |
1142 | goog.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 if |
1147 | // possible. |
1148 | // |
1149 | // IE improperly marshals tyepof across execution contexts, but a |
1150 | // 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 | } |
1156 | |
1157 | // HACK: In order to use an Object prototype method on the arbitrary |
1158 | // 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' length |
1163 | // property throws an NS_ERROR_FAILURE, so we need to special-case it |
1164 | // here. |
1165 | if (className == '[object Window]') { |
1166 | return 'object'; |
1167 | } |
1168 | |
1169 | // We cannot always use constructor == Array or instanceof Array because |
1170 | // different frames have different Array objects. In IE6, if the iframe |
1171 | // where the array was created is destroyed, the array loses its |
1172 | // prototype. Then dereferencing val.splice here throws an exception, so |
1173 | // we can't use goog.isFunction. Calling typeof directly returns 'unknown' |
1174 | // so that will work. In this case, this function will return false and |
1175 | // most array functions will still work because the array is still |
1176 | // array-like (supports length and []) even though it has lost its |
1177 | // prototype. |
1178 | // Mark Miller noticed that Object.prototype.toString |
1179 | // 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 strings |
1184 | // "[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 window |
1189 | // boundaries (not iframe though) so we have to do object detection |
1190 | // for this edge case. |
1191 | typeof value.length == 'number' && |
1192 | typeof value.splice != 'undefined' && |
1193 | typeof value.propertyIsEnumerable != 'undefined' && |
1194 | !value.propertyIsEnumerable('splice') |
1195 | |
1196 | )) { |
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 path |
1204 | // (value instanceof Array) and solely relying on |
1205 | // (value && Object.prototype.toString.vall(value) === '[object Array]') |
1206 | // but that would require many more function calls and is not warranted |
1207 | // unless closure code is receiving objects from untrusted sources. |
1208 | |
1209 | // IE in cross-window calls does not correctly marshal the function type |
1210 | // (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 a |
1212 | // function. |
1213 | if ((className == '[object Function]' || |
1214 | typeof value.call != 'undefined' && |
1215 | typeof value.propertyIsEnumerable != 'undefined' && |
1216 | !value.propertyIsEnumerable('call'))) { |
1217 | return 'function'; |
1218 | } |
1219 | |
1220 | } else { |
1221 | return 'null'; |
1222 | } |
1223 | |
1224 | } else if (s == 'function' && typeof value.call == 'undefined') { |
1225 | // In Safari typeof nodeList returns 'function', and on Firefox typeof |
1226 | // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We |
1227 | // would like to return object for those and we can detect an invalid |
1228 | // function by making sure that the function object has a call method. |
1229 | return 'object'; |
1230 | } |
1231 | return s; |
1232 | }; |
1233 | |
1234 | |
1235 | /** |
1236 | * Returns true if the specified value is null. |
1237 | * @param {?} val Variable to test. |
1238 | * @return {boolean} Whether variable is null. |
1239 | */ |
1240 | goog.isNull = function(val) { |
1241 | return val === null; |
1242 | }; |
1243 | |
1244 | |
1245 | /** |
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 | */ |
1250 | goog.isDefAndNotNull = function(val) { |
1251 | // Note that undefined == null. |
1252 | return val != null; |
1253 | }; |
1254 | |
1255 | |
1256 | /** |
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 | */ |
1261 | goog.isArray = function(val) { |
1262 | return goog.typeOf(val) == 'array'; |
1263 | }; |
1264 | |
1265 | |
1266 | /** |
1267 | * Returns true if the object looks like an array. To qualify as array like |
1268 | * the value needs to be either a NodeList or an object with a Number length |
1269 | * property. |
1270 | * @param {?} val Variable to test. |
1271 | * @return {boolean} Whether variable is an array. |
1272 | */ |
1273 | goog.isArrayLike = function(val) { |
1274 | var type = goog.typeOf(val); |
1275 | return type == 'array' || type == 'object' && typeof val.length == 'number'; |
1276 | }; |
1277 | |
1278 | |
1279 | /** |
1280 | * Returns true if the object looks like a Date. To qualify as Date-like the |
1281 | * 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 | */ |
1285 | goog.isDateLike = function(val) { |
1286 | return goog.isObject(val) && typeof val.getFullYear == 'function'; |
1287 | }; |
1288 | |
1289 | |
1290 | /** |
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 | */ |
1295 | goog.isString = function(val) { |
1296 | return typeof val == 'string'; |
1297 | }; |
1298 | |
1299 | |
1300 | /** |
1301 | * Returns true if the specified value is a boolean. |
1302 | * @param {?} val Variable to test. |
1303 | * @return {boolean} Whether variable is boolean. |
1304 | */ |
1305 | goog.isBoolean = function(val) { |
1306 | return typeof val == 'boolean'; |
1307 | }; |
1308 | |
1309 | |
1310 | /** |
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 | */ |
1315 | goog.isNumber = function(val) { |
1316 | return typeof val == 'number'; |
1317 | }; |
1318 | |
1319 | |
1320 | /** |
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 | */ |
1325 | goog.isFunction = function(val) { |
1326 | return goog.typeOf(val) == 'function'; |
1327 | }; |
1328 | |
1329 | |
1330 | /** |
1331 | * Returns true if the specified value is an object. This includes arrays and |
1332 | * functions. |
1333 | * @param {?} val Variable to test. |
1334 | * @return {boolean} Whether variable is an object. |
1335 | */ |
1336 | goog.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 is |
1340 | // not an object. |
1341 | }; |
1342 | |
1343 | |
1344 | /** |
1345 | * Gets a unique ID for an object. This mutates the object so that further calls |
1346 | * with the same object as a parameter returns the same value. The unique ID is |
1347 | * guaranteed to be unique across the current session amongst objects that are |
1348 | * passed into {@code getUid}. There is no guarantee that the ID is unique or |
1349 | * consistent across sessions. It is unsafe to generate unique ID for function |
1350 | * prototypes. |
1351 | * |
1352 | * @param {Object} obj The object to get the unique ID for. |
1353 | * @return {number} The unique ID for the object. |
1354 | */ |
1355 | goog.getUid = function(obj) { |
1356 | // TODO(arv): Make the type stricter, do not accept null. |
1357 | |
1358 | // In Opera window.hasOwnProperty exists but always returns false so we avoid |
1359 | // using it. As a consequence the unique ID generated for BaseClass.prototype |
1360 | // and SubClass.prototype will be the same. |
1361 | return obj[goog.UID_PROPERTY_] || |
1362 | (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_); |
1363 | }; |
1364 | |
1365 | |
1366 | /** |
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 | */ |
1374 | goog.hasUid = function(obj) { |
1375 | return !!obj[goog.UID_PROPERTY_]; |
1376 | }; |
1377 | |
1378 | |
1379 | /** |
1380 | * Removes the unique ID from an object. This is useful if the object was |
1381 | * previously mutated using {@code goog.getUid} in which case the mutation is |
1382 | * undone. |
1383 | * @param {Object} obj The object to remove the unique ID field from. |
1384 | */ |
1385 | goog.removeUid = function(obj) { |
1386 | // TODO(arv): Make the type stricter, do not accept null. |
1387 | |
1388 | // In IE, DOM nodes are not instances of Object and throw an exception if we |
1389 | // 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 | }; |
1399 | |
1400 | |
1401 | /** |
1402 | * Name for unique ID property. Initialized in a way to help avoid collisions |
1403 | * with other closure JavaScript on the same page. |
1404 | * @type {string} |
1405 | * @private |
1406 | */ |
1407 | goog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0); |
1408 | |
1409 | |
1410 | /** |
1411 | * Counter for UID. |
1412 | * @type {number} |
1413 | * @private |
1414 | */ |
1415 | goog.uidCounter_ = 0; |
1416 | |
1417 | |
1418 | /** |
1419 | * Adds a hash code field to an object. The hash code is unique for the |
1420 | * 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 | */ |
1425 | goog.getHashCode = goog.getUid; |
1426 | |
1427 | |
1428 | /** |
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 | */ |
1433 | goog.removeHashCode = goog.removeUid; |
1434 | |
1435 | |
1436 | /** |
1437 | * Clones a value. The input may be an Object, Array, or basic type. Objects and |
1438 | * arrays will be cloned recursively. |
1439 | * |
1440 | * WARNINGS: |
1441 | * <code>goog.cloneObject</code> does not detect reference loops. Objects that |
1442 | * refer to themselves will cause infinite recursion. |
1443 | * |
1444 | * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies |
1445 | * 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 | */ |
1451 | goog.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 | } |
1463 | |
1464 | return obj; |
1465 | }; |
1466 | |
1467 | |
1468 | /** |
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 should |
1472 | * point to when the function is run. |
1473 | * @param {...*} var_args Additional arguments that are partially applied to the |
1474 | * function. |
1475 | * @return {!Function} A partially-applied form of the function bind() was |
1476 | * invoked as a method of. |
1477 | * @private |
1478 | * @suppress {deprecated} The compiler thinks that Function.prototype.bind is |
1479 | * deprecated because some people have declared a pure-JS version. |
1480 | * Only the pure-JS version is truly deprecated. |
1481 | */ |
1482 | goog.bindNative_ = function(fn, selfObj, var_args) { |
1483 | return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments)); |
1484 | }; |
1485 | |
1486 | |
1487 | /** |
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 should |
1491 | * point to when the function is run. |
1492 | * @param {...*} var_args Additional arguments that are partially applied to the |
1493 | * function. |
1494 | * @return {!Function} A partially-applied form of the function bind() was |
1495 | * invoked as a method of. |
1496 | * @private |
1497 | */ |
1498 | goog.bindJs_ = function(fn, selfObj, var_args) { |
1499 | if (!fn) { |
1500 | throw new Error(); |
1501 | } |
1502 | |
1503 | 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 | }; |
1511 | |
1512 | } else { |
1513 | return function() { |
1514 | return fn.apply(selfObj, arguments); |
1515 | }; |
1516 | } |
1517 | }; |
1518 | |
1519 | |
1520 | /** |
1521 | * Partially applies this function to a particular 'this object' and zero or |
1522 | * more arguments. The result is a new function with some arguments of the first |
1523 | * function pre-filled and the value of this 'pre-specified'. |
1524 | * |
1525 | * Remaining arguments specified at call-time are appended to the pre-specified |
1526 | * 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 the |
1536 | * function is run. |
1537 | * @param {...*} var_args Additional arguments that are partially applied to the |
1538 | * function. |
1539 | * @return {!Function} A partially-applied form of the function bind() was |
1540 | * invoked as a method of. |
1541 | * @template T |
1542 | * @suppress {deprecated} See above. |
1543 | */ |
1544 | goog.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 Chrome |
1548 | // extension environment. This means that for Chrome extensions, they get |
1549 | // the implementation of Function.prototype.bind that calls goog.bind |
1550 | // instead of the native one. Even worse, we don't want to introduce a |
1551 | // circular dependency between goog.bind and Function.prototype.bind, so |
1552 | // 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 | }; |
1560 | |
1561 | |
1562 | /** |
1563 | * Like bind(), except that a 'this object' is not required. Useful when the |
1564 | * 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() was |
1573 | * invoked as a method of. |
1574 | */ |
1575 | goog.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 arguments |
1579 | // to the existing arguments. |
1580 | var newArgs = args.slice(); |
1581 | newArgs.push.apply(newArgs, arguments); |
1582 | return fn.apply(this, newArgs); |
1583 | }; |
1584 | }; |
1585 | |
1586 | |
1587 | /** |
1588 | * Copies all the members of a source object to a target object. This method |
1589 | * does not work on all browsers for all objects that contain keys such as |
1590 | * toString or hasOwnProperty. Use goog.object.extend for this purpose. |
1591 | * @param {Object} target Target. |
1592 | * @param {Object} source Source. |
1593 | */ |
1594 | goog.mixin = function(target, source) { |
1595 | for (var x in source) { |
1596 | target[x] = source[x]; |
1597 | } |
1598 | |
1599 | // For IE7 or lower, the for-in-loop does not contain any properties that are |
1600 | // not enumerable on the prototype object (for example, isPrototypeOf from |
1601 | // Object.prototype) but also it will not include 'replace' on objects that |
1602 | // extend String and change 'replace' (not that it is common for anyone to |
1603 | // extend anything except Object). |
1604 | }; |
1605 | |
1606 | |
1607 | /** |
1608 | * @return {number} An integer value representing the number of milliseconds |
1609 | * between midnight, January 1, 1970 and the current time. |
1610 | */ |
1611 | goog.now = (goog.TRUSTED_SITE && Date.now) || (function() { |
1612 | // Unary plus operator converts its operand to a number which in the case of |
1613 | // a date is done by calling getTime(). |
1614 | return +new Date(); |
1615 | }); |
1616 | |
1617 | |
1618 | /** |
1619 | * Evals JavaScript in the global scope. In IE this uses execScript, other |
1620 | * browsers use goog.global.eval. If goog.global.eval does not evaluate in the |
1621 | * 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 | */ |
1625 | goog.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 works |
1630 | 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 | } |
1639 | |
1640 | 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 and |
1648 | // .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 | }; |
1657 | |
1658 | |
1659 | /** |
1660 | * Indicates whether or not we can call 'eval' directly to eval code in the |
1661 | * global scope. Set to a Boolean by the first call to goog.globalEval (which |
1662 | * empirically tests whether eval works for globals). @see goog.globalEval |
1663 | * @type {?boolean} |
1664 | * @private |
1665 | */ |
1666 | goog.evalWorksForGlobals_ = null; |
1667 | |
1668 | |
1669 | /** |
1670 | * Optional map of CSS class names to obfuscated names used with |
1671 | * goog.getCssName(). |
1672 | * @type {Object|undefined} |
1673 | * @private |
1674 | * @see goog.setCssNameMapping |
1675 | */ |
1676 | goog.cssNameMapping_; |
1677 | |
1678 | |
1679 | /** |
1680 | * Optional obfuscation style for CSS class names. Should be set to either |
1681 | * 'BY_WHOLE' or 'BY_PART' if defined. |
1682 | * @type {string|undefined} |
1683 | * @private |
1684 | * @see goog.setCssNameMapping |
1685 | */ |
1686 | goog.cssNameMappingStyle_; |
1687 | |
1688 | |
1689 | /** |
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 and |
1695 | * passed through unaltered. |
1696 | * |
1697 | * When there is a mapping, there are two possible styles in which these |
1698 | * 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_WHOLE |
1700 | * style, the full css name is looked up in the map directly. If a rewrite is |
1701 | * 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 to |
1704 | * 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 the |
1712 | * modifier will be processed, as it is assumed the first argument was generated |
1713 | * 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 and |
1718 | * the modifier. |
1719 | */ |
1720 | goog.getCssName = function(className, opt_modifier) { |
1721 | var getMapping = function(cssName) { |
1722 | return goog.cssNameMapping_[cssName] || cssName; |
1723 | }; |
1724 | |
1725 | 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 | }; |
1734 | |
1735 | 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 | } |
1744 | |
1745 | if (opt_modifier) { |
1746 | return className + '-' + rename(opt_modifier); |
1747 | } else { |
1748 | return rename(className); |
1749 | } |
1750 | }; |
1751 | |
1752 | |
1753 | /** |
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 JSCompiler |
1766 | * will replace all calls to goog.getCssName() using the supplied map if the |
1767 | * --closure_pass flag is set. |
1768 | * |
1769 | * @param {!Object} mapping A map of strings to strings where keys are possible |
1770 | * arguments to goog.getCssName() and values are the corresponding values |
1771 | * that should be returned. |
1772 | * @param {string=} opt_style The style of css name mapping. There are two valid |
1773 | * options: 'BY_PART', and 'BY_WHOLE'. |
1774 | * @see goog.getCssName for a description. |
1775 | */ |
1776 | goog.setCssNameMapping = function(mapping, opt_style) { |
1777 | goog.cssNameMapping_ = mapping; |
1778 | goog.cssNameMappingStyle_ = opt_style; |
1779 | }; |
1780 | |
1781 | |
1782 | /** |
1783 | * To use CSS renaming in compiled mode, one of the input files should have a |
1784 | * call to goog.setCssNameMapping() with an object literal that the JSCompiler |
1785 | * can extract and use to replace all calls to goog.getCssName(). In uncompiled |
1786 | * mode, JavaScript code should be loaded before this base.js file that declares |
1787 | * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is |
1788 | * 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 | */ |
1794 | goog.global.CLOSURE_CSS_NAME_MAPPING; |
1795 | |
1796 | |
1797 | if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) { |
1798 | // This does not call goog.setCssNameMapping() because the JSCompiler |
1799 | // requires that goog.setCssNameMapping() be called with an object literal. |
1800 | goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING; |
1801 | } |
1802 | |
1803 | |
1804 | /** |
1805 | * Gets a localized message. |
1806 | * |
1807 | * This function is a compiler primitive. If you give the compiler a localized |
1808 | * message bundle, it will replace the string at compile-time with a localized |
1809 | * 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 | */ |
1820 | goog.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 | }; |
1828 | |
1829 | |
1830 | /** |
1831 | * Gets a localized message. If the message does not have a translation, gives a |
1832 | * fallback message. |
1833 | * |
1834 | * This is useful when introducing a new message that has not yet been |
1835 | * 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 | */ |
1845 | goog.getMsgWithFallback = function(a, b) { |
1846 | return a; |
1847 | }; |
1848 | |
1849 | |
1850 | /** |
1851 | * Exposes an unobfuscated global namespace path for the given object. |
1852 | * Note that fields of the exported object *will* be obfuscated, unless they are |
1853 | * 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; default |
1869 | * is goog.global. |
1870 | */ |
1871 | goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) { |
1872 | goog.exportPath_(publicPath, object, opt_objectToExportTo); |
1873 | }; |
1874 | |
1875 | |
1876 | /** |
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 | */ |
1884 | goog.exportProperty = function(object, publicName, symbol) { |
1885 | object[publicName] = symbol; |
1886 | }; |
1887 | |
1888 | |
1889 | /** |
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 | */ |
1909 | goog.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; |
1917 | |
1918 | /** |
1919 | * Calls superclass constructor/method. |
1920 | * |
1921 | * This function is only available if you use goog.inherits to |
1922 | * 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. Calling |
1929 | * superclass constructor can be done with the special string |
1930 | * 'constructor'. |
1931 | * @param {...*} var_args The arguments to pass to superclass |
1932 | * 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 | }; |
1940 | |
1941 | |
1942 | /** |
1943 | * Call up to the superclass. |
1944 | * |
1945 | * If this is called from a constructor, then this calls the superclass |
1946 | * constructor with arguments 1-N. |
1947 | * |
1948 | * If this is called from a prototype method, then you must pass the name of the |
1949 | * method as the second argument to this function. If you do not, you will get a |
1950 | * runtime error. This calls the superclass' method with arguments 2-N. |
1951 | * |
1952 | * This function only works if you use goog.inherits to express inheritance |
1953 | * relationships between your classes. |
1954 | * |
1955 | * This function is a compiler primitive. At compile-time, the compiler will do |
1956 | * macro expansion to remove a lot of the extra overhead that this function |
1957 | * introduces. The compiler will also enforce a lot of the assumptions that this |
1958 | * 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, but |
1965 | * all Closure Library consumers must depend on this file. |
1966 | */ |
1967 | goog.base = function(me, opt_methodName, var_args) { |
1968 | var caller = arguments.callee.caller; |
1969 | |
1970 | 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 | } |
1975 | |
1976 | 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 | } |
1981 | |
1982 | 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 | } |
1992 | |
1993 | // If we did not find the caller in the prototype chain, then one of two |
1994 | // 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 | }; |
2005 | |
2006 | |
2007 | /** |
2008 | * Allow for aliasing within scope functions. This function exists for |
2009 | * uncompiled code - in compiled code the calls will be inlined and the aliases |
2010 | * applied. In uncompiled code the function is simply run since the aliases as |
2011 | * written are valid JavaScript. |
2012 | * |
2013 | * |
2014 | * @param {function()} fn Function to call. This function can contain aliases |
2015 | * to namespaces (e.g. "var dom = goog.dom") or classes |
2016 | * (e.g. "var Timer = goog.Timer"). |
2017 | */ |
2018 | goog.scope = function(fn) { |
2019 | fn.call(goog.global); |
2020 | }; |
2021 | |
2022 | |
2023 | /* |
2024 | * To support uncompiled, strict mode bundles that use eval to divide source |
2025 | * 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 that |
2029 | * be defined externally. |
2030 | * NOTE: We don't use goog.exportSymbol here because we don't want to trigger |
2031 | * extern generation when that compiler option is enabled. |
2032 | */ |
2033 | if (!COMPILED) { |
2034 | goog.global['COMPILED'] = COMPILED; |
2035 | } |
2036 | |
2037 | |
2038 | |
2039 | //============================================================================== |
2040 | // goog.defineClass implementation |
2041 | //============================================================================== |
2042 | |
2043 | /** |
2044 | * Creates a restricted form of a Closure "class": |
2045 | * - from the compiler's perspective, the instance returned from the |
2046 | * constructor is sealed (no new properties may be added). This enables |
2047 | * better checks. |
2048 | * - the compiler will rewrite this definition to a form that is optimal |
2049 | * for type checking and optimization (initially this will be a more |
2050 | * traditional form). |
2051 | * |
2052 | * @param {Function} superClass The superclass, Object or null. |
2053 | * @param {goog.defineClass.ClassDescriptor} def |
2054 | * An object literal describing the |
2055 | * the class. It may have the following properties: |
2056 | * "constructor": the constructor function |
2057 | * "statics": an object literal containing methods to add to the constructor |
2058 | * as "static" methods or a function that will receive the constructor |
2059 | * function as its only parameter to which static properties can |
2060 | * be added. |
2061 | * all other properties are added to the prototype. |
2062 | * @return {!Function} The class constructor. |
2063 | */ |
2064 | goog.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 | } |
2074 | |
2075 | var cls = goog.defineClass.createSealingConstructor_(constructor, superClass); |
2076 | if (superClass) { |
2077 | goog.inherits(cls, superClass); |
2078 | } |
2079 | |
2080 | // Remove all the properties that should not be copied to the prototype. |
2081 | delete def.constructor; |
2082 | delete def.statics; |
2083 | |
2084 | 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 | } |
2092 | |
2093 | return cls; |
2094 | }; |
2095 | |
2096 | |
2097 | /** |
2098 | * @typedef { |
2099 | * !Object| |
2100 | * {constructor:!Function}| |
2101 | * {constructor:!Function, statics:(Object|function(Function):void)}} |
2102 | */ |
2103 | goog.defineClass.ClassDescriptor; |
2104 | |
2105 | |
2106 | /** |
2107 | * @define {boolean} Whether the instances returned by |
2108 | * goog.defineClass should be sealed when possible. |
2109 | */ |
2110 | goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG); |
2111 | |
2112 | |
2113 | /** |
2114 | * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is |
2115 | * defined, this function will wrap the constructor in a function that seals the |
2116 | * 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 | * @private |
2122 | */ |
2123 | goog.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 of |
2134 | // 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 | }; |
2146 | |
2147 | |
2148 | // TODO(johnlenz): share these values with the goog.object |
2149 | /** |
2150 | * The names of the fields that are defined on Object.prototype. |
2151 | * @type {!Array.<string>} |
2152 | * @private |
2153 | * @const |
2154 | */ |
2155 | goog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [ |
2156 | 'constructor', |
2157 | 'hasOwnProperty', |
2158 | 'isPrototypeOf', |
2159 | 'propertyIsEnumerable', |
2160 | 'toLocaleString', |
2161 | 'toString', |
2162 | 'valueOf' |
2163 | ]; |
2164 | |
2165 | |
2166 | // TODO(johnlenz): share this function with the goog.object |
2167 | /** |
2168 | * @param {!Object} target The object to add properties to. |
2169 | * @param {!Object} source The object to copy properites from. |
2170 | * @private |
2171 | */ |
2172 | goog.defineClass.applyProperties_ = function(target, source) { |
2173 | // TODO(johnlenz): update this to support ES5 getters/setters |
2174 | |
2175 | var key; |
2176 | for (key in source) { |
2177 | if (Object.prototype.hasOwnProperty.call(source, key)) { |
2178 | target[key] = source[key]; |
2179 | } |
2180 | } |
2181 | |
2182 | // For IE the for-in-loop does not contain any properties that are not |
2183 | // enumerable on the prototype object (for example isPrototypeOf from |
2184 | // Object.prototype) and it will also not include 'replace' on objects that |
2185 | // extend String and change 'replace' (not that it is common for anyone to |
2186 | // 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 | }; |
2194 | |
2195 | |
2196 | /** |
2197 | * Sealing classes breaks the older idiom of assigning properties on the |
2198 | * prototype rather than in the constructor. As such, goog.defineClass |
2199 | * must not seal subclasses of these old-style classes until they are fixed. |
2200 | * Until then, this marks a class as "broken", instructing defineClass |
2201 | * not to seal subclasses. |
2202 | * @param {!Function} ctr The legacy constructor to tag as unsealable. |
2203 | */ |
2204 | goog.tagUnsealableClass = function(ctr) { |
2205 | if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) { |
2206 | ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true; |
2207 | } |
2208 | }; |
2209 | |
2210 | |
2211 | /** |
2212 | * Name for unsealable tag property. |
2213 | * @const @private {string} |
2214 | */ |
2215 | goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable'; |