base.js 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006
  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. * @fileoverview Bootstrap for the Google JS Library (Closure).
  16. *
  17. * In uncompiled mode base.js will attempt to load Closure's deps file, unless
  18. * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects
  19. * to include their own deps file(s) from different locations.
  20. *
  21. * Avoid including base.js more than once. This is strictly discouraged and not
  22. * supported. goog.require(...) won't work properly in that case.
  23. *
  24. * @provideGoog
  25. */
  26. /**
  27. * @define {boolean} Overridden to true by the compiler.
  28. */
  29. var COMPILED = false;
  30. /**
  31. * Base namespace for the Closure library. Checks to see goog is already
  32. * defined in the current scope before assigning to prevent clobbering if
  33. * base.js is loaded more than once.
  34. *
  35. * @const
  36. */
  37. var goog = goog || {};
  38. /**
  39. * Reference to the global context. In most cases this will be 'window'.
  40. * @const
  41. * @suppress {newCheckTypes}
  42. */
  43. goog.global = this;
  44. /**
  45. * A hook for overriding the define values in uncompiled mode.
  46. *
  47. * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before
  48. * loading base.js. If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`,
  49. * `goog.define` will use the value instead of the default value. This
  50. * allows flags to be overwritten without compilation (this is normally
  51. * accomplished with the compiler's "define" flag).
  52. *
  53. * Example:
  54. * <pre>
  55. * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};
  56. * </pre>
  57. *
  58. * @type {Object<string, (string|number|boolean)>|undefined}
  59. */
  60. goog.global.CLOSURE_UNCOMPILED_DEFINES;
  61. /**
  62. * A hook for overriding the define values in uncompiled or compiled mode,
  63. * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In
  64. * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.
  65. *
  66. * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or
  67. * string literals or the compiler will emit an error.
  68. *
  69. * While any @define value may be set, only those set with goog.define will be
  70. * effective for uncompiled code.
  71. *
  72. * Example:
  73. * <pre>
  74. * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;
  75. * </pre>
  76. *
  77. * @type {Object<string, (string|number|boolean)>|undefined}
  78. */
  79. goog.global.CLOSURE_DEFINES;
  80. /**
  81. * Returns true if the specified value is not undefined.
  82. *
  83. * @param {?} val Variable to test.
  84. * @return {boolean} Whether variable is defined.
  85. */
  86. goog.isDef = function(val) {
  87. // void 0 always evaluates to undefined and hence we do not need to depend on
  88. // the definition of the global variable named 'undefined'.
  89. return val !== void 0;
  90. };
  91. /**
  92. * Returns true if the specified value is a string.
  93. * @param {?} val Variable to test.
  94. * @return {boolean} Whether variable is a string.
  95. */
  96. goog.isString = function(val) {
  97. return typeof val == 'string';
  98. };
  99. /**
  100. * Returns true if the specified value is a boolean.
  101. * @param {?} val Variable to test.
  102. * @return {boolean} Whether variable is boolean.
  103. */
  104. goog.isBoolean = function(val) {
  105. return typeof val == 'boolean';
  106. };
  107. /**
  108. * Returns true if the specified value is a number.
  109. * @param {?} val Variable to test.
  110. * @return {boolean} Whether variable is a number.
  111. */
  112. goog.isNumber = function(val) {
  113. return typeof val == 'number';
  114. };
  115. /**
  116. * Builds an object structure for the provided namespace path, ensuring that
  117. * names that already exist are not overwritten. For example:
  118. * "a.b.c" -> a = {};a.b={};a.b.c={};
  119. * Used by goog.provide and goog.exportSymbol.
  120. * @param {string} name name of the object that this file defines.
  121. * @param {*=} opt_object the object to expose at the end of the path.
  122. * @param {Object=} opt_objectToExportTo The object to add the path to; default
  123. * is `goog.global`.
  124. * @private
  125. */
  126. goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
  127. var parts = name.split('.');
  128. var cur = opt_objectToExportTo || goog.global;
  129. // Internet Explorer exhibits strange behavior when throwing errors from
  130. // methods externed in this manner. See the testExportSymbolExceptions in
  131. // base_test.html for an example.
  132. if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') {
  133. cur.execScript('var ' + parts[0]);
  134. }
  135. for (var part; parts.length && (part = parts.shift());) {
  136. if (!parts.length && goog.isDef(opt_object)) {
  137. // last part and we have an object; use it
  138. cur[part] = opt_object;
  139. } else if (cur[part] && cur[part] !== Object.prototype[part]) {
  140. cur = cur[part];
  141. } else {
  142. cur = cur[part] = {};
  143. }
  144. }
  145. };
  146. /**
  147. * Defines a named value. In uncompiled mode, the value is retrieved 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 the compiler
  151. * options or the value set in the CLOSURE_DEFINES object.
  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. var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES;
  160. var defines = goog.global.CLOSURE_DEFINES;
  161. if (uncompiledDefines &&
  162. // Anti DOM-clobbering runtime check (b/37736576).
  163. /** @type {?} */ (uncompiledDefines).nodeType === undefined &&
  164. Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) {
  165. value = uncompiledDefines[name];
  166. } else if (
  167. defines &&
  168. // Anti DOM-clobbering runtime check (b/37736576).
  169. /** @type {?} */ (defines).nodeType === undefined &&
  170. Object.prototype.hasOwnProperty.call(defines, name)) {
  171. value = defines[name];
  172. }
  173. }
  174. goog.exportPath_(name, value);
  175. };
  176. /**
  177. * @define {boolean} DEBUG is provided as a convenience so that debugging code
  178. * that should not be included in a production. It can be easily stripped
  179. * by specifying --define goog.DEBUG=false to the Closure Compiler aka
  180. * JSCompiler. For example, most toString() methods should be declared inside an
  181. * "if (goog.DEBUG)" conditional because they are generally used for debugging
  182. * purposes and it is difficult for the JSCompiler to statically determine
  183. * whether they are used.
  184. */
  185. goog.define('goog.DEBUG', true);
  186. /**
  187. * @define {string} LOCALE defines the locale being used for compilation. It is
  188. * used to select locale specific data to be compiled in js binary. BUILD rule
  189. * can specify this value by "--define goog.LOCALE=<locale_name>" as a compiler
  190. * option.
  191. *
  192. * Take into account that the locale code format is important. You should use
  193. * the canonical Unicode format with hyphen as a delimiter. Language must be
  194. * lowercase, Language Script - Capitalized, Region - UPPERCASE.
  195. * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.
  196. *
  197. * See more info about locale codes here:
  198. * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers
  199. *
  200. * For language codes you should use values defined by ISO 693-1. See it here
  201. * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from
  202. * this rule: the Hebrew language. For legacy reasons the old code (iw) should
  203. * be used instead of the new code (he).
  204. *
  205. */
  206. goog.define('goog.LOCALE', 'en'); // default to en
  207. /**
  208. * @define {boolean} Whether this code is running on trusted sites.
  209. *
  210. * On untrusted sites, several native functions can be defined or overridden by
  211. * external libraries like Prototype, Datejs, and JQuery and setting this flag
  212. * to false forces closure to use its own implementations when possible.
  213. *
  214. * If your JavaScript can be loaded by a third party site and you are wary about
  215. * relying on non-standard implementations, specify
  216. * "--define goog.TRUSTED_SITE=false" to the compiler.
  217. */
  218. goog.define('goog.TRUSTED_SITE', true);
  219. /**
  220. * @define {boolean} Whether a project is expected to be running in strict mode.
  221. *
  222. * This define can be used to trigger alternate implementations compatible with
  223. * running in EcmaScript Strict mode or warn about unavailable functionality.
  224. * @see https://goo.gl/PudQ4y
  225. *
  226. */
  227. goog.define('goog.STRICT_MODE_COMPATIBLE', false);
  228. /**
  229. * @define {boolean} Whether code that calls {@link goog.setTestOnly} should
  230. * be disallowed in the compilation unit.
  231. */
  232. goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);
  233. /**
  234. * @define {boolean} Whether to use a Chrome app CSP-compliant method for
  235. * loading scripts via goog.require. @see appendScriptSrcNode_.
  236. */
  237. goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);
  238. /**
  239. * Defines a namespace in Closure.
  240. *
  241. * A namespace may only be defined once in a codebase. It may be defined using
  242. * goog.provide() or goog.module().
  243. *
  244. * The presence of one or more goog.provide() calls in a file indicates
  245. * that the file defines the given objects/namespaces.
  246. * Provided symbols must not be null or undefined.
  247. *
  248. * In addition, goog.provide() creates the object stubs for a namespace
  249. * (for example, goog.provide("goog.foo.bar") will create the object
  250. * goog.foo.bar if it does not already exist).
  251. *
  252. * Build tools also scan for provide/require/module statements
  253. * to discern dependencies, build dependency files (see deps.js), etc.
  254. *
  255. * @see goog.require
  256. * @see goog.module
  257. * @param {string} name Namespace provided by this file in the form
  258. * "goog.package.part".
  259. */
  260. goog.provide = function(name) {
  261. if (goog.isInModuleLoader_()) {
  262. throw new Error('goog.provide cannot be used within a module.');
  263. }
  264. if (!COMPILED) {
  265. // Ensure that the same namespace isn't provided twice.
  266. // A goog.module/goog.provide maps a goog.require to a specific file
  267. if (goog.isProvided_(name)) {
  268. throw new Error('Namespace "' + name + '" already declared.');
  269. }
  270. }
  271. goog.constructNamespace_(name);
  272. };
  273. /**
  274. * @param {string} name Namespace provided by this file in the form
  275. * "goog.package.part".
  276. * @param {Object=} opt_obj The object to embed in the namespace.
  277. * @private
  278. */
  279. goog.constructNamespace_ = function(name, opt_obj) {
  280. if (!COMPILED) {
  281. delete goog.implicitNamespaces_[name];
  282. var namespace = name;
  283. while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {
  284. if (goog.getObjectByName(namespace)) {
  285. break;
  286. }
  287. goog.implicitNamespaces_[namespace] = true;
  288. }
  289. }
  290. goog.exportPath_(name, opt_obj);
  291. };
  292. /**
  293. * Returns CSP nonce, if set for any script tag.
  294. * @param {?Window=} opt_window The window context used to retrieve the nonce.
  295. * Defaults to global context.
  296. * @return {string} CSP nonce or empty string if no nonce is present.
  297. */
  298. goog.getScriptNonce = function(opt_window) {
  299. if (opt_window && opt_window != goog.global) {
  300. return goog.getScriptNonce_(opt_window.document);
  301. }
  302. if (goog.cspNonce_ === null) {
  303. goog.cspNonce_ = goog.getScriptNonce_(goog.global.document);
  304. }
  305. return goog.cspNonce_;
  306. };
  307. /**
  308. * According to the CSP3 spec a nonce must be a valid base64 string.
  309. * @see https://www.w3.org/TR/CSP3/#grammardef-base64-value
  310. * @private @const
  311. */
  312. goog.NONCE_PATTERN_ = /^[\w+/_-]+[=]{0,2}$/;
  313. /**
  314. * @private {?string}
  315. */
  316. goog.cspNonce_ = null;
  317. /**
  318. * Returns CSP nonce, if set for any script tag.
  319. * @param {!Document} doc
  320. * @return {string} CSP nonce or empty string if no nonce is present.
  321. * @private
  322. */
  323. goog.getScriptNonce_ = function(doc) {
  324. var script = doc.querySelector && doc.querySelector('script[nonce]');
  325. if (script) {
  326. // Try to get the nonce from the IDL property first, because browsers that
  327. // implement additional nonce protection features (currently only Chrome) to
  328. // prevent nonce stealing via CSS do not expose the nonce via attributes.
  329. // See https://github.com/whatwg/html/issues/2369
  330. var nonce = script['nonce'] || script.getAttribute('nonce');
  331. if (nonce && goog.NONCE_PATTERN_.test(nonce)) {
  332. return nonce;
  333. }
  334. }
  335. return '';
  336. };
  337. /**
  338. * Module identifier validation regexp.
  339. * Note: This is a conservative check, it is very possible to be more lenient,
  340. * the primary exclusion here is "/" and "\" and a leading ".", these
  341. * restrictions are intended to leave the door open for using goog.require
  342. * with relative file paths rather than module identifiers.
  343. * @private
  344. */
  345. goog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;
  346. /**
  347. * Defines a module in Closure.
  348. *
  349. * Marks that this file must be loaded as a module and claims the namespace.
  350. *
  351. * A namespace may only be defined once in a codebase. It may be defined using
  352. * goog.provide() or goog.module().
  353. *
  354. * goog.module() has three requirements:
  355. * - goog.module may not be used in the same file as goog.provide.
  356. * - goog.module must be the first statement in the file.
  357. * - only one goog.module is allowed per file.
  358. *
  359. * When a goog.module annotated file is loaded, it is enclosed in
  360. * a strict function closure. This means that:
  361. * - any variables declared in a goog.module file are private to the file
  362. * (not global), though the compiler is expected to inline the module.
  363. * - The code must obey all the rules of "strict" JavaScript.
  364. * - the file will be marked as "use strict"
  365. *
  366. * NOTE: unlike goog.provide, goog.module does not declare any symbols by
  367. * itself. If declared symbols are desired, use
  368. * goog.module.declareLegacyNamespace().
  369. *
  370. *
  371. * See the public goog.module proposal: http://goo.gl/Va1hin
  372. *
  373. * @param {string} name Namespace provided by this file in the form
  374. * "goog.package.part", is expected but not required.
  375. * @return {void}
  376. */
  377. goog.module = function(name) {
  378. if (!goog.isString(name) || !name ||
  379. name.search(goog.VALID_MODULE_RE_) == -1) {
  380. throw new Error('Invalid module identifier');
  381. }
  382. if (!goog.isInGoogModuleLoader_()) {
  383. throw new Error(
  384. 'Module ' + name + ' has been loaded incorrectly. Note, ' +
  385. 'modules cannot be loaded as normal scripts. They require some kind of ' +
  386. 'pre-processing step. You\'re likely trying to load a module via a ' +
  387. 'script tag or as a part of a concatenated bundle without rewriting the ' +
  388. 'module. For more info see: ' +
  389. 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');
  390. }
  391. if (goog.moduleLoaderState_.moduleName) {
  392. throw new Error('goog.module may only be called once per module.');
  393. }
  394. // Store the module name for the loader.
  395. goog.moduleLoaderState_.moduleName = name;
  396. if (!COMPILED) {
  397. // Ensure that the same namespace isn't provided twice.
  398. // A goog.module/goog.provide maps a goog.require to a specific file
  399. if (goog.isProvided_(name)) {
  400. throw new Error('Namespace "' + name + '" already declared.');
  401. }
  402. delete goog.implicitNamespaces_[name];
  403. }
  404. };
  405. /**
  406. * @param {string} name The module identifier.
  407. * @return {?} The module exports for an already loaded module or null.
  408. *
  409. * Note: This is not an alternative to goog.require, it does not
  410. * indicate a hard dependency, instead it is used to indicate
  411. * an optional dependency or to access the exports of a module
  412. * that has already been loaded.
  413. * @suppress {missingProvide}
  414. */
  415. goog.module.get = function(name) {
  416. return goog.module.getInternal_(name);
  417. };
  418. /**
  419. * @param {string} name The module identifier.
  420. * @return {?} The module exports for an already loaded module or null.
  421. * @private
  422. */
  423. goog.module.getInternal_ = function(name) {
  424. if (!COMPILED) {
  425. if (name in goog.loadedModules_) {
  426. return goog.loadedModules_[name].exports;
  427. } else if (!goog.implicitNamespaces_[name]) {
  428. var ns = goog.getObjectByName(name);
  429. return ns != null ? ns : null;
  430. }
  431. }
  432. return null;
  433. };
  434. /**
  435. * Types of modules the debug loader can load.
  436. * @enum {string}
  437. */
  438. goog.ModuleType = {
  439. ES6: 'es6',
  440. GOOG: 'goog'
  441. };
  442. /**
  443. * @private {?{
  444. * moduleName: (string|undefined),
  445. * declareLegacyNamespace:boolean,
  446. * type: ?goog.ModuleType
  447. * }}
  448. */
  449. goog.moduleLoaderState_ = null;
  450. /**
  451. * @private
  452. * @return {boolean} Whether a goog.module or an es6 module is currently being
  453. * initialized.
  454. */
  455. goog.isInModuleLoader_ = function() {
  456. return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();
  457. };
  458. /**
  459. * @private
  460. * @return {boolean} Whether a goog.module is currently being initialized.
  461. */
  462. goog.isInGoogModuleLoader_ = function() {
  463. return !!goog.moduleLoaderState_ &&
  464. goog.moduleLoaderState_.type == goog.ModuleType.GOOG;
  465. };
  466. /**
  467. * @private
  468. * @return {boolean} Whether an es6 module is currently being initialized.
  469. */
  470. goog.isInEs6ModuleLoader_ = function() {
  471. var inLoader = !!goog.moduleLoaderState_ &&
  472. goog.moduleLoaderState_.type == goog.ModuleType.ES6;
  473. if (inLoader) {
  474. return true;
  475. }
  476. var jscomp = goog.global['$jscomp'];
  477. if (jscomp) {
  478. // jscomp may not have getCurrentModulePath if this is a compiled bundle
  479. // that has some of the runtime, but not all of it. This can happen if
  480. // optimizations are turned on so the unused runtime is removed but renaming
  481. // and Closure pass are off (so $jscomp is still named $jscomp and the
  482. // goog.provide/require calls still exist).
  483. if (typeof jscomp.getCurrentModulePath != 'function') {
  484. return false;
  485. }
  486. // Bundled ES6 module.
  487. return !!jscomp.getCurrentModulePath();
  488. }
  489. return false;
  490. };
  491. /**
  492. * Provide the module's exports as a globally accessible object under the
  493. * module's declared name. This is intended to ease migration to goog.module
  494. * for files that have existing usages.
  495. * @suppress {missingProvide}
  496. */
  497. goog.module.declareLegacyNamespace = function() {
  498. if (!COMPILED && !goog.isInGoogModuleLoader_()) {
  499. throw new Error(
  500. 'goog.module.declareLegacyNamespace must be called from ' +
  501. 'within a goog.module');
  502. }
  503. if (!COMPILED && !goog.moduleLoaderState_.moduleName) {
  504. throw new Error(
  505. 'goog.module must be called prior to ' +
  506. 'goog.module.declareLegacyNamespace.');
  507. }
  508. goog.moduleLoaderState_.declareLegacyNamespace = true;
  509. };
  510. /**
  511. * Associates an ES6 module with a Closure module ID so that is available via
  512. * goog.require. The associated ID acts like a goog.module ID - it does not
  513. * create any global names, it is merely available via goog.require /
  514. * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and
  515. * goog.module.get will return the entire module as if it was import *'d. This
  516. * allows Closure files to reference ES6 modules for the sake of migration.
  517. *
  518. * @param {string} namespace
  519. * @suppress {missingProvide}
  520. */
  521. goog.declareModuleId = function(namespace) {
  522. if (!COMPILED) {
  523. if (!goog.isInEs6ModuleLoader_()) {
  524. throw new Error(
  525. 'goog.declareModuleId may only be called from ' +
  526. 'within an ES6 module');
  527. }
  528. if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {
  529. throw new Error(
  530. 'goog.declareModuleId may only be called once per module.');
  531. }
  532. if (namespace in goog.loadedModules_) {
  533. throw new Error(
  534. 'Module with namespace "' + namespace + '" already exists.');
  535. }
  536. }
  537. if (goog.moduleLoaderState_) {
  538. // Not bundled - debug loading.
  539. goog.moduleLoaderState_.moduleName = namespace;
  540. } else {
  541. // Bundled - not debug loading, no module loader state.
  542. var jscomp = goog.global['$jscomp'];
  543. if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {
  544. throw new Error(
  545. 'Module with namespace "' + namespace +
  546. '" has been loaded incorrectly.');
  547. }
  548. var exports = jscomp.require(jscomp.getCurrentModulePath());
  549. goog.loadedModules_[namespace] = {
  550. exports: exports,
  551. type: goog.ModuleType.ES6,
  552. moduleId: namespace
  553. };
  554. }
  555. };
  556. /**
  557. * Deprecated old name for goog.declareModuleId. This function is being renamed
  558. * to help disambiguate with goog.module.declareLegacyNamespace.
  559. *
  560. * @type {function(string): undefined}
  561. * @suppress {missingProvide}
  562. */
  563. goog.module.declareNamespace = goog.declareModuleId;
  564. /**
  565. * Marks that the current file should only be used for testing, and never for
  566. * live code in production.
  567. *
  568. * In the case of unit tests, the message may optionally be an exact namespace
  569. * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra
  570. * provide (if not explicitly defined in the code).
  571. *
  572. * @param {string=} opt_message Optional message to add to the error that's
  573. * raised when used in production code.
  574. */
  575. goog.setTestOnly = function(opt_message) {
  576. if (goog.DISALLOW_TEST_ONLY_CODE) {
  577. opt_message = opt_message || '';
  578. throw new Error(
  579. 'Importing test-only code into non-debug environment' +
  580. (opt_message ? ': ' + opt_message : '.'));
  581. }
  582. };
  583. /**
  584. * Forward declares a symbol. This is an indication to the compiler that the
  585. * symbol may be used in the source yet is not required and may not be provided
  586. * in compilation.
  587. *
  588. * The most common usage of forward declaration is code that takes a type as a
  589. * function parameter but does not need to require it. By forward declaring
  590. * instead of requiring, no hard dependency is made, and (if not required
  591. * elsewhere) the namespace may never be required and thus, not be pulled
  592. * into the JavaScript binary. If it is required elsewhere, it will be type
  593. * checked as normal.
  594. *
  595. * Before using goog.forwardDeclare, please read the documentation at
  596. * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to
  597. * understand the options and tradeoffs when working with forward declarations.
  598. *
  599. * @param {string} name The namespace to forward declare in the form of
  600. * "goog.package.part".
  601. */
  602. goog.forwardDeclare = function(name) {};
  603. /**
  604. * Forward declare type information. Used to assign types to goog.global
  605. * referenced object that would otherwise result in unknown type references
  606. * and thus block property disambiguation.
  607. */
  608. goog.forwardDeclare('Document');
  609. goog.forwardDeclare('HTMLScriptElement');
  610. goog.forwardDeclare('XMLHttpRequest');
  611. if (!COMPILED) {
  612. /**
  613. * Check if the given name has been goog.provided. This will return false for
  614. * names that are available only as implicit namespaces.
  615. * @param {string} name name of the object to look for.
  616. * @return {boolean} Whether the name has been provided.
  617. * @private
  618. */
  619. goog.isProvided_ = function(name) {
  620. return (name in goog.loadedModules_) ||
  621. (!goog.implicitNamespaces_[name] &&
  622. goog.isDefAndNotNull(goog.getObjectByName(name)));
  623. };
  624. /**
  625. * Namespaces implicitly defined by goog.provide. For example,
  626. * goog.provide('goog.events.Event') implicitly declares that 'goog' and
  627. * 'goog.events' must be namespaces.
  628. *
  629. * @type {!Object<string, (boolean|undefined)>}
  630. * @private
  631. */
  632. goog.implicitNamespaces_ = {'goog.module': true};
  633. // NOTE: We add goog.module as an implicit namespace as goog.module is defined
  634. // here and because the existing module package has not been moved yet out of
  635. // the goog.module namespace. This satisifies both the debug loader and
  636. // ahead-of-time dependency management.
  637. }
  638. /**
  639. * Returns an object based on its fully qualified external name. The object
  640. * is not found if null or undefined. If you are using a compilation pass that
  641. * renames property names beware that using this function will not find renamed
  642. * properties.
  643. *
  644. * @param {string} name The fully qualified name.
  645. * @param {Object=} opt_obj The object within which to look; default is
  646. * |goog.global|.
  647. * @return {?} The value (object or primitive) or, if not found, null.
  648. */
  649. goog.getObjectByName = function(name, opt_obj) {
  650. var parts = name.split('.');
  651. var cur = opt_obj || goog.global;
  652. for (var i = 0; i < parts.length; i++) {
  653. cur = cur[parts[i]];
  654. if (!goog.isDefAndNotNull(cur)) {
  655. return null;
  656. }
  657. }
  658. return cur;
  659. };
  660. /**
  661. * Globalizes a whole namespace, such as goog or goog.lang.
  662. *
  663. * @param {!Object} obj The namespace to globalize.
  664. * @param {Object=} opt_global The object to add the properties to.
  665. * @deprecated Properties may be explicitly exported to the global scope, but
  666. * this should no longer be done in bulk.
  667. */
  668. goog.globalize = function(obj, opt_global) {
  669. var global = opt_global || goog.global;
  670. for (var x in obj) {
  671. global[x] = obj[x];
  672. }
  673. };
  674. /**
  675. * Adds a dependency from a file to the files it requires.
  676. * @param {string} relPath The path to the js file.
  677. * @param {!Array<string>} provides An array of strings with
  678. * the names of the objects this file provides.
  679. * @param {!Array<string>} requires An array of strings with
  680. * the names of the objects this file requires.
  681. * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating
  682. * how the file must be loaded. The boolean 'true' is equivalent
  683. * to {'module': 'goog'} for backwards-compatibility. Valid properties
  684. * and values include {'module': 'goog'} and {'lang': 'es6'}.
  685. */
  686. goog.addDependency = function(relPath, provides, requires, opt_loadFlags) {
  687. if (!COMPILED && goog.DEPENDENCIES_ENABLED) {
  688. goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);
  689. }
  690. };
  691. // NOTE(nnaze): The debug DOM loader was included in base.js as an original way
  692. // to do "debug-mode" development. The dependency system can sometimes be
  693. // confusing, as can the debug DOM loader's asynchronous nature.
  694. //
  695. // With the DOM loader, a call to goog.require() is not blocking -- the script
  696. // will not load until some point after the current script. If a namespace is
  697. // needed at runtime, it needs to be defined in a previous script, or loaded via
  698. // require() with its registered dependencies.
  699. //
  700. // User-defined namespaces may need their own deps file. For a reference on
  701. // creating a deps file, see:
  702. // Externally: https://developers.google.com/closure/library/docs/depswriter
  703. //
  704. // Because of legacy clients, the DOM loader can't be easily removed from
  705. // base.js. Work was done to make it disableable or replaceable for
  706. // different environments (DOM-less JavaScript interpreters like Rhino or V8,
  707. // for example). See bootstrap/ for more information.
  708. /**
  709. * @define {boolean} Whether to enable the debug loader.
  710. *
  711. * If enabled, a call to goog.require() will attempt to load the namespace by
  712. * appending a script tag to the DOM (if the namespace has been registered).
  713. *
  714. * If disabled, goog.require() will simply assert that the namespace has been
  715. * provided (and depend on the fact that some outside tool correctly ordered
  716. * the script).
  717. */
  718. goog.define('goog.ENABLE_DEBUG_LOADER', true);
  719. /**
  720. * @param {string} msg
  721. * @private
  722. */
  723. goog.logToConsole_ = function(msg) {
  724. if (goog.global.console) {
  725. goog.global.console['error'](msg);
  726. }
  727. };
  728. /**
  729. * Implements a system for the dynamic resolution of dependencies that works in
  730. * parallel with the BUILD system.
  731. *
  732. * Note that all calls to goog.require will be stripped by the compiler.
  733. *
  734. * @see goog.provide
  735. * @param {string} namespace Namespace (as was given in goog.provide,
  736. * goog.module, or goog.declareModuleId) in the form
  737. * "goog.package.part".
  738. * @return {?} If called within a goog.module or ES6 module file, the associated
  739. * namespace or module otherwise null.
  740. */
  741. goog.require = function(namespace) {
  742. if (!COMPILED) {
  743. // Might need to lazy load on old IE.
  744. if (goog.ENABLE_DEBUG_LOADER) {
  745. goog.debugLoader_.requested(namespace);
  746. }
  747. // If the object already exists we do not need to do anything.
  748. if (goog.isProvided_(namespace)) {
  749. if (goog.isInModuleLoader_()) {
  750. return goog.module.getInternal_(namespace);
  751. }
  752. } else if (goog.ENABLE_DEBUG_LOADER) {
  753. var moduleLoaderState = goog.moduleLoaderState_;
  754. goog.moduleLoaderState_ = null;
  755. try {
  756. goog.debugLoader_.load_(namespace);
  757. } finally {
  758. goog.moduleLoaderState_ = moduleLoaderState;
  759. }
  760. }
  761. return null;
  762. }
  763. };
  764. /**
  765. * Requires a symbol for its type information. This is an indication to the
  766. * compiler that the symbol may appear in type annotations, yet it is not
  767. * referenced at runtime.
  768. *
  769. * When called within a goog.module or ES6 module file, the return value may be
  770. * assigned to or destructured into a variable, but it may not be otherwise used
  771. * in code outside of a type annotation.
  772. *
  773. * Note that all calls to goog.requireType will be stripped by the compiler.
  774. *
  775. * @param {string} namespace Namespace (as was given in goog.provide,
  776. * goog.module, or goog.declareModuleId) in the form
  777. * "goog.package.part".
  778. * @return {?}
  779. */
  780. goog.requireType = function(namespace) {
  781. // Return an empty object so that single-level destructuring of the return
  782. // value doesn't crash at runtime when using the debug loader. Multi-level
  783. // destructuring isn't supported.
  784. return {};
  785. };
  786. /**
  787. * Path for included scripts.
  788. * @type {string}
  789. */
  790. goog.basePath = '';
  791. /**
  792. * A hook for overriding the base path.
  793. * @type {string|undefined}
  794. */
  795. goog.global.CLOSURE_BASE_PATH;
  796. /**
  797. * Whether to attempt to load Closure's deps file. By default, when uncompiled,
  798. * deps files will attempt to be loaded.
  799. * @type {boolean|undefined}
  800. */
  801. goog.global.CLOSURE_NO_DEPS;
  802. /**
  803. * A function to import a single script. This is meant to be overridden when
  804. * Closure is being run in non-HTML contexts, such as web workers. It's defined
  805. * in the global scope so that it can be set before base.js is loaded, which
  806. * allows deps.js to be imported properly.
  807. *
  808. * The first parameter the script source, which is a relative URI. The second,
  809. * optional parameter is the script contents, in the event the script needed
  810. * transformation. It should return true if the script was imported, false
  811. * otherwise.
  812. * @type {(function(string, string=): boolean)|undefined}
  813. */
  814. goog.global.CLOSURE_IMPORT_SCRIPT;
  815. /**
  816. * Null function used for default values of callbacks, etc.
  817. * @return {void} Nothing.
  818. */
  819. goog.nullFunction = function() {};
  820. /**
  821. * When defining a class Foo with an abstract method bar(), you can do:
  822. * Foo.prototype.bar = goog.abstractMethod
  823. *
  824. * Now if a subclass of Foo fails to override bar(), an error will be thrown
  825. * when bar() is invoked.
  826. *
  827. * @type {!Function}
  828. * @throws {Error} when invoked to indicate the method should be overridden.
  829. */
  830. goog.abstractMethod = function() {
  831. throw new Error('unimplemented abstract method');
  832. };
  833. /**
  834. * Adds a `getInstance` static method that always returns the same
  835. * instance object.
  836. * @param {!Function} ctor The constructor for the class to add the static
  837. * method to.
  838. * @suppress {missingProperties} 'instance_' isn't a property on 'Function'
  839. * but we don't have a better type to use here.
  840. */
  841. goog.addSingletonGetter = function(ctor) {
  842. // instance_ is immediately set to prevent issues with sealed constructors
  843. // such as are encountered when a constructor is returned as the export object
  844. // of a goog.module in unoptimized code.
  845. // Delcare type to avoid conformance violations that ctor.instance_ is unknown
  846. /** @type {undefined|!Object} @suppress {underscore} */
  847. ctor.instance_ = undefined;
  848. ctor.getInstance = function() {
  849. if (ctor.instance_) {
  850. return ctor.instance_;
  851. }
  852. if (goog.DEBUG) {
  853. // NOTE: JSCompiler can't optimize away Array#push.
  854. goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;
  855. }
  856. // Cast to avoid conformance violations that ctor.instance_ is unknown
  857. return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;
  858. };
  859. };
  860. /**
  861. * All singleton classes that have been instantiated, for testing. Don't read
  862. * it directly, use the `goog.testing.singleton` module. The compiler
  863. * removes this variable if unused.
  864. * @type {!Array<!Function>}
  865. * @private
  866. */
  867. goog.instantiatedSingletons_ = [];
  868. /**
  869. * @define {boolean} Whether to load goog.modules using `eval` when using
  870. * the debug loader. This provides a better debugging experience as the
  871. * source is unmodified and can be edited using Chrome Workspaces or similar.
  872. * However in some environments the use of `eval` is banned
  873. * so we provide an alternative.
  874. */
  875. goog.define('goog.LOAD_MODULE_USING_EVAL', true);
  876. /**
  877. * @define {boolean} Whether the exports of goog.modules should be sealed when
  878. * possible.
  879. */
  880. goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);
  881. /**
  882. * The registry of initialized modules:
  883. * The module identifier or path to module exports map.
  884. * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}
  885. */
  886. goog.loadedModules_ = {};
  887. /**
  888. * True if the debug loader enabled and used.
  889. * @const {boolean}
  890. */
  891. goog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;
  892. /**
  893. * @define {string} How to decide whether to transpile. Valid values
  894. * are 'always', 'never', and 'detect'. The default ('detect') is to
  895. * use feature detection to determine which language levels need
  896. * transpilation.
  897. */
  898. // NOTE(sdh): we could expand this to accept a language level to bypass
  899. // detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but
  900. // would leave ES3 and ES5 files alone.
  901. goog.define('goog.TRANSPILE', 'detect');
  902. /**
  903. * @define {string} If a file needs to be transpiled what the output language
  904. * should be. By default this is the highest language level this file detects
  905. * the current environment supports. Generally this flag should not be set, but
  906. * it could be useful to override. Example: If the current environment supports
  907. * ES6 then by default ES7+ files will be transpiled to ES6, unless this is
  908. * overridden.
  909. *
  910. * Valid values include: es3, es5, es6, es7, and es8. Anything not recognized
  911. * is treated as es3.
  912. *
  913. * Note that setting this value does not force transpilation. Just if
  914. * transpilation occurs this will be the output. So this is most useful when
  915. * goog.TRANSPILE is set to 'always' and then forcing the language level to be
  916. * something lower than what the environment detects.
  917. */
  918. goog.define('goog.TRANSPILE_TO_LANGUAGE', '');
  919. /**
  920. * @define {string} Path to the transpiler. Executing the script at this
  921. * path (relative to base.js) should define a function $jscomp.transpile.
  922. */
  923. goog.define('goog.TRANSPILER', 'transpile.js');
  924. /**
  925. * @package {?boolean}
  926. * Visible for testing.
  927. */
  928. goog.hasBadLetScoping = null;
  929. /**
  930. * @return {boolean}
  931. * @package Visible for testing.
  932. */
  933. goog.useSafari10Workaround = function() {
  934. if (goog.hasBadLetScoping == null) {
  935. var hasBadLetScoping;
  936. try {
  937. hasBadLetScoping = !eval(
  938. '"use strict";' +
  939. 'let x = 1; function f() { return typeof x; };' +
  940. 'f() == "number";');
  941. } catch (e) {
  942. // Assume that ES6 syntax isn't supported.
  943. hasBadLetScoping = false;
  944. }
  945. goog.hasBadLetScoping = hasBadLetScoping;
  946. }
  947. return goog.hasBadLetScoping;
  948. };
  949. /**
  950. * @param {string} moduleDef
  951. * @return {string}
  952. * @package Visible for testing.
  953. */
  954. goog.workaroundSafari10EvalBug = function(moduleDef) {
  955. return '(function(){' + moduleDef +
  956. '\n' + // Terminate any trailing single line comment.
  957. ';' + // Terminate any trailing expression.
  958. '})();\n';
  959. };
  960. /**
  961. * @param {function(?):?|string} moduleDef The module definition.
  962. */
  963. goog.loadModule = function(moduleDef) {
  964. // NOTE: we allow function definitions to be either in the from
  965. // of a string to eval (which keeps the original source intact) or
  966. // in a eval forbidden environment (CSP) we allow a function definition
  967. // which in its body must call `goog.module`, and return the exports
  968. // of the module.
  969. var previousState = goog.moduleLoaderState_;
  970. try {
  971. goog.moduleLoaderState_ = {
  972. moduleName: '',
  973. declareLegacyNamespace: false,
  974. type: goog.ModuleType.GOOG
  975. };
  976. var exports;
  977. if (goog.isFunction(moduleDef)) {
  978. exports = moduleDef.call(undefined, {});
  979. } else if (goog.isString(moduleDef)) {
  980. if (goog.useSafari10Workaround()) {
  981. moduleDef = goog.workaroundSafari10EvalBug(moduleDef);
  982. }
  983. exports = goog.loadModuleFromSource_.call(undefined, moduleDef);
  984. } else {
  985. throw new Error('Invalid module definition');
  986. }
  987. var moduleName = goog.moduleLoaderState_.moduleName;
  988. if (goog.isString(moduleName) && moduleName) {
  989. // Don't seal legacy namespaces as they may be used as a parent of
  990. // another namespace
  991. if (goog.moduleLoaderState_.declareLegacyNamespace) {
  992. goog.constructNamespace_(moduleName, exports);
  993. } else if (
  994. goog.SEAL_MODULE_EXPORTS && Object.seal &&
  995. typeof exports == 'object' && exports != null) {
  996. Object.seal(exports);
  997. }
  998. var data = {
  999. exports: exports,
  1000. type: goog.ModuleType.GOOG,
  1001. moduleId: goog.moduleLoaderState_.moduleName
  1002. };
  1003. goog.loadedModules_[moduleName] = data;
  1004. } else {
  1005. throw new Error('Invalid module name \"' + moduleName + '\"');
  1006. }
  1007. } finally {
  1008. goog.moduleLoaderState_ = previousState;
  1009. }
  1010. };
  1011. /**
  1012. * @private @const
  1013. */
  1014. goog.loadModuleFromSource_ = /** @type {function(string):?} */ (function() {
  1015. // NOTE: we avoid declaring parameters or local variables here to avoid
  1016. // masking globals or leaking values into the module definition.
  1017. 'use strict';
  1018. var exports = {};
  1019. eval(arguments[0]);
  1020. return exports;
  1021. });
  1022. /**
  1023. * Normalize a file path by removing redundant ".." and extraneous "." file
  1024. * path components.
  1025. * @param {string} path
  1026. * @return {string}
  1027. * @private
  1028. */
  1029. goog.normalizePath_ = function(path) {
  1030. var components = path.split('/');
  1031. var i = 0;
  1032. while (i < components.length) {
  1033. if (components[i] == '.') {
  1034. components.splice(i, 1);
  1035. } else if (
  1036. i && components[i] == '..' && components[i - 1] &&
  1037. components[i - 1] != '..') {
  1038. components.splice(--i, 2);
  1039. } else {
  1040. i++;
  1041. }
  1042. }
  1043. return components.join('/');
  1044. };
  1045. /**
  1046. * Provides a hook for loading a file when using Closure's goog.require() API
  1047. * with goog.modules. In particular this hook is provided to support Node.js.
  1048. *
  1049. * @type {(function(string):string)|undefined}
  1050. */
  1051. goog.global.CLOSURE_LOAD_FILE_SYNC;
  1052. /**
  1053. * Loads file by synchronous XHR. Should not be used in production environments.
  1054. * @param {string} src Source URL.
  1055. * @return {?string} File contents, or null if load failed.
  1056. * @private
  1057. */
  1058. goog.loadFileSync_ = function(src) {
  1059. if (goog.global.CLOSURE_LOAD_FILE_SYNC) {
  1060. return goog.global.CLOSURE_LOAD_FILE_SYNC(src);
  1061. } else {
  1062. try {
  1063. /** @type {XMLHttpRequest} */
  1064. var xhr = new goog.global['XMLHttpRequest']();
  1065. xhr.open('get', src, false);
  1066. xhr.send();
  1067. // NOTE: Successful http: requests have a status of 200, but successful
  1068. // file: requests may have a status of zero. Any other status, or a
  1069. // thrown exception (particularly in case of file: requests) indicates
  1070. // some sort of error, which we treat as a missing or unavailable file.
  1071. return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null;
  1072. } catch (err) {
  1073. // No need to rethrow or log, since errors should show up on their own.
  1074. return null;
  1075. }
  1076. }
  1077. };
  1078. /**
  1079. * Lazily retrieves the transpiler and applies it to the source.
  1080. * @param {string} code JS code.
  1081. * @param {string} path Path to the code.
  1082. * @param {string} target Language level output.
  1083. * @return {string} The transpiled code.
  1084. * @private
  1085. */
  1086. goog.transpile_ = function(code, path, target) {
  1087. var jscomp = goog.global['$jscomp'];
  1088. if (!jscomp) {
  1089. goog.global['$jscomp'] = jscomp = {};
  1090. }
  1091. var transpile = jscomp.transpile;
  1092. if (!transpile) {
  1093. var transpilerPath = goog.basePath + goog.TRANSPILER;
  1094. var transpilerCode = goog.loadFileSync_(transpilerPath);
  1095. if (transpilerCode) {
  1096. // This must be executed synchronously, since by the time we know we
  1097. // need it, we're about to load and write the ES6 code synchronously,
  1098. // so a normal script-tag load will be too slow. Wrapped in a function
  1099. // so that code is eval'd in the global scope.
  1100. (function() {
  1101. eval(transpilerCode + '\n//# sourceURL=' + transpilerPath);
  1102. }).call(goog.global);
  1103. // Even though the transpiler is optional, if $gwtExport is found, it's
  1104. // a sign the transpiler was loaded and the $jscomp.transpile *should*
  1105. // be there.
  1106. if (goog.global['$gwtExport'] && goog.global['$gwtExport']['$jscomp'] &&
  1107. !goog.global['$gwtExport']['$jscomp']['transpile']) {
  1108. throw new Error(
  1109. 'The transpiler did not properly export the "transpile" ' +
  1110. 'method. $gwtExport: ' + JSON.stringify(goog.global['$gwtExport']));
  1111. }
  1112. // transpile.js only exports a single $jscomp function, transpile. We
  1113. // grab just that and add it to the existing definition of $jscomp which
  1114. // contains the polyfills.
  1115. goog.global['$jscomp'].transpile =
  1116. goog.global['$gwtExport']['$jscomp']['transpile'];
  1117. jscomp = goog.global['$jscomp'];
  1118. transpile = jscomp.transpile;
  1119. }
  1120. }
  1121. if (!transpile) {
  1122. // The transpiler is an optional component. If it's not available then
  1123. // replace it with a pass-through function that simply logs.
  1124. var suffix = ' requires transpilation but no transpiler was found.';
  1125. transpile = jscomp.transpile = function(code, path) {
  1126. // TODO(sdh): figure out some way to get this error to show up
  1127. // in test results, noting that the failure may occur in many
  1128. // different ways, including in loadModule() before the test
  1129. // runner even comes up.
  1130. goog.logToConsole_(path + suffix);
  1131. return code;
  1132. };
  1133. }
  1134. // Note: any transpilation errors/warnings will be logged to the console.
  1135. return transpile(code, path, target);
  1136. };
  1137. //==============================================================================
  1138. // Language Enhancements
  1139. //==============================================================================
  1140. /**
  1141. * This is a "fixed" version of the typeof operator. It differs from the typeof
  1142. * operator in such a way that null returns 'null' and arrays return 'array'.
  1143. * @param {?} value The value to get the type of.
  1144. * @return {string} The name of the type.
  1145. */
  1146. goog.typeOf = function(value) {
  1147. var s = typeof value;
  1148. if (s == 'object') {
  1149. if (value) {
  1150. // Check these first, so we can avoid calling Object.prototype.toString if
  1151. // possible.
  1152. //
  1153. // IE improperly marshals typeof across execution contexts, but a
  1154. // cross-context object will still return false for "instanceof Object".
  1155. if (value instanceof Array) {
  1156. return 'array';
  1157. } else if (value instanceof Object) {
  1158. return s;
  1159. }
  1160. // HACK: In order to use an Object prototype method on the arbitrary
  1161. // value, the compiler requires the value be cast to type Object,
  1162. // even though the ECMA spec explicitly allows it.
  1163. var className = Object.prototype.toString.call(
  1164. /** @type {!Object} */ (value));
  1165. // In Firefox 3.6, attempting to access iframe window objects' length
  1166. // property throws an NS_ERROR_FAILURE, so we need to special-case it
  1167. // here.
  1168. if (className == '[object Window]') {
  1169. return 'object';
  1170. }
  1171. // We cannot always use constructor == Array or instanceof Array because
  1172. // different frames have different Array objects. In IE6, if the iframe
  1173. // where the array was created is destroyed, the array loses its
  1174. // prototype. Then dereferencing val.splice here throws an exception, so
  1175. // we can't use goog.isFunction. Calling typeof directly returns 'unknown'
  1176. // so that will work. In this case, this function will return false and
  1177. // most array functions will still work because the array is still
  1178. // array-like (supports length and []) even though it has lost its
  1179. // prototype.
  1180. // Mark Miller noticed that Object.prototype.toString
  1181. // allows access to the unforgeable [[Class]] property.
  1182. // 15.2.4.2 Object.prototype.toString ( )
  1183. // When the toString method is called, the following steps are taken:
  1184. // 1. Get the [[Class]] property of this object.
  1185. // 2. Compute a string value by concatenating the three strings
  1186. // "[object ", Result(1), and "]".
  1187. // 3. Return Result(2).
  1188. // and this behavior survives the destruction of the execution context.
  1189. if ((className == '[object Array]' ||
  1190. // In IE all non value types are wrapped as objects across window
  1191. // boundaries (not iframe though) so we have to do object detection
  1192. // for this edge case.
  1193. typeof value.length == 'number' &&
  1194. typeof value.splice != 'undefined' &&
  1195. typeof value.propertyIsEnumerable != 'undefined' &&
  1196. !value.propertyIsEnumerable('splice')
  1197. )) {
  1198. return 'array';
  1199. }
  1200. // HACK: There is still an array case that fails.
  1201. // function ArrayImpostor() {}
  1202. // ArrayImpostor.prototype = [];
  1203. // var impostor = new ArrayImpostor;
  1204. // this can be fixed by getting rid of the fast path
  1205. // (value instanceof Array) and solely relying on
  1206. // (value && Object.prototype.toString.vall(value) === '[object Array]')
  1207. // but that would require many more function calls and is not warranted
  1208. // unless closure code is receiving objects from untrusted sources.
  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. } else {
  1220. return 'null';
  1221. }
  1222. } else if (s == 'function' && typeof value.call == 'undefined') {
  1223. // In Safari typeof nodeList returns 'function', and on Firefox typeof
  1224. // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We
  1225. // would like to return object for those and we can detect an invalid
  1226. // function by making sure that the function object has a call method.
  1227. return 'object';
  1228. }
  1229. return s;
  1230. };
  1231. /**
  1232. * Returns true if the specified value is null.
  1233. * @param {?} val Variable to test.
  1234. * @return {boolean} Whether variable is null.
  1235. */
  1236. goog.isNull = function(val) {
  1237. return val === null;
  1238. };
  1239. /**
  1240. * Returns true if the specified value is defined and not null.
  1241. * @param {?} val Variable to test.
  1242. * @return {boolean} Whether variable is defined and not null.
  1243. */
  1244. goog.isDefAndNotNull = function(val) {
  1245. // Note that undefined == null.
  1246. return val != null;
  1247. };
  1248. /**
  1249. * Returns true if the specified value is an array.
  1250. * @param {?} val Variable to test.
  1251. * @return {boolean} Whether variable is an array.
  1252. */
  1253. goog.isArray = function(val) {
  1254. return goog.typeOf(val) == 'array';
  1255. };
  1256. /**
  1257. * Returns true if the object looks like an array. To qualify as array like
  1258. * the value needs to be either a NodeList or an object with a Number length
  1259. * property. Note that for this function neither strings nor functions are
  1260. * considered "array-like".
  1261. *
  1262. * @param {?} val Variable to test.
  1263. * @return {boolean} Whether variable is an array.
  1264. */
  1265. goog.isArrayLike = function(val) {
  1266. var type = goog.typeOf(val);
  1267. // We do not use goog.isObject here in order to exclude function values.
  1268. return type == 'array' || type == 'object' && typeof val.length == 'number';
  1269. };
  1270. /**
  1271. * Returns true if the object looks like a Date. To qualify as Date-like the
  1272. * value needs to be an object and have a getFullYear() function.
  1273. * @param {?} val Variable to test.
  1274. * @return {boolean} Whether variable is a like a Date.
  1275. */
  1276. goog.isDateLike = function(val) {
  1277. return goog.isObject(val) && typeof val.getFullYear == 'function';
  1278. };
  1279. /**
  1280. * Returns true if the specified value is a function.
  1281. * @param {?} val Variable to test.
  1282. * @return {boolean} Whether variable is a function.
  1283. */
  1284. goog.isFunction = function(val) {
  1285. return goog.typeOf(val) == 'function';
  1286. };
  1287. /**
  1288. * Returns true if the specified value is an object. This includes arrays and
  1289. * functions.
  1290. * @param {?} val Variable to test.
  1291. * @return {boolean} Whether variable is an object.
  1292. */
  1293. goog.isObject = function(val) {
  1294. var type = typeof val;
  1295. return type == 'object' && val != null || type == 'function';
  1296. // return Object(val) === val also works, but is slower, especially if val is
  1297. // not an object.
  1298. };
  1299. /**
  1300. * Gets a unique ID for an object. This mutates the object so that further calls
  1301. * with the same object as a parameter returns the same value. The unique ID is
  1302. * guaranteed to be unique across the current session amongst objects that are
  1303. * passed into `getUid`. There is no guarantee that the ID is unique or
  1304. * consistent across sessions. It is unsafe to generate unique ID for function
  1305. * prototypes.
  1306. *
  1307. * @param {Object} obj The object to get the unique ID for.
  1308. * @return {number} The unique ID for the object.
  1309. */
  1310. goog.getUid = function(obj) {
  1311. // TODO(arv): Make the type stricter, do not accept null.
  1312. // In Opera window.hasOwnProperty exists but always returns false so we avoid
  1313. // using it. As a consequence the unique ID generated for BaseClass.prototype
  1314. // and SubClass.prototype will be the same.
  1315. return obj[goog.UID_PROPERTY_] ||
  1316. (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);
  1317. };
  1318. /**
  1319. * Whether the given object is already assigned a unique ID.
  1320. *
  1321. * This does not modify the object.
  1322. *
  1323. * @param {!Object} obj The object to check.
  1324. * @return {boolean} Whether there is an assigned unique id for the object.
  1325. */
  1326. goog.hasUid = function(obj) {
  1327. return !!obj[goog.UID_PROPERTY_];
  1328. };
  1329. /**
  1330. * Removes the unique ID from an object. This is useful if the object was
  1331. * previously mutated using `goog.getUid` in which case the mutation is
  1332. * undone.
  1333. * @param {Object} obj The object to remove the unique ID field from.
  1334. */
  1335. goog.removeUid = function(obj) {
  1336. // TODO(arv): Make the type stricter, do not accept null.
  1337. // In IE, DOM nodes are not instances of Object and throw an exception if we
  1338. // try to delete. Instead we try to use removeAttribute.
  1339. if (obj !== null && 'removeAttribute' in obj) {
  1340. obj.removeAttribute(goog.UID_PROPERTY_);
  1341. }
  1342. try {
  1343. delete obj[goog.UID_PROPERTY_];
  1344. } catch (ex) {
  1345. }
  1346. };
  1347. /**
  1348. * Name for unique ID property. Initialized in a way to help avoid collisions
  1349. * with other closure JavaScript on the same page.
  1350. * @type {string}
  1351. * @private
  1352. */
  1353. goog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);
  1354. /**
  1355. * Counter for UID.
  1356. * @type {number}
  1357. * @private
  1358. */
  1359. goog.uidCounter_ = 0;
  1360. /**
  1361. * Adds a hash code field to an object. The hash code is unique for the
  1362. * given object.
  1363. * @param {Object} obj The object to get the hash code for.
  1364. * @return {number} The hash code for the object.
  1365. * @deprecated Use goog.getUid instead.
  1366. */
  1367. goog.getHashCode = goog.getUid;
  1368. /**
  1369. * Removes the hash code field from an object.
  1370. * @param {Object} obj The object to remove the field from.
  1371. * @deprecated Use goog.removeUid instead.
  1372. */
  1373. goog.removeHashCode = goog.removeUid;
  1374. /**
  1375. * Clones a value. The input may be an Object, Array, or basic type. Objects and
  1376. * arrays will be cloned recursively.
  1377. *
  1378. * WARNINGS:
  1379. * <code>goog.cloneObject</code> does not detect reference loops. Objects that
  1380. * refer to themselves will cause infinite recursion.
  1381. *
  1382. * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies
  1383. * UIDs created by <code>getUid</code> into cloned results.
  1384. *
  1385. * @param {*} obj The value to clone.
  1386. * @return {*} A clone of the input value.
  1387. * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.
  1388. */
  1389. goog.cloneObject = function(obj) {
  1390. var type = goog.typeOf(obj);
  1391. if (type == 'object' || type == 'array') {
  1392. if (typeof obj.clone === 'function') {
  1393. return obj.clone();
  1394. }
  1395. var clone = type == 'array' ? [] : {};
  1396. for (var key in obj) {
  1397. clone[key] = goog.cloneObject(obj[key]);
  1398. }
  1399. return clone;
  1400. }
  1401. return obj;
  1402. };
  1403. /**
  1404. * A native implementation of goog.bind.
  1405. * @param {?function(this:T, ...)} fn A function to partially apply.
  1406. * @param {T} selfObj Specifies the object which this should point to when the
  1407. * function is run.
  1408. * @param {...*} var_args Additional arguments that are partially applied to the
  1409. * function.
  1410. * @return {!Function} A partially-applied form of the function goog.bind() was
  1411. * invoked as a method of.
  1412. * @template T
  1413. * @private
  1414. */
  1415. goog.bindNative_ = function(fn, selfObj, var_args) {
  1416. return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
  1417. };
  1418. /**
  1419. * A pure-JS implementation of goog.bind.
  1420. * @param {?function(this:T, ...)} fn A function to partially apply.
  1421. * @param {T} selfObj Specifies the object which this should point to when the
  1422. * function is run.
  1423. * @param {...*} var_args Additional arguments that are partially applied to the
  1424. * function.
  1425. * @return {!Function} A partially-applied form of the function goog.bind() was
  1426. * invoked as a method of.
  1427. * @template T
  1428. * @private
  1429. */
  1430. goog.bindJs_ = function(fn, selfObj, var_args) {
  1431. if (!fn) {
  1432. throw new Error();
  1433. }
  1434. if (arguments.length > 2) {
  1435. var boundArgs = Array.prototype.slice.call(arguments, 2);
  1436. return function() {
  1437. // Prepend the bound arguments to the current arguments.
  1438. var newArgs = Array.prototype.slice.call(arguments);
  1439. Array.prototype.unshift.apply(newArgs, boundArgs);
  1440. return fn.apply(selfObj, newArgs);
  1441. };
  1442. } else {
  1443. return function() {
  1444. return fn.apply(selfObj, arguments);
  1445. };
  1446. }
  1447. };
  1448. /**
  1449. * Partially applies this function to a particular 'this object' and zero or
  1450. * more arguments. The result is a new function with some arguments of the first
  1451. * function pre-filled and the value of this 'pre-specified'.
  1452. *
  1453. * Remaining arguments specified at call-time are appended to the pre-specified
  1454. * ones.
  1455. *
  1456. * Also see: {@link #partial}.
  1457. *
  1458. * Usage:
  1459. * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');
  1460. * barMethBound('arg3', 'arg4');</pre>
  1461. *
  1462. * @param {?function(this:T, ...)} fn A function to partially apply.
  1463. * @param {T} selfObj Specifies the object which this should point to when the
  1464. * function is run.
  1465. * @param {...*} var_args Additional arguments that are partially applied to the
  1466. * function.
  1467. * @return {!Function} A partially-applied form of the function goog.bind() was
  1468. * invoked as a method of.
  1469. * @template T
  1470. * @suppress {deprecated} See above.
  1471. */
  1472. goog.bind = function(fn, selfObj, var_args) {
  1473. // TODO(nicksantos): narrow the type signature.
  1474. if (Function.prototype.bind &&
  1475. // NOTE(nicksantos): Somebody pulled base.js into the default Chrome
  1476. // extension environment. This means that for Chrome extensions, they get
  1477. // the implementation of Function.prototype.bind that calls goog.bind
  1478. // instead of the native one. Even worse, we don't want to introduce a
  1479. // circular dependency between goog.bind and Function.prototype.bind, so
  1480. // we have to hack this to make sure it works correctly.
  1481. Function.prototype.bind.toString().indexOf('native code') != -1) {
  1482. goog.bind = goog.bindNative_;
  1483. } else {
  1484. goog.bind = goog.bindJs_;
  1485. }
  1486. return goog.bind.apply(null, arguments);
  1487. };
  1488. /**
  1489. * Like goog.bind(), except that a 'this object' is not required. Useful when
  1490. * the target function is already bound.
  1491. *
  1492. * Usage:
  1493. * var g = goog.partial(f, arg1, arg2);
  1494. * g(arg3, arg4);
  1495. *
  1496. * @param {Function} fn A function to partially apply.
  1497. * @param {...*} var_args Additional arguments that are partially applied to fn.
  1498. * @return {!Function} A partially-applied form of the function goog.partial()
  1499. * was invoked as a method of.
  1500. */
  1501. goog.partial = function(fn, var_args) {
  1502. var args = Array.prototype.slice.call(arguments, 1);
  1503. return function() {
  1504. // Clone the array (with slice()) and append additional arguments
  1505. // to the existing arguments.
  1506. var newArgs = args.slice();
  1507. newArgs.push.apply(newArgs, arguments);
  1508. return fn.apply(/** @type {?} */ (this), newArgs);
  1509. };
  1510. };
  1511. /**
  1512. * Copies all the members of a source object to a target object. This method
  1513. * does not work on all browsers for all objects that contain keys such as
  1514. * toString or hasOwnProperty. Use goog.object.extend for this purpose.
  1515. * @param {Object} target Target.
  1516. * @param {Object} source Source.
  1517. */
  1518. goog.mixin = function(target, source) {
  1519. for (var x in source) {
  1520. target[x] = source[x];
  1521. }
  1522. // For IE7 or lower, the for-in-loop does not contain any properties that are
  1523. // not enumerable on the prototype object (for example, isPrototypeOf from
  1524. // Object.prototype) but also it will not include 'replace' on objects that
  1525. // extend String and change 'replace' (not that it is common for anyone to
  1526. // extend anything except Object).
  1527. };
  1528. /**
  1529. * @return {number} An integer value representing the number of milliseconds
  1530. * between midnight, January 1, 1970 and the current time.
  1531. */
  1532. goog.now = (goog.TRUSTED_SITE && Date.now) || (function() {
  1533. // Unary plus operator converts its operand to a number which in
  1534. // the case of
  1535. // a date is done by calling getTime().
  1536. return +new Date();
  1537. });
  1538. /**
  1539. * Evals JavaScript in the global scope. In IE this uses execScript, other
  1540. * browsers use goog.global.eval. If goog.global.eval does not evaluate in the
  1541. * global scope (for example, in Safari), appends a script tag instead.
  1542. * Throws an exception if neither execScript or eval is defined.
  1543. * @param {string} script JavaScript string.
  1544. */
  1545. goog.globalEval = function(script) {
  1546. if (goog.global.execScript) {
  1547. goog.global.execScript(script, 'JavaScript');
  1548. } else if (goog.global.eval) {
  1549. // Test to see if eval works
  1550. if (goog.evalWorksForGlobals_ == null) {
  1551. try {
  1552. goog.global.eval('var _evalTest_ = 1;');
  1553. } catch (ignore) {
  1554. }
  1555. if (typeof goog.global['_evalTest_'] != 'undefined') {
  1556. try {
  1557. delete goog.global['_evalTest_'];
  1558. } catch (ignore) {
  1559. // Microsoft edge fails the deletion above in strict mode.
  1560. }
  1561. goog.evalWorksForGlobals_ = true;
  1562. } else {
  1563. goog.evalWorksForGlobals_ = false;
  1564. }
  1565. }
  1566. if (goog.evalWorksForGlobals_) {
  1567. goog.global.eval(script);
  1568. } else {
  1569. /** @type {!Document} */
  1570. var doc = goog.global.document;
  1571. var scriptElt =
  1572. /** @type {!HTMLScriptElement} */ (doc.createElement('SCRIPT'));
  1573. scriptElt.type = 'text/javascript';
  1574. scriptElt.defer = false;
  1575. // Note(user): can't use .innerHTML since "t('<test>')" will fail and
  1576. // .text doesn't work in Safari 2. Therefore we append a text node.
  1577. scriptElt.appendChild(doc.createTextNode(script));
  1578. doc.head.appendChild(scriptElt);
  1579. doc.head.removeChild(scriptElt);
  1580. }
  1581. } else {
  1582. throw new Error('goog.globalEval not available');
  1583. }
  1584. };
  1585. /**
  1586. * Indicates whether or not we can call 'eval' directly to eval code in the
  1587. * global scope. Set to a Boolean by the first call to goog.globalEval (which
  1588. * empirically tests whether eval works for globals). @see goog.globalEval
  1589. * @type {?boolean}
  1590. * @private
  1591. */
  1592. goog.evalWorksForGlobals_ = null;
  1593. /**
  1594. * Optional map of CSS class names to obfuscated names used with
  1595. * goog.getCssName().
  1596. * @private {!Object<string, string>|undefined}
  1597. * @see goog.setCssNameMapping
  1598. */
  1599. goog.cssNameMapping_;
  1600. /**
  1601. * Optional obfuscation style for CSS class names. Should be set to either
  1602. * 'BY_WHOLE' or 'BY_PART' if defined.
  1603. * @type {string|undefined}
  1604. * @private
  1605. * @see goog.setCssNameMapping
  1606. */
  1607. goog.cssNameMappingStyle_;
  1608. /**
  1609. * A hook for modifying the default behavior goog.getCssName. The function
  1610. * if present, will receive the standard output of the goog.getCssName as
  1611. * its input.
  1612. *
  1613. * @type {(function(string):string)|undefined}
  1614. */
  1615. goog.global.CLOSURE_CSS_NAME_MAP_FN;
  1616. /**
  1617. * Handles strings that are intended to be used as CSS class names.
  1618. *
  1619. * This function works in tandem with @see goog.setCssNameMapping.
  1620. *
  1621. * Without any mapping set, the arguments are simple joined with a hyphen and
  1622. * passed through unaltered.
  1623. *
  1624. * When there is a mapping, there are two possible styles in which these
  1625. * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)
  1626. * of the passed in css name is rewritten according to the map. In the BY_WHOLE
  1627. * style, the full css name is looked up in the map directly. If a rewrite is
  1628. * not specified by the map, the compiler will output a warning.
  1629. *
  1630. * When the mapping is passed to the compiler, it will replace calls to
  1631. * goog.getCssName with the strings from the mapping, e.g.
  1632. * var x = goog.getCssName('foo');
  1633. * var y = goog.getCssName(this.baseClass, 'active');
  1634. * becomes:
  1635. * var x = 'foo';
  1636. * var y = this.baseClass + '-active';
  1637. *
  1638. * If one argument is passed it will be processed, if two are passed only the
  1639. * modifier will be processed, as it is assumed the first argument was generated
  1640. * as a result of calling goog.getCssName.
  1641. *
  1642. * @param {string} className The class name.
  1643. * @param {string=} opt_modifier A modifier to be appended to the class name.
  1644. * @return {string} The class name or the concatenation of the class name and
  1645. * the modifier.
  1646. */
  1647. goog.getCssName = function(className, opt_modifier) {
  1648. // String() is used for compatibility with compiled soy where the passed
  1649. // className can be non-string objects.
  1650. if (String(className).charAt(0) == '.') {
  1651. throw new Error(
  1652. 'className passed in goog.getCssName must not start with ".".' +
  1653. ' You passed: ' + className);
  1654. }
  1655. var getMapping = function(cssName) {
  1656. return goog.cssNameMapping_[cssName] || cssName;
  1657. };
  1658. var renameByParts = function(cssName) {
  1659. // Remap all the parts individually.
  1660. var parts = cssName.split('-');
  1661. var mapped = [];
  1662. for (var i = 0; i < parts.length; i++) {
  1663. mapped.push(getMapping(parts[i]));
  1664. }
  1665. return mapped.join('-');
  1666. };
  1667. var rename;
  1668. if (goog.cssNameMapping_) {
  1669. rename =
  1670. goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts;
  1671. } else {
  1672. rename = function(a) {
  1673. return a;
  1674. };
  1675. }
  1676. var result =
  1677. opt_modifier ? className + '-' + rename(opt_modifier) : rename(className);
  1678. // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further
  1679. // processing of the class name.
  1680. if (goog.global.CLOSURE_CSS_NAME_MAP_FN) {
  1681. return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);
  1682. }
  1683. return result;
  1684. };
  1685. /**
  1686. * Sets the map to check when returning a value from goog.getCssName(). Example:
  1687. * <pre>
  1688. * goog.setCssNameMapping({
  1689. * "goog": "a",
  1690. * "disabled": "b",
  1691. * });
  1692. *
  1693. * var x = goog.getCssName('goog');
  1694. * // The following evaluates to: "a a-b".
  1695. * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')
  1696. * </pre>
  1697. * When declared as a map of string literals to string literals, the JSCompiler
  1698. * will replace all calls to goog.getCssName() using the supplied map if the
  1699. * --process_closure_primitives flag is set.
  1700. *
  1701. * @param {!Object} mapping A map of strings to strings where keys are possible
  1702. * arguments to goog.getCssName() and values are the corresponding values
  1703. * that should be returned.
  1704. * @param {string=} opt_style The style of css name mapping. There are two valid
  1705. * options: 'BY_PART', and 'BY_WHOLE'.
  1706. * @see goog.getCssName for a description.
  1707. */
  1708. goog.setCssNameMapping = function(mapping, opt_style) {
  1709. goog.cssNameMapping_ = mapping;
  1710. goog.cssNameMappingStyle_ = opt_style;
  1711. };
  1712. /**
  1713. * To use CSS renaming in compiled mode, one of the input files should have a
  1714. * call to goog.setCssNameMapping() with an object literal that the JSCompiler
  1715. * can extract and use to replace all calls to goog.getCssName(). In uncompiled
  1716. * mode, JavaScript code should be loaded before this base.js file that declares
  1717. * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is
  1718. * to ensure that the mapping is loaded before any calls to goog.getCssName()
  1719. * are made in uncompiled mode.
  1720. *
  1721. * A hook for overriding the CSS name mapping.
  1722. * @type {!Object<string, string>|undefined}
  1723. */
  1724. goog.global.CLOSURE_CSS_NAME_MAPPING;
  1725. if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {
  1726. // This does not call goog.setCssNameMapping() because the JSCompiler
  1727. // requires that goog.setCssNameMapping() be called with an object literal.
  1728. goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;
  1729. }
  1730. /**
  1731. * Gets a localized message.
  1732. *
  1733. * This function is a compiler primitive. If you give the compiler a localized
  1734. * message bundle, it will replace the string at compile-time with a localized
  1735. * version, and expand goog.getMsg call to a concatenated string.
  1736. *
  1737. * Messages must be initialized in the form:
  1738. * <code>
  1739. * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});
  1740. * </code>
  1741. *
  1742. * This function produces a string which should be treated as plain text. Use
  1743. * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to
  1744. * produce SafeHtml.
  1745. *
  1746. * @param {string} str Translatable string, places holders in the form {$foo}.
  1747. * @param {Object<string, string>=} opt_values Maps place holder name to value.
  1748. * @return {string} message with placeholders filled.
  1749. */
  1750. goog.getMsg = function(str, opt_values) {
  1751. if (opt_values) {
  1752. str = str.replace(/\{\$([^}]+)}/g, function(match, key) {
  1753. return (opt_values != null && key in opt_values) ? opt_values[key] :
  1754. match;
  1755. });
  1756. }
  1757. return str;
  1758. };
  1759. /**
  1760. * Gets a localized message. If the message does not have a translation, gives a
  1761. * fallback message.
  1762. *
  1763. * This is useful when introducing a new message that has not yet been
  1764. * translated into all languages.
  1765. *
  1766. * This function is a compiler primitive. Must be used in the form:
  1767. * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>
  1768. * where MSG_A and MSG_B were initialized with goog.getMsg.
  1769. *
  1770. * @param {string} a The preferred message.
  1771. * @param {string} b The fallback message.
  1772. * @return {string} The best translated message.
  1773. */
  1774. goog.getMsgWithFallback = function(a, b) {
  1775. return a;
  1776. };
  1777. /**
  1778. * Exposes an unobfuscated global namespace path for the given object.
  1779. * Note that fields of the exported object *will* be obfuscated, unless they are
  1780. * exported in turn via this function or goog.exportProperty.
  1781. *
  1782. * Also handy for making public items that are defined in anonymous closures.
  1783. *
  1784. * ex. goog.exportSymbol('public.path.Foo', Foo);
  1785. *
  1786. * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);
  1787. * public.path.Foo.staticFunction();
  1788. *
  1789. * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',
  1790. * Foo.prototype.myMethod);
  1791. * new public.path.Foo().myMethod();
  1792. *
  1793. * @param {string} publicPath Unobfuscated name to export.
  1794. * @param {*} object Object the name should point to.
  1795. * @param {Object=} opt_objectToExportTo The object to add the path to; default
  1796. * is goog.global.
  1797. */
  1798. goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {
  1799. goog.exportPath_(publicPath, object, opt_objectToExportTo);
  1800. };
  1801. /**
  1802. * Exports a property unobfuscated into the object's namespace.
  1803. * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);
  1804. * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);
  1805. * @param {Object} object Object whose static property is being exported.
  1806. * @param {string} publicName Unobfuscated name to export.
  1807. * @param {*} symbol Object the name should point to.
  1808. */
  1809. goog.exportProperty = function(object, publicName, symbol) {
  1810. object[publicName] = symbol;
  1811. };
  1812. /**
  1813. * Inherit the prototype methods from one constructor into another.
  1814. *
  1815. * Usage:
  1816. * <pre>
  1817. * function ParentClass(a, b) { }
  1818. * ParentClass.prototype.foo = function(a) { };
  1819. *
  1820. * function ChildClass(a, b, c) {
  1821. * ChildClass.base(this, 'constructor', a, b);
  1822. * }
  1823. * goog.inherits(ChildClass, ParentClass);
  1824. *
  1825. * var child = new ChildClass('a', 'b', 'see');
  1826. * child.foo(); // This works.
  1827. * </pre>
  1828. *
  1829. * @param {!Function} childCtor Child class.
  1830. * @param {!Function} parentCtor Parent class.
  1831. * @suppress {strictMissingProperties} superClass_ and base is not defined on
  1832. * Function.
  1833. */
  1834. goog.inherits = function(childCtor, parentCtor) {
  1835. /** @constructor */
  1836. function tempCtor() {}
  1837. tempCtor.prototype = parentCtor.prototype;
  1838. childCtor.superClass_ = parentCtor.prototype;
  1839. childCtor.prototype = new tempCtor();
  1840. /** @override */
  1841. childCtor.prototype.constructor = childCtor;
  1842. /**
  1843. * Calls superclass constructor/method.
  1844. *
  1845. * This function is only available if you use goog.inherits to
  1846. * express inheritance relationships between classes.
  1847. *
  1848. * NOTE: This is a replacement for goog.base and for superClass_
  1849. * property defined in childCtor.
  1850. *
  1851. * @param {!Object} me Should always be "this".
  1852. * @param {string} methodName The method name to call. Calling
  1853. * superclass constructor can be done with the special string
  1854. * 'constructor'.
  1855. * @param {...*} var_args The arguments to pass to superclass
  1856. * method/constructor.
  1857. * @return {*} The return value of the superclass method/constructor.
  1858. */
  1859. childCtor.base = function(me, methodName, var_args) {
  1860. // Copying using loop to avoid deop due to passing arguments object to
  1861. // function. This is faster in many JS engines as of late 2014.
  1862. var args = new Array(arguments.length - 2);
  1863. for (var i = 2; i < arguments.length; i++) {
  1864. args[i - 2] = arguments[i];
  1865. }
  1866. return parentCtor.prototype[methodName].apply(me, args);
  1867. };
  1868. };
  1869. /**
  1870. * Call up to the superclass.
  1871. *
  1872. * If this is called from a constructor, then this calls the superclass
  1873. * constructor with arguments 1-N.
  1874. *
  1875. * If this is called from a prototype method, then you must pass the name of the
  1876. * method as the second argument to this function. If you do not, you will get a
  1877. * runtime error. This calls the superclass' method with arguments 2-N.
  1878. *
  1879. * This function only works if you use goog.inherits to express inheritance
  1880. * relationships between your classes.
  1881. *
  1882. * This function is a compiler primitive. At compile-time, the compiler will do
  1883. * macro expansion to remove a lot of the extra overhead that this function
  1884. * introduces. The compiler will also enforce a lot of the assumptions that this
  1885. * function makes, and treat it as a compiler error if you break them.
  1886. *
  1887. * @param {!Object} me Should always be "this".
  1888. * @param {*=} opt_methodName The method name if calling a super method.
  1889. * @param {...*} var_args The rest of the arguments.
  1890. * @return {*} The return value of the superclass method.
  1891. * @suppress {es5Strict} This method can not be used in strict mode, but
  1892. * all Closure Library consumers must depend on this file.
  1893. * @deprecated goog.base is not strict mode compatible. Prefer the static
  1894. * "base" method added to the constructor by goog.inherits
  1895. * or ES6 classes and the "super" keyword.
  1896. */
  1897. goog.base = function(me, opt_methodName, var_args) {
  1898. var caller = arguments.callee.caller;
  1899. if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) {
  1900. throw new Error(
  1901. 'arguments.caller not defined. goog.base() cannot be used ' +
  1902. 'with strict mode code. See ' +
  1903. 'http://www.ecma-international.org/ecma-262/5.1/#sec-C');
  1904. }
  1905. if (typeof caller.superClass_ !== 'undefined') {
  1906. // Copying using loop to avoid deop due to passing arguments object to
  1907. // function. This is faster in many JS engines as of late 2014.
  1908. var ctorArgs = new Array(arguments.length - 1);
  1909. for (var i = 1; i < arguments.length; i++) {
  1910. ctorArgs[i - 1] = arguments[i];
  1911. }
  1912. // This is a constructor. Call the superclass constructor.
  1913. return /** @type {!Function} */ (caller.superClass_)
  1914. .constructor.apply(me, ctorArgs);
  1915. }
  1916. if (typeof opt_methodName != 'string' && typeof opt_methodName != 'symbol') {
  1917. throw new Error(
  1918. 'method names provided to goog.base must be a string or a symbol');
  1919. }
  1920. // Copying using loop to avoid deop due to passing arguments object to
  1921. // function. This is faster in many JS engines as of late 2014.
  1922. var args = new Array(arguments.length - 2);
  1923. for (var i = 2; i < arguments.length; i++) {
  1924. args[i - 2] = arguments[i];
  1925. }
  1926. var foundCaller = false;
  1927. for (var ctor = me.constructor; ctor;
  1928. ctor = ctor.superClass_ && ctor.superClass_.constructor) {
  1929. if (ctor.prototype[opt_methodName] === caller) {
  1930. foundCaller = true;
  1931. } else if (foundCaller) {
  1932. return ctor.prototype[opt_methodName].apply(me, args);
  1933. }
  1934. }
  1935. // If we did not find the caller in the prototype chain, then one of two
  1936. // things happened:
  1937. // 1) The caller is an instance method.
  1938. // 2) This method was not called by the right caller.
  1939. if (me[opt_methodName] === caller) {
  1940. return me.constructor.prototype[opt_methodName].apply(me, args);
  1941. } else {
  1942. throw new Error(
  1943. 'goog.base called from a method of one name ' +
  1944. 'to a method of a different name');
  1945. }
  1946. };
  1947. /**
  1948. * Allow for aliasing within scope functions. This function exists for
  1949. * uncompiled code - in compiled code the calls will be inlined and the aliases
  1950. * applied. In uncompiled code the function is simply run since the aliases as
  1951. * written are valid JavaScript.
  1952. *
  1953. *
  1954. * @param {function()} fn Function to call. This function can contain aliases
  1955. * to namespaces (e.g. "var dom = goog.dom") or classes
  1956. * (e.g. "var Timer = goog.Timer").
  1957. */
  1958. goog.scope = function(fn) {
  1959. if (goog.isInModuleLoader_()) {
  1960. throw new Error('goog.scope is not supported within a module.');
  1961. }
  1962. fn.call(goog.global);
  1963. };
  1964. /*
  1965. * To support uncompiled, strict mode bundles that use eval to divide source
  1966. * like so:
  1967. * eval('someSource;//# sourceUrl sourcefile.js');
  1968. * We need to export the globally defined symbols "goog" and "COMPILED".
  1969. * Exporting "goog" breaks the compiler optimizations, so we required that
  1970. * be defined externally.
  1971. * NOTE: We don't use goog.exportSymbol here because we don't want to trigger
  1972. * extern generation when that compiler option is enabled.
  1973. */
  1974. if (!COMPILED) {
  1975. goog.global['COMPILED'] = COMPILED;
  1976. }
  1977. //==============================================================================
  1978. // goog.defineClass implementation
  1979. //==============================================================================
  1980. /**
  1981. * Creates a restricted form of a Closure "class":
  1982. * - from the compiler's perspective, the instance returned from the
  1983. * constructor is sealed (no new properties may be added). This enables
  1984. * better checks.
  1985. * - the compiler will rewrite this definition to a form that is optimal
  1986. * for type checking and optimization (initially this will be a more
  1987. * traditional form).
  1988. *
  1989. * @param {Function} superClass The superclass, Object or null.
  1990. * @param {goog.defineClass.ClassDescriptor} def
  1991. * An object literal describing
  1992. * the class. It may have the following properties:
  1993. * "constructor": the constructor function
  1994. * "statics": an object literal containing methods to add to the constructor
  1995. * as "static" methods or a function that will receive the constructor
  1996. * function as its only parameter to which static properties can
  1997. * be added.
  1998. * all other properties are added to the prototype.
  1999. * @return {!Function} The class constructor.
  2000. */
  2001. goog.defineClass = function(superClass, def) {
  2002. // TODO(johnlenz): consider making the superClass an optional parameter.
  2003. var constructor = def.constructor;
  2004. var statics = def.statics;
  2005. // Wrap the constructor prior to setting up the prototype and static methods.
  2006. if (!constructor || constructor == Object.prototype.constructor) {
  2007. constructor = function() {
  2008. throw new Error(
  2009. 'cannot instantiate an interface (no constructor defined).');
  2010. };
  2011. }
  2012. var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);
  2013. if (superClass) {
  2014. goog.inherits(cls, superClass);
  2015. }
  2016. // Remove all the properties that should not be copied to the prototype.
  2017. delete def.constructor;
  2018. delete def.statics;
  2019. goog.defineClass.applyProperties_(cls.prototype, def);
  2020. if (statics != null) {
  2021. if (statics instanceof Function) {
  2022. statics(cls);
  2023. } else {
  2024. goog.defineClass.applyProperties_(cls, statics);
  2025. }
  2026. }
  2027. return cls;
  2028. };
  2029. /**
  2030. * @typedef {{
  2031. * constructor: (!Function|undefined),
  2032. * statics: (Object|undefined|function(Function):void)
  2033. * }}
  2034. */
  2035. goog.defineClass.ClassDescriptor;
  2036. /**
  2037. * @define {boolean} Whether the instances returned by goog.defineClass should
  2038. * be sealed when possible.
  2039. *
  2040. * When sealing is disabled the constructor function will not be wrapped by
  2041. * goog.defineClass, making it incompatible with ES6 class methods.
  2042. */
  2043. goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);
  2044. /**
  2045. * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is
  2046. * defined, this function will wrap the constructor in a function that seals the
  2047. * results of the provided constructor function.
  2048. *
  2049. * @param {!Function} ctr The constructor whose results maybe be sealed.
  2050. * @param {Function} superClass The superclass constructor.
  2051. * @return {!Function} The replacement constructor.
  2052. * @private
  2053. */
  2054. goog.defineClass.createSealingConstructor_ = function(ctr, superClass) {
  2055. if (!goog.defineClass.SEAL_CLASS_INSTANCES) {
  2056. // Do now wrap the constructor when sealing is disabled. Angular code
  2057. // depends on this for injection to work properly.
  2058. return ctr;
  2059. }
  2060. // Compute whether the constructor is sealable at definition time, rather
  2061. // than when the instance is being constructed.
  2062. var superclassSealable = !goog.defineClass.isUnsealable_(superClass);
  2063. /**
  2064. * @this {Object}
  2065. * @return {?}
  2066. */
  2067. var wrappedCtr = function() {
  2068. // Don't seal an instance of a subclass when it calls the constructor of
  2069. // its super class as there is most likely still setup to do.
  2070. var instance = ctr.apply(this, arguments) || this;
  2071. instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];
  2072. if (this.constructor === wrappedCtr && superclassSealable &&
  2073. Object.seal instanceof Function) {
  2074. Object.seal(instance);
  2075. }
  2076. return instance;
  2077. };
  2078. return wrappedCtr;
  2079. };
  2080. /**
  2081. * @param {Function} ctr The constructor to test.
  2082. * @return {boolean} Whether the constructor has been tagged as unsealable
  2083. * using goog.tagUnsealableClass.
  2084. * @private
  2085. */
  2086. goog.defineClass.isUnsealable_ = function(ctr) {
  2087. return ctr && ctr.prototype &&
  2088. ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_];
  2089. };
  2090. // TODO(johnlenz): share these values with the goog.object
  2091. /**
  2092. * The names of the fields that are defined on Object.prototype.
  2093. * @type {!Array<string>}
  2094. * @private
  2095. * @const
  2096. */
  2097. goog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [
  2098. 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
  2099. 'toLocaleString', 'toString', 'valueOf'
  2100. ];
  2101. // TODO(johnlenz): share this function with the goog.object
  2102. /**
  2103. * @param {!Object} target The object to add properties to.
  2104. * @param {!Object} source The object to copy properties from.
  2105. * @private
  2106. */
  2107. goog.defineClass.applyProperties_ = function(target, source) {
  2108. // TODO(johnlenz): update this to support ES5 getters/setters
  2109. var key;
  2110. for (key in source) {
  2111. if (Object.prototype.hasOwnProperty.call(source, key)) {
  2112. target[key] = source[key];
  2113. }
  2114. }
  2115. // For IE the for-in-loop does not contain any properties that are not
  2116. // enumerable on the prototype object (for example isPrototypeOf from
  2117. // Object.prototype) and it will also not include 'replace' on objects that
  2118. // extend String and change 'replace' (not that it is common for anyone to
  2119. // extend anything except Object).
  2120. for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {
  2121. key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];
  2122. if (Object.prototype.hasOwnProperty.call(source, key)) {
  2123. target[key] = source[key];
  2124. }
  2125. }
  2126. };
  2127. /**
  2128. * Sealing classes breaks the older idiom of assigning properties on the
  2129. * prototype rather than in the constructor. As such, goog.defineClass
  2130. * must not seal subclasses of these old-style classes until they are fixed.
  2131. * Until then, this marks a class as "broken", instructing defineClass
  2132. * not to seal subclasses.
  2133. * @param {!Function} ctr The legacy constructor to tag as unsealable.
  2134. */
  2135. goog.tagUnsealableClass = function(ctr) {
  2136. if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) {
  2137. ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true;
  2138. }
  2139. };
  2140. /**
  2141. * Name for unsealable tag property.
  2142. * @const @private {string}
  2143. */
  2144. goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable';
  2145. // There's a bug in the compiler where without collapse properties the
  2146. // Closure namespace defines do not guard code correctly. To help reduce code
  2147. // size also check for !COMPILED even though it redundant until this is fixed.
  2148. if (!COMPILED && goog.DEPENDENCIES_ENABLED) {
  2149. /**
  2150. * Tries to detect whether is in the context of an HTML document.
  2151. * @return {boolean} True if it looks like HTML document.
  2152. * @private
  2153. */
  2154. goog.inHtmlDocument_ = function() {
  2155. /** @type {!Document} */
  2156. var doc = goog.global.document;
  2157. return doc != null && 'write' in doc; // XULDocument misses write.
  2158. };
  2159. /**
  2160. * We'd like to check for if the document readyState is 'loading'; however
  2161. * there are bugs on IE 10 and below where the readyState being anything other
  2162. * than 'complete' is not reliable.
  2163. * @return {boolean}
  2164. * @private
  2165. */
  2166. goog.isDocumentLoading_ = function() {
  2167. // attachEvent is available on IE 6 thru 10 only, and thus can be used to
  2168. // detect those browsers.
  2169. /** @type {!HTMLDocument} */
  2170. var doc = goog.global.document;
  2171. return doc.attachEvent ? doc.readyState != 'complete' :
  2172. doc.readyState == 'loading';
  2173. };
  2174. /**
  2175. * Tries to detect the base path of base.js script that bootstraps Closure.
  2176. * @private
  2177. */
  2178. goog.findBasePath_ = function() {
  2179. if (goog.isDef(goog.global.CLOSURE_BASE_PATH) &&
  2180. // Anti DOM-clobbering runtime check (b/37736576).
  2181. goog.isString(goog.global.CLOSURE_BASE_PATH)) {
  2182. goog.basePath = goog.global.CLOSURE_BASE_PATH;
  2183. return;
  2184. } else if (!goog.inHtmlDocument_()) {
  2185. return;
  2186. }
  2187. /** @type {!Document} */
  2188. var doc = goog.global.document;
  2189. // If we have a currentScript available, use it exclusively.
  2190. var currentScript = doc.currentScript;
  2191. if (currentScript) {
  2192. var scripts = [currentScript];
  2193. } else {
  2194. var scripts = doc.getElementsByTagName('SCRIPT');
  2195. }
  2196. // Search backwards since the current script is in almost all cases the one
  2197. // that has base.js.
  2198. for (var i = scripts.length - 1; i >= 0; --i) {
  2199. var script = /** @type {!HTMLScriptElement} */ (scripts[i]);
  2200. var src = script.src;
  2201. var qmark = src.lastIndexOf('?');
  2202. var l = qmark == -1 ? src.length : qmark;
  2203. if (src.substr(l - 7, 7) == 'base.js') {
  2204. goog.basePath = src.substr(0, l - 7);
  2205. return;
  2206. }
  2207. }
  2208. };
  2209. goog.findBasePath_();
  2210. /** @struct @constructor @final */
  2211. goog.Transpiler = function() {
  2212. /** @private {?Object<string, boolean>} */
  2213. this.requiresTranspilation_ = null;
  2214. /** @private {string} */
  2215. this.transpilationTarget_ = goog.TRANSPILE_TO_LANGUAGE;
  2216. };
  2217. /**
  2218. * Returns a newly created map from language mode string to a boolean
  2219. * indicating whether transpilation should be done for that mode as well as
  2220. * the highest level language that this environment supports.
  2221. *
  2222. * Guaranteed invariant:
  2223. * For any two modes, l1 and l2 where l2 is a newer mode than l1,
  2224. * `map[l1] == true` implies that `map[l2] == true`.
  2225. *
  2226. * Note this method is extracted and used elsewhere, so it cannot rely on
  2227. * anything external (it should easily be able to be transformed into a
  2228. * standalone, top level function).
  2229. *
  2230. * @private
  2231. * @return {{
  2232. * target: string,
  2233. * map: !Object<string, boolean>
  2234. * }}
  2235. */
  2236. goog.Transpiler.prototype.createRequiresTranspilation_ = function() {
  2237. var transpilationTarget = 'es3';
  2238. var /** !Object<string, boolean> */ requiresTranspilation = {'es3': false};
  2239. var transpilationRequiredForAllLaterModes = false;
  2240. /**
  2241. * Adds an entry to requiresTranspliation for the given language mode.
  2242. *
  2243. * IMPORTANT: Calls must be made in order from oldest to newest language
  2244. * mode.
  2245. * @param {string} modeName
  2246. * @param {function(): boolean} isSupported Returns true if the JS engine
  2247. * supports the given mode.
  2248. */
  2249. function addNewerLanguageTranspilationCheck(modeName, isSupported) {
  2250. if (transpilationRequiredForAllLaterModes) {
  2251. requiresTranspilation[modeName] = true;
  2252. } else if (isSupported()) {
  2253. transpilationTarget = modeName;
  2254. requiresTranspilation[modeName] = false;
  2255. } else {
  2256. requiresTranspilation[modeName] = true;
  2257. transpilationRequiredForAllLaterModes = true;
  2258. }
  2259. }
  2260. /**
  2261. * Does the given code evaluate without syntax errors and return a truthy
  2262. * result?
  2263. */
  2264. function /** boolean */ evalCheck(/** string */ code) {
  2265. try {
  2266. return !!eval(code);
  2267. } catch (ignored) {
  2268. return false;
  2269. }
  2270. }
  2271. var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?
  2272. goog.global.navigator.userAgent :
  2273. '';
  2274. // Identify ES3-only browsers by their incorrect treatment of commas.
  2275. addNewerLanguageTranspilationCheck('es5', function() {
  2276. return evalCheck('[1,].length==1');
  2277. });
  2278. addNewerLanguageTranspilationCheck('es6', function() {
  2279. // Edge has a non-deterministic (i.e., not reproducible) bug with ES6:
  2280. // https://github.com/Microsoft/ChakraCore/issues/1496.
  2281. var re = /Edge\/(\d+)(\.\d)*/i;
  2282. var edgeUserAgent = userAgent.match(re);
  2283. if (edgeUserAgent && Number(edgeUserAgent[1]) < 15) {
  2284. return false;
  2285. }
  2286. // Test es6: [FF50 (?), Edge 14 (?), Chrome 50]
  2287. // (a) default params (specifically shadowing locals),
  2288. // (b) destructuring, (c) block-scoped functions,
  2289. // (d) for-of (const), (e) new.target/Reflect.construct
  2290. var es6fullTest =
  2291. 'class X{constructor(){if(new.target!=String)throw 1;this.x=42}}' +
  2292. 'let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof ' +
  2293. 'String))throw 1;for(const a of[2,3]){if(a==2)continue;function ' +
  2294. 'f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()' +
  2295. '==3}';
  2296. return evalCheck('(()=>{"use strict";' + es6fullTest + '})()');
  2297. });
  2298. // TODO(joeltine): Remove es6-impl references for b/31340605.
  2299. // Consider es6-impl (widely-implemented es6 features) to be supported
  2300. // whenever es6 is supported. Technically es6-impl is a lower level of
  2301. // support than es6, but we don't have tests specifically for it.
  2302. addNewerLanguageTranspilationCheck('es6-impl', function() {
  2303. return true;
  2304. });
  2305. // ** and **= are the only new features in 'es7'
  2306. addNewerLanguageTranspilationCheck('es7', function() {
  2307. return evalCheck('2 ** 2 == 4');
  2308. });
  2309. // async functions are the only new features in 'es8'
  2310. addNewerLanguageTranspilationCheck('es8', function() {
  2311. return evalCheck('async () => 1, true');
  2312. });
  2313. addNewerLanguageTranspilationCheck('es9', function() {
  2314. return evalCheck('({...rest} = {}), true');
  2315. });
  2316. addNewerLanguageTranspilationCheck('es_next', function() {
  2317. return false; // assume it always need to transpile
  2318. });
  2319. return {target: transpilationTarget, map: requiresTranspilation};
  2320. };
  2321. /**
  2322. * Determines whether the given language needs to be transpiled.
  2323. * @param {string} lang
  2324. * @param {string|undefined} module
  2325. * @return {boolean}
  2326. */
  2327. goog.Transpiler.prototype.needsTranspile = function(lang, module) {
  2328. if (goog.TRANSPILE == 'always') {
  2329. return true;
  2330. } else if (goog.TRANSPILE == 'never') {
  2331. return false;
  2332. } else if (!this.requiresTranspilation_) {
  2333. var obj = this.createRequiresTranspilation_();
  2334. this.requiresTranspilation_ = obj.map;
  2335. this.transpilationTarget_ = this.transpilationTarget_ || obj.target;
  2336. }
  2337. if (lang in this.requiresTranspilation_) {
  2338. if (this.requiresTranspilation_[lang]) {
  2339. return true;
  2340. } else if (
  2341. goog.inHtmlDocument_() && module == 'es6' &&
  2342. !('noModule' in goog.global.document.createElement('script'))) {
  2343. return true;
  2344. } else {
  2345. return false;
  2346. }
  2347. } else {
  2348. throw new Error('Unknown language mode: ' + lang);
  2349. }
  2350. };
  2351. /**
  2352. * Lazily retrieves the transpiler and applies it to the source.
  2353. * @param {string} code JS code.
  2354. * @param {string} path Path to the code.
  2355. * @return {string} The transpiled code.
  2356. */
  2357. goog.Transpiler.prototype.transpile = function(code, path) {
  2358. // TODO(johnplaisted): We should delete goog.transpile_ and just have this
  2359. // function. But there's some compile error atm where goog.global is being
  2360. // stripped incorrectly without this.
  2361. return goog.transpile_(code, path, this.transpilationTarget_);
  2362. };
  2363. /** @private @final {!goog.Transpiler} */
  2364. goog.transpiler_ = new goog.Transpiler();
  2365. /**
  2366. * Rewrites closing script tags in input to avoid ending an enclosing script
  2367. * tag.
  2368. *
  2369. * @param {string} str
  2370. * @return {string}
  2371. * @private
  2372. */
  2373. goog.protectScriptTag_ = function(str) {
  2374. return str.replace(/<\/(SCRIPT)/ig, '\\x3c/$1');
  2375. };
  2376. /**
  2377. * A debug loader is responsible for downloading and executing javascript
  2378. * files in an unbundled, uncompiled environment.
  2379. *
  2380. * This can be custimized via the setDependencyFactory method, or by
  2381. * CLOSURE_IMPORT_SCRIPT/CLOSURE_LOAD_FILE_SYNC.
  2382. *
  2383. * @struct @constructor @final @private
  2384. */
  2385. goog.DebugLoader_ = function() {
  2386. /** @private @const {!Object<string, !goog.Dependency>} */
  2387. this.dependencies_ = {};
  2388. /** @private @const {!Object<string, string>} */
  2389. this.idToPath_ = {};
  2390. /** @private @const {!Object<string, boolean>} */
  2391. this.written_ = {};
  2392. /** @private @const {!Array<!goog.Dependency>} */
  2393. this.loadingDeps_ = [];
  2394. /** @private {!Array<!goog.Dependency>} */
  2395. this.depsToLoad_ = [];
  2396. /** @private {boolean} */
  2397. this.paused_ = false;
  2398. /** @private {!goog.DependencyFactory} */
  2399. this.factory_ = new goog.DependencyFactory(goog.transpiler_);
  2400. /** @private @const {!Object<string, !Function>} */
  2401. this.deferredCallbacks_ = {};
  2402. /** @private @const {!Array<string>} */
  2403. this.deferredQueue_ = [];
  2404. };
  2405. /**
  2406. * @param {!Array<string>} namespaces
  2407. * @param {function(): undefined} callback Function to call once all the
  2408. * namespaces have loaded.
  2409. */
  2410. goog.DebugLoader_.prototype.bootstrap = function(namespaces, callback) {
  2411. var cb = callback;
  2412. function resolve() {
  2413. if (cb) {
  2414. goog.global.setTimeout(cb, 0);
  2415. cb = null;
  2416. }
  2417. }
  2418. if (!namespaces.length) {
  2419. resolve();
  2420. return;
  2421. }
  2422. var deps = [];
  2423. for (var i = 0; i < namespaces.length; i++) {
  2424. var path = this.getPathFromDeps_(namespaces[i]);
  2425. if (!path) {
  2426. throw new Error('Unregonized namespace: ' + namespaces[i]);
  2427. }
  2428. deps.push(this.dependencies_[path]);
  2429. }
  2430. var require = goog.require;
  2431. var loaded = 0;
  2432. for (var i = 0; i < namespaces.length; i++) {
  2433. require(namespaces[i]);
  2434. deps[i].onLoad(function() {
  2435. if (++loaded == namespaces.length) {
  2436. resolve();
  2437. }
  2438. });
  2439. }
  2440. };
  2441. /**
  2442. * Loads the Closure Dependency file.
  2443. *
  2444. * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base
  2445. * loaded, setDependencyFactory called, and then this called. i.e. allows
  2446. * custom loading of the deps file.
  2447. */
  2448. goog.DebugLoader_.prototype.loadClosureDeps = function() {
  2449. // Circumvent addDependency, which would try to transpile deps.js if
  2450. // transpile is set to always.
  2451. var relPath = 'deps.js';
  2452. this.depsToLoad_.push(this.factory_.createDependency(
  2453. goog.normalizePath_(goog.basePath + relPath), relPath, [], [], {},
  2454. false));
  2455. this.loadDeps_();
  2456. };
  2457. /**
  2458. * Notifies the debug loader when a dependency has been requested.
  2459. *
  2460. * @param {string} absPathOrId Path of the dependency or goog id.
  2461. * @param {boolean=} opt_force
  2462. */
  2463. goog.DebugLoader_.prototype.requested = function(absPathOrId, opt_force) {
  2464. var path = this.getPathFromDeps_(absPathOrId);
  2465. if (path &&
  2466. (opt_force || this.areDepsLoaded_(this.dependencies_[path].requires))) {
  2467. var callback = this.deferredCallbacks_[path];
  2468. if (callback) {
  2469. delete this.deferredCallbacks_[path];
  2470. callback();
  2471. }
  2472. }
  2473. };
  2474. /**
  2475. * Sets the dependency factory, which can be used to create custom
  2476. * goog.Dependency implementations to control how dependencies are loaded.
  2477. *
  2478. * @param {!goog.DependencyFactory} factory
  2479. */
  2480. goog.DebugLoader_.prototype.setDependencyFactory = function(factory) {
  2481. this.factory_ = factory;
  2482. };
  2483. /**
  2484. * Travserses the dependency graph and queues the given dependency, and all of
  2485. * its transitive dependencies, for loading and then starts loading if not
  2486. * paused.
  2487. *
  2488. * @param {string} namespace
  2489. * @private
  2490. */
  2491. goog.DebugLoader_.prototype.load_ = function(namespace) {
  2492. if (!this.getPathFromDeps_(namespace)) {
  2493. var errorMessage = 'goog.require could not find: ' + namespace;
  2494. goog.logToConsole_(errorMessage);
  2495. throw Error(errorMessage);
  2496. } else {
  2497. var loader = this;
  2498. var deps = [];
  2499. /** @param {string} namespace */
  2500. var visit = function(namespace) {
  2501. var path = loader.getPathFromDeps_(namespace);
  2502. if (!path) {
  2503. throw new Error('Bad dependency path or symbol: ' + namespace);
  2504. }
  2505. if (loader.written_[path]) {
  2506. return;
  2507. }
  2508. loader.written_[path] = true;
  2509. var dep = loader.dependencies_[path];
  2510. for (var i = 0; i < dep.requires.length; i++) {
  2511. if (!goog.isProvided_(dep.requires[i])) {
  2512. visit(dep.requires[i]);
  2513. }
  2514. }
  2515. deps.push(dep);
  2516. };
  2517. visit(namespace);
  2518. var wasLoading = !!this.depsToLoad_.length;
  2519. this.depsToLoad_ = this.depsToLoad_.concat(deps);
  2520. if (!this.paused_ && !wasLoading) {
  2521. this.loadDeps_();
  2522. }
  2523. }
  2524. };
  2525. /**
  2526. * Loads any queued dependencies until they are all loaded or paused.
  2527. *
  2528. * @private
  2529. */
  2530. goog.DebugLoader_.prototype.loadDeps_ = function() {
  2531. var loader = this;
  2532. var paused = this.paused_;
  2533. while (this.depsToLoad_.length && !paused) {
  2534. (function() {
  2535. var loadCallDone = false;
  2536. var dep = loader.depsToLoad_.shift();
  2537. var loaded = false;
  2538. loader.loading_(dep);
  2539. var controller = {
  2540. pause: function() {
  2541. if (loadCallDone) {
  2542. throw new Error('Cannot call pause after the call to load.');
  2543. } else {
  2544. paused = true;
  2545. }
  2546. },
  2547. resume: function() {
  2548. if (loadCallDone) {
  2549. loader.resume_();
  2550. } else {
  2551. // Some dep called pause and then resume in the same load call.
  2552. // Just keep running this same loop.
  2553. paused = false;
  2554. }
  2555. },
  2556. loaded: function() {
  2557. if (loaded) {
  2558. throw new Error('Double call to loaded.');
  2559. }
  2560. loaded = true;
  2561. loader.loaded_(dep);
  2562. },
  2563. pending: function() {
  2564. // Defensive copy.
  2565. var pending = [];
  2566. for (var i = 0; i < loader.loadingDeps_.length; i++) {
  2567. pending.push(loader.loadingDeps_[i]);
  2568. }
  2569. return pending;
  2570. },
  2571. /**
  2572. * @param {goog.ModuleType} type
  2573. */
  2574. setModuleState: function(type) {
  2575. goog.moduleLoaderState_ = {
  2576. type: type,
  2577. moduleName: '',
  2578. declareLegacyNamespace: false
  2579. };
  2580. },
  2581. /** @type {function(string, string, string=)} */
  2582. registerEs6ModuleExports: function(
  2583. path, exports, opt_closureNamespace) {
  2584. if (opt_closureNamespace) {
  2585. goog.loadedModules_[opt_closureNamespace] = {
  2586. exports: exports,
  2587. type: goog.ModuleType.ES6,
  2588. moduleId: opt_closureNamespace || ''
  2589. };
  2590. }
  2591. },
  2592. /** @type {function(string, ?)} */
  2593. registerGoogModuleExports: function(moduleId, exports) {
  2594. goog.loadedModules_[moduleId] = {
  2595. exports: exports,
  2596. type: goog.ModuleType.GOOG,
  2597. moduleId: moduleId
  2598. };
  2599. },
  2600. clearModuleState: function() {
  2601. goog.moduleLoaderState_ = null;
  2602. },
  2603. defer: function(callback) {
  2604. if (loadCallDone) {
  2605. throw new Error(
  2606. 'Cannot register with defer after the call to load.');
  2607. }
  2608. loader.defer_(dep, callback);
  2609. },
  2610. areDepsLoaded: function() {
  2611. return loader.areDepsLoaded_(dep.requires);
  2612. }
  2613. };
  2614. try {
  2615. dep.load(controller);
  2616. } finally {
  2617. loadCallDone = true;
  2618. }
  2619. })();
  2620. }
  2621. if (paused) {
  2622. this.pause_();
  2623. }
  2624. };
  2625. /** @private */
  2626. goog.DebugLoader_.prototype.pause_ = function() {
  2627. this.paused_ = true;
  2628. };
  2629. /** @private */
  2630. goog.DebugLoader_.prototype.resume_ = function() {
  2631. if (this.paused_) {
  2632. this.paused_ = false;
  2633. this.loadDeps_();
  2634. }
  2635. };
  2636. /**
  2637. * Marks the given dependency as loading (load has been called but it has not
  2638. * yet marked itself as finished). Useful for dependencies that want to know
  2639. * what else is loading. Example: goog.modules cannot eval if there are
  2640. * loading dependencies.
  2641. *
  2642. * @param {!goog.Dependency} dep
  2643. * @private
  2644. */
  2645. goog.DebugLoader_.prototype.loading_ = function(dep) {
  2646. this.loadingDeps_.push(dep);
  2647. };
  2648. /**
  2649. * Marks the given dependency as having finished loading and being available
  2650. * for require.
  2651. *
  2652. * @param {!goog.Dependency} dep
  2653. * @private
  2654. */
  2655. goog.DebugLoader_.prototype.loaded_ = function(dep) {
  2656. for (var i = 0; i < this.loadingDeps_.length; i++) {
  2657. if (this.loadingDeps_[i] == dep) {
  2658. this.loadingDeps_.splice(i, 1);
  2659. break;
  2660. }
  2661. }
  2662. for (var i = 0; i < this.deferredQueue_.length; i++) {
  2663. if (this.deferredQueue_[i] == dep.path) {
  2664. this.deferredQueue_.splice(i, 1);
  2665. break;
  2666. }
  2667. }
  2668. if (this.loadingDeps_.length == this.deferredQueue_.length &&
  2669. !this.depsToLoad_.length) {
  2670. // Something has asked to load these, but they may not be directly
  2671. // required again later, so load them now that we know we're done loading
  2672. // everything else. e.g. a goog module entry point.
  2673. while (this.deferredQueue_.length) {
  2674. this.requested(this.deferredQueue_.shift(), true);
  2675. }
  2676. }
  2677. dep.loaded();
  2678. };
  2679. /**
  2680. * @param {!Array<string>} pathsOrIds
  2681. * @return {boolean}
  2682. * @private
  2683. */
  2684. goog.DebugLoader_.prototype.areDepsLoaded_ = function(pathsOrIds) {
  2685. for (var i = 0; i < pathsOrIds.length; i++) {
  2686. var path = this.getPathFromDeps_(pathsOrIds[i]);
  2687. if (!path ||
  2688. (!(path in this.deferredCallbacks_) &&
  2689. !goog.isProvided_(pathsOrIds[i]))) {
  2690. return false;
  2691. }
  2692. }
  2693. return true;
  2694. };
  2695. /**
  2696. * @param {string} absPathOrId
  2697. * @return {?string}
  2698. * @private
  2699. */
  2700. goog.DebugLoader_.prototype.getPathFromDeps_ = function(absPathOrId) {
  2701. if (absPathOrId in this.idToPath_) {
  2702. return this.idToPath_[absPathOrId];
  2703. } else if (absPathOrId in this.dependencies_) {
  2704. return absPathOrId;
  2705. } else {
  2706. return null;
  2707. }
  2708. };
  2709. /**
  2710. * @param {!goog.Dependency} dependency
  2711. * @param {!Function} callback
  2712. * @private
  2713. */
  2714. goog.DebugLoader_.prototype.defer_ = function(dependency, callback) {
  2715. this.deferredCallbacks_[dependency.path] = callback;
  2716. this.deferredQueue_.push(dependency.path);
  2717. };
  2718. /**
  2719. * Interface for goog.Dependency implementations to have some control over
  2720. * loading of dependencies.
  2721. *
  2722. * @record
  2723. */
  2724. goog.LoadController = function() {};
  2725. /**
  2726. * Tells the controller to halt loading of more dependencies.
  2727. */
  2728. goog.LoadController.prototype.pause = function() {};
  2729. /**
  2730. * Tells the controller to resume loading of more dependencies if paused.
  2731. */
  2732. goog.LoadController.prototype.resume = function() {};
  2733. /**
  2734. * Tells the controller that this dependency has finished loading.
  2735. *
  2736. * This causes this to be removed from pending() and any load callbacks to
  2737. * fire.
  2738. */
  2739. goog.LoadController.prototype.loaded = function() {};
  2740. /**
  2741. * List of dependencies on which load has been called but which have not
  2742. * called loaded on their controller. This includes the current dependency.
  2743. *
  2744. * @return {!Array<!goog.Dependency>}
  2745. */
  2746. goog.LoadController.prototype.pending = function() {};
  2747. /**
  2748. * Registers an object as an ES6 module's exports so that goog.modules may
  2749. * require it by path.
  2750. *
  2751. * @param {string} path Full path of the module.
  2752. * @param {?} exports
  2753. * @param {string=} opt_closureNamespace Closure namespace to associate with
  2754. * this module.
  2755. */
  2756. goog.LoadController.prototype.registerEs6ModuleExports = function(
  2757. path, exports, opt_closureNamespace) {};
  2758. /**
  2759. * Sets the current module state.
  2760. *
  2761. * @param {goog.ModuleType} type Type of module.
  2762. */
  2763. goog.LoadController.prototype.setModuleState = function(type) {};
  2764. /**
  2765. * Clears the current module state.
  2766. */
  2767. goog.LoadController.prototype.clearModuleState = function() {};
  2768. /**
  2769. * Registers a callback to call once the dependency is actually requested
  2770. * via goog.require + all of the immediate dependencies have been loaded or
  2771. * all other files have been loaded. Allows for lazy loading until
  2772. * require'd without pausing dependency loading, which is needed on old IE.
  2773. *
  2774. * @param {!Function} callback
  2775. */
  2776. goog.LoadController.prototype.defer = function(callback) {};
  2777. /**
  2778. * @return {boolean}
  2779. */
  2780. goog.LoadController.prototype.areDepsLoaded = function() {};
  2781. /**
  2782. * Basic super class for all dependencies Closure Library can load.
  2783. *
  2784. * This default implementation is designed to load untranspiled, non-module
  2785. * scripts in a web broswer.
  2786. *
  2787. * For transpiled non-goog.module files {@see goog.TranspiledDependency}.
  2788. * For goog.modules see {@see goog.GoogModuleDependency}.
  2789. * For untranspiled ES6 modules {@see goog.Es6ModuleDependency}.
  2790. *
  2791. * @param {string} path Absolute path of this script.
  2792. * @param {string} relativePath Path of this script relative to goog.basePath.
  2793. * @param {!Array<string>} provides goog.provided or goog.module symbols
  2794. * in this file.
  2795. * @param {!Array<string>} requires goog symbols or relative paths to Closure
  2796. * this depends on.
  2797. * @param {!Object<string, string>} loadFlags
  2798. * @struct @constructor
  2799. */
  2800. goog.Dependency = function(
  2801. path, relativePath, provides, requires, loadFlags) {
  2802. /** @const */
  2803. this.path = path;
  2804. /** @const */
  2805. this.relativePath = relativePath;
  2806. /** @const */
  2807. this.provides = provides;
  2808. /** @const */
  2809. this.requires = requires;
  2810. /** @const */
  2811. this.loadFlags = loadFlags;
  2812. /** @private {boolean} */
  2813. this.loaded_ = false;
  2814. /** @private {!Array<function()>} */
  2815. this.loadCallbacks_ = [];
  2816. };
  2817. /**
  2818. * @return {string} The pathname part of this dependency's path if it is a
  2819. * URI.
  2820. */
  2821. goog.Dependency.prototype.getPathName = function() {
  2822. var pathName = this.path;
  2823. var protocolIndex = pathName.indexOf('://');
  2824. if (protocolIndex >= 0) {
  2825. pathName = pathName.substring(protocolIndex + 3);
  2826. var slashIndex = pathName.indexOf('/');
  2827. if (slashIndex >= 0) {
  2828. pathName = pathName.substring(slashIndex + 1);
  2829. }
  2830. }
  2831. return pathName;
  2832. };
  2833. /**
  2834. * @param {function()} callback Callback to fire as soon as this has loaded.
  2835. * @final
  2836. */
  2837. goog.Dependency.prototype.onLoad = function(callback) {
  2838. if (this.loaded_) {
  2839. callback();
  2840. } else {
  2841. this.loadCallbacks_.push(callback);
  2842. }
  2843. };
  2844. /**
  2845. * Marks this dependency as loaded and fires any callbacks registered with
  2846. * onLoad.
  2847. * @final
  2848. */
  2849. goog.Dependency.prototype.loaded = function() {
  2850. this.loaded_ = true;
  2851. var callbacks = this.loadCallbacks_;
  2852. this.loadCallbacks_ = [];
  2853. for (var i = 0; i < callbacks.length; i++) {
  2854. callbacks[i]();
  2855. }
  2856. };
  2857. /**
  2858. * Whether or not document.written / appended script tags should be deferred.
  2859. *
  2860. * @private {boolean}
  2861. */
  2862. goog.Dependency.defer_ = false;
  2863. /**
  2864. * Map of script ready / state change callbacks. Old IE cannot handle putting
  2865. * these properties on goog.global.
  2866. *
  2867. * @private @const {!Object<string, function(?):undefined>}
  2868. */
  2869. goog.Dependency.callbackMap_ = {};
  2870. /**
  2871. * @param {function(...?):?} callback
  2872. * @return {string}
  2873. * @private
  2874. */
  2875. goog.Dependency.registerCallback_ = function(callback) {
  2876. var key = Math.random().toString(32);
  2877. goog.Dependency.callbackMap_[key] = callback;
  2878. return key;
  2879. };
  2880. /**
  2881. * @param {string} key
  2882. * @private
  2883. */
  2884. goog.Dependency.unregisterCallback_ = function(key) {
  2885. delete goog.Dependency.callbackMap_[key];
  2886. };
  2887. /**
  2888. * @param {string} key
  2889. * @param {...?} var_args
  2890. * @private
  2891. * @suppress {unusedPrivateMembers}
  2892. */
  2893. goog.Dependency.callback_ = function(key, var_args) {
  2894. if (key in goog.Dependency.callbackMap_) {
  2895. var callback = goog.Dependency.callbackMap_[key];
  2896. var args = [];
  2897. for (var i = 1; i < arguments.length; i++) {
  2898. args.push(arguments[i]);
  2899. }
  2900. callback.apply(undefined, args);
  2901. } else {
  2902. var errorMessage = 'Callback key ' + key +
  2903. ' does not exist (was base.js loaded more than once?).';
  2904. throw Error(errorMessage);
  2905. }
  2906. };
  2907. /**
  2908. * Starts loading this dependency. This dependency can pause loading if it
  2909. * needs to and resume it later via the controller interface.
  2910. *
  2911. * When this is loaded it should call controller.loaded(). Note that this will
  2912. * end up calling the loaded method of this dependency; there is no need to
  2913. * call it explicitly.
  2914. *
  2915. * @param {!goog.LoadController} controller
  2916. */
  2917. goog.Dependency.prototype.load = function(controller) {
  2918. if (goog.global.CLOSURE_IMPORT_SCRIPT) {
  2919. if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {
  2920. controller.loaded();
  2921. } else {
  2922. controller.pause();
  2923. }
  2924. return;
  2925. }
  2926. if (!goog.inHtmlDocument_()) {
  2927. goog.logToConsole_(
  2928. 'Cannot use default debug loader outside of HTML documents.');
  2929. if (this.relativePath == 'deps.js') {
  2930. // Some old code is relying on base.js auto loading deps.js failing with
  2931. // no error before later setting CLOSURE_IMPORT_SCRIPT.
  2932. // CLOSURE_IMPORT_SCRIPT should be set *before* base.js is loaded, or
  2933. // CLOSURE_NO_DEPS set to true.
  2934. goog.logToConsole_(
  2935. 'Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, ' +
  2936. 'or setting CLOSURE_NO_DEPS to true.');
  2937. controller.loaded();
  2938. } else {
  2939. controller.pause();
  2940. }
  2941. return;
  2942. }
  2943. /** @type {!HTMLDocument} */
  2944. var doc = goog.global.document;
  2945. // If the user tries to require a new symbol after document load,
  2946. // something has gone terribly wrong. Doing a document.write would
  2947. // wipe out the page. This does not apply to the CSP-compliant method
  2948. // of writing script tags.
  2949. if (doc.readyState == 'complete' &&
  2950. !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {
  2951. // Certain test frameworks load base.js multiple times, which tries
  2952. // to write deps.js each time. If that happens, just fail silently.
  2953. // These frameworks wipe the page between each load of base.js, so this
  2954. // is OK.
  2955. var isDeps = /\bdeps.js$/.test(this.path);
  2956. if (isDeps) {
  2957. controller.loaded();
  2958. return;
  2959. } else {
  2960. throw Error('Cannot write "' + this.path + '" after document load');
  2961. }
  2962. }
  2963. if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&
  2964. goog.isDocumentLoading_()) {
  2965. var key = goog.Dependency.registerCallback_(function(script) {
  2966. if (!goog.DebugLoader_.IS_OLD_IE_ || script.readyState == 'complete') {
  2967. goog.Dependency.unregisterCallback_(key);
  2968. controller.loaded();
  2969. }
  2970. });
  2971. var nonceAttr = !goog.DebugLoader_.IS_OLD_IE_ && goog.getScriptNonce() ?
  2972. ' nonce="' + goog.getScriptNonce() + '"' :
  2973. '';
  2974. var event =
  2975. goog.DebugLoader_.IS_OLD_IE_ ? 'onreadystatechange' : 'onload';
  2976. var defer = goog.Dependency.defer_ ? 'defer' : '';
  2977. doc.write(
  2978. '<script src="' + this.path + '" ' + event +
  2979. '="goog.Dependency.callback_(\'' + key +
  2980. '\', this)" type="text/javascript" ' + defer + nonceAttr + '><' +
  2981. '/script>');
  2982. } else {
  2983. var scriptEl =
  2984. /** @type {!HTMLScriptElement} */ (doc.createElement('script'));
  2985. scriptEl.defer = goog.Dependency.defer_;
  2986. scriptEl.async = false;
  2987. scriptEl.type = 'text/javascript';
  2988. // If CSP nonces are used, propagate them to dynamically created scripts.
  2989. // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.
  2990. var nonce = goog.getScriptNonce();
  2991. if (nonce) {
  2992. scriptEl.setAttribute('nonce', nonce);
  2993. }
  2994. if (goog.DebugLoader_.IS_OLD_IE_) {
  2995. // Execution order is not guaranteed on old IE, halt loading and write
  2996. // these scripts one at a time, after each loads.
  2997. controller.pause();
  2998. scriptEl.onreadystatechange = function() {
  2999. if (scriptEl.readyState == 'loaded' ||
  3000. scriptEl.readyState == 'complete') {
  3001. controller.loaded();
  3002. controller.resume();
  3003. }
  3004. };
  3005. } else {
  3006. scriptEl.onload = function() {
  3007. scriptEl.onload = null;
  3008. controller.loaded();
  3009. };
  3010. }
  3011. scriptEl.src = this.path;
  3012. doc.head.appendChild(scriptEl);
  3013. }
  3014. };
  3015. /**
  3016. * @param {string} path Absolute path of this script.
  3017. * @param {string} relativePath Path of this script relative to goog.basePath.
  3018. * @param {!Array<string>} provides Should be an empty array.
  3019. * TODO(johnplaisted) add support for adding closure namespaces to ES6
  3020. * modules for interop purposes.
  3021. * @param {!Array<string>} requires goog symbols or relative paths to Closure
  3022. * this depends on.
  3023. * @param {!Object<string, string>} loadFlags
  3024. * @struct @constructor
  3025. * @extends {goog.Dependency}
  3026. */
  3027. goog.Es6ModuleDependency = function(
  3028. path, relativePath, provides, requires, loadFlags) {
  3029. goog.Es6ModuleDependency.base(
  3030. this, 'constructor', path, relativePath, provides, requires, loadFlags);
  3031. };
  3032. goog.inherits(goog.Es6ModuleDependency, goog.Dependency);
  3033. /** @override */
  3034. goog.Es6ModuleDependency.prototype.load = function(controller) {
  3035. if (goog.global.CLOSURE_IMPORT_SCRIPT) {
  3036. if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {
  3037. controller.loaded();
  3038. } else {
  3039. controller.pause();
  3040. }
  3041. return;
  3042. }
  3043. if (!goog.inHtmlDocument_()) {
  3044. goog.logToConsole_(
  3045. 'Cannot use default debug loader outside of HTML documents.');
  3046. controller.pause();
  3047. return;
  3048. }
  3049. /** @type {!HTMLDocument} */
  3050. var doc = goog.global.document;
  3051. var dep = this;
  3052. // TODO(johnplaisted): Does document.writing really speed up anything? Any
  3053. // difference between this and just waiting for interactive mode and then
  3054. // appending?
  3055. function write(src, contents) {
  3056. if (contents) {
  3057. doc.write(
  3058. '<script type="module" crossorigin>' + contents + '</' +
  3059. 'script>');
  3060. } else {
  3061. doc.write(
  3062. '<script type="module" crossorigin src="' + src + '"></' +
  3063. 'script>');
  3064. }
  3065. }
  3066. function append(src, contents) {
  3067. var scriptEl =
  3068. /** @type {!HTMLScriptElement} */ (doc.createElement('script'));
  3069. scriptEl.defer = true;
  3070. scriptEl.async = false;
  3071. scriptEl.type = 'module';
  3072. scriptEl.setAttribute('crossorigin', true);
  3073. // If CSP nonces are used, propagate them to dynamically created scripts.
  3074. // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.
  3075. var nonce = goog.getScriptNonce();
  3076. if (nonce) {
  3077. scriptEl.setAttribute('nonce', nonce);
  3078. }
  3079. if (contents) {
  3080. scriptEl.textContent = contents;
  3081. } else {
  3082. scriptEl.src = src;
  3083. }
  3084. doc.head.appendChild(scriptEl);
  3085. }
  3086. var create;
  3087. if (goog.isDocumentLoading_()) {
  3088. create = write;
  3089. // We can ONLY call document.write if we are guaranteed that any
  3090. // non-module script tags document.written after this are deferred.
  3091. // Small optimization, in theory document.writing is faster.
  3092. goog.Dependency.defer_ = true;
  3093. } else {
  3094. create = append;
  3095. }
  3096. // Write 4 separate tags here:
  3097. // 1) Sets the module state at the correct time (just before execution).
  3098. // 2) A src node for this, which just hopefully lets the browser load it a
  3099. // little early (no need to parse #3).
  3100. // 3) Import the module and register it.
  3101. // 4) Clear the module state at the correct time. Guarnteed to run even
  3102. // if there is an error in the module (#3 will not run if there is an
  3103. // error in the module).
  3104. var beforeKey = goog.Dependency.registerCallback_(function() {
  3105. goog.Dependency.unregisterCallback_(beforeKey);
  3106. controller.setModuleState(goog.ModuleType.ES6);
  3107. });
  3108. create(undefined, 'goog.Dependency.callback_("' + beforeKey + '")');
  3109. // TODO(johnplaisted): Does this really speed up anything?
  3110. create(this.path, undefined);
  3111. var registerKey = goog.Dependency.registerCallback_(function(exports) {
  3112. goog.Dependency.unregisterCallback_(registerKey);
  3113. controller.registerEs6ModuleExports(
  3114. dep.path, exports, goog.moduleLoaderState_.moduleName);
  3115. });
  3116. create(
  3117. undefined,
  3118. 'import * as m from "' + this.path + '"; goog.Dependency.callback_("' +
  3119. registerKey + '", m)');
  3120. var afterKey = goog.Dependency.registerCallback_(function() {
  3121. goog.Dependency.unregisterCallback_(afterKey);
  3122. controller.clearModuleState();
  3123. controller.loaded();
  3124. });
  3125. create(undefined, 'goog.Dependency.callback_("' + afterKey + '")');
  3126. };
  3127. /**
  3128. * Superclass of any dependency that needs to be loaded into memory,
  3129. * transformed, and then eval'd (goog.modules and transpiled files).
  3130. *
  3131. * @param {string} path Absolute path of this script.
  3132. * @param {string} relativePath Path of this script relative to goog.basePath.
  3133. * @param {!Array<string>} provides goog.provided or goog.module symbols
  3134. * in this file.
  3135. * @param {!Array<string>} requires goog symbols or relative paths to Closure
  3136. * this depends on.
  3137. * @param {!Object<string, string>} loadFlags
  3138. * @struct @constructor @abstract
  3139. * @extends {goog.Dependency}
  3140. */
  3141. goog.TransformedDependency = function(
  3142. path, relativePath, provides, requires, loadFlags) {
  3143. goog.TransformedDependency.base(
  3144. this, 'constructor', path, relativePath, provides, requires, loadFlags);
  3145. /** @private {?string} */
  3146. this.contents_ = null;
  3147. /**
  3148. * Whether to lazily make the synchronous XHR (when goog.require'd) or make
  3149. * the synchronous XHR when initially loading. On FireFox 61 there is a bug
  3150. * where an ES6 module cannot make a synchronous XHR (rather, it can, but if
  3151. * it does then no other ES6 modules will load after).
  3152. *
  3153. * tl;dr we lazy load due to bugs on older browsers and eager load due to
  3154. * bugs on newer ones.
  3155. *
  3156. * https://bugzilla.mozilla.org/show_bug.cgi?id=1477090
  3157. *
  3158. * @private @const {boolean}
  3159. */
  3160. this.lazyFetch_ = !goog.inHtmlDocument_() ||
  3161. !('noModule' in goog.global.document.createElement('script'));
  3162. };
  3163. goog.inherits(goog.TransformedDependency, goog.Dependency);
  3164. /** @override */
  3165. goog.TransformedDependency.prototype.load = function(controller) {
  3166. var dep = this;
  3167. function fetch() {
  3168. dep.contents_ = goog.loadFileSync_(dep.path);
  3169. if (dep.contents_) {
  3170. dep.contents_ = dep.transform(dep.contents_);
  3171. if (dep.contents_) {
  3172. dep.contents_ += '\n//# sourceURL=' + dep.path;
  3173. }
  3174. }
  3175. }
  3176. if (goog.global.CLOSURE_IMPORT_SCRIPT) {
  3177. fetch();
  3178. if (this.contents_ &&
  3179. goog.global.CLOSURE_IMPORT_SCRIPT('', this.contents_)) {
  3180. this.contents_ = null;
  3181. controller.loaded();
  3182. } else {
  3183. controller.pause();
  3184. }
  3185. return;
  3186. }
  3187. var isEs6 = this.loadFlags['module'] == goog.ModuleType.ES6;
  3188. if (!this.lazyFetch_) {
  3189. fetch();
  3190. }
  3191. function load() {
  3192. if (dep.lazyFetch_) {
  3193. fetch();
  3194. }
  3195. if (!dep.contents_) {
  3196. // loadFileSync_ or transform are responsible. Assume they logged an
  3197. // error.
  3198. return;
  3199. }
  3200. if (isEs6) {
  3201. controller.setModuleState(goog.ModuleType.ES6);
  3202. }
  3203. var namespace;
  3204. try {
  3205. var contents = dep.contents_;
  3206. dep.contents_ = null;
  3207. goog.globalEval(contents);
  3208. if (isEs6) {
  3209. namespace = goog.moduleLoaderState_.moduleName;
  3210. }
  3211. } finally {
  3212. if (isEs6) {
  3213. controller.clearModuleState();
  3214. }
  3215. }
  3216. if (isEs6) {
  3217. // Due to circular dependencies this may not be available for require
  3218. // right now.
  3219. goog.global['$jscomp']['require']['ensure'](
  3220. [dep.getPathName()], function() {
  3221. controller.registerEs6ModuleExports(
  3222. dep.path,
  3223. goog.global['$jscomp']['require'](dep.getPathName()),
  3224. namespace);
  3225. });
  3226. }
  3227. controller.loaded();
  3228. }
  3229. // Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all
  3230. // events. If we fetched now and then document.write'd the contents the
  3231. // document.write would be an eval and would execute too soon! Instead write
  3232. // a script tag to fetch and eval synchronously at the correct time.
  3233. function fetchInOwnScriptThenLoad() {
  3234. /** @type {!HTMLDocument} */
  3235. var doc = goog.global.document;
  3236. var key = goog.Dependency.registerCallback_(function() {
  3237. goog.Dependency.unregisterCallback_(key);
  3238. load();
  3239. });
  3240. doc.write(
  3241. '<script type="text/javascript">' +
  3242. goog.protectScriptTag_('goog.Dependency.callback_("' + key + '");') +
  3243. '</' +
  3244. 'script>');
  3245. }
  3246. // If one thing is pending it is this.
  3247. var anythingElsePending = controller.pending().length > 1;
  3248. // If anything else is loading we need to lazy load due to bugs in old IE.
  3249. // Specifically script tags with src and script tags with contents could
  3250. // execute out of order if document.write is used, so we cannot use
  3251. // document.write. Do not pause here; it breaks old IE as well.
  3252. var useOldIeWorkAround =
  3253. anythingElsePending && goog.DebugLoader_.IS_OLD_IE_;
  3254. // Additionally if we are meant to defer scripts but the page is still
  3255. // loading (e.g. an ES6 module is loading) then also defer. Or if we are
  3256. // meant to defer and anything else is pending then defer (those may be
  3257. // scripts that did not need transformation and are just script tags with
  3258. // defer set to true, and we need to evaluate after that deferred script).
  3259. var needsAsyncLoading = goog.Dependency.defer_ &&
  3260. (anythingElsePending || goog.isDocumentLoading_());
  3261. if (useOldIeWorkAround || needsAsyncLoading) {
  3262. // Note that we only defer when we have to rather than 100% of the time.
  3263. // Always defering would work, but then in theory the order of
  3264. // goog.require calls would then matter. We want to enforce that most of
  3265. // the time the order of the require calls does not matter.
  3266. controller.defer(function() {
  3267. load();
  3268. });
  3269. return;
  3270. }
  3271. // TODO(johnplaisted): Externs are missing onreadystatechange for
  3272. // HTMLDocument.
  3273. /** @type {?} */
  3274. var doc = goog.global.document;
  3275. var isInternetExplorer =
  3276. goog.inHtmlDocument_() && 'ActiveXObject' in goog.global;
  3277. // Don't delay in any version of IE. There's bug around this that will
  3278. // cause out of order script execution. This means that on older IE ES6
  3279. // modules will load too early (while the document is still loading + the
  3280. // dom is not available). The other option is to load too late (when the
  3281. // document is complete and the onload even will never fire). This seems
  3282. // to be the lesser of two evils as scripts already act like the former.
  3283. if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&
  3284. !isInternetExplorer) {
  3285. goog.Dependency.defer_ = true;
  3286. // Transpiled ES6 modules still need to load like regular ES6 modules,
  3287. // aka only after the document is interactive.
  3288. controller.pause();
  3289. var oldCallback = doc.onreadystatechange;
  3290. doc.onreadystatechange = function() {
  3291. if (doc.readyState == 'interactive') {
  3292. doc.onreadystatechange = oldCallback;
  3293. load();
  3294. controller.resume();
  3295. }
  3296. if (goog.isFunction(oldCallback)) {
  3297. oldCallback.apply(undefined, arguments);
  3298. }
  3299. };
  3300. } else {
  3301. // Always eval on old IE.
  3302. if (goog.DebugLoader_.IS_OLD_IE_ || !goog.inHtmlDocument_() ||
  3303. !goog.isDocumentLoading_()) {
  3304. load();
  3305. } else {
  3306. fetchInOwnScriptThenLoad();
  3307. }
  3308. }
  3309. };
  3310. /**
  3311. * @param {string} contents
  3312. * @return {string}
  3313. * @abstract
  3314. */
  3315. goog.TransformedDependency.prototype.transform = function(contents) {};
  3316. /**
  3317. * Any non-goog.module dependency which needs to be transpiled before eval.
  3318. *
  3319. * @param {string} path Absolute path of this script.
  3320. * @param {string} relativePath Path of this script relative to goog.basePath.
  3321. * @param {!Array<string>} provides goog.provided or goog.module symbols
  3322. * in this file.
  3323. * @param {!Array<string>} requires goog symbols or relative paths to Closure
  3324. * this depends on.
  3325. * @param {!Object<string, string>} loadFlags
  3326. * @param {!goog.Transpiler} transpiler
  3327. * @struct @constructor
  3328. * @extends {goog.TransformedDependency}
  3329. */
  3330. goog.TranspiledDependency = function(
  3331. path, relativePath, provides, requires, loadFlags, transpiler) {
  3332. goog.TranspiledDependency.base(
  3333. this, 'constructor', path, relativePath, provides, requires, loadFlags);
  3334. /** @protected @const*/
  3335. this.transpiler = transpiler;
  3336. };
  3337. goog.inherits(goog.TranspiledDependency, goog.TransformedDependency);
  3338. /** @override */
  3339. goog.TranspiledDependency.prototype.transform = function(contents) {
  3340. // Transpile with the pathname so that ES6 modules are domain agnostic.
  3341. return this.transpiler.transpile(contents, this.getPathName());
  3342. };
  3343. /**
  3344. * A goog.module, transpiled or not. Will always perform some minimal
  3345. * transformation even when not transpiled to wrap in a goog.loadModule
  3346. * statement.
  3347. *
  3348. * @param {string} path Absolute path of this script.
  3349. * @param {string} relativePath Path of this script relative to goog.basePath.
  3350. * @param {!Array<string>} provides goog.provided or goog.module symbols
  3351. * in this file.
  3352. * @param {!Array<string>} requires goog symbols or relative paths to Closure
  3353. * this depends on.
  3354. * @param {!Object<string, string>} loadFlags
  3355. * @param {boolean} needsTranspile
  3356. * @param {!goog.Transpiler} transpiler
  3357. * @struct @constructor
  3358. * @extends {goog.TransformedDependency}
  3359. */
  3360. goog.GoogModuleDependency = function(
  3361. path, relativePath, provides, requires, loadFlags, needsTranspile,
  3362. transpiler) {
  3363. goog.GoogModuleDependency.base(
  3364. this, 'constructor', path, relativePath, provides, requires, loadFlags);
  3365. /** @private @const */
  3366. this.needsTranspile_ = needsTranspile;
  3367. /** @private @const */
  3368. this.transpiler_ = transpiler;
  3369. };
  3370. goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);
  3371. /** @override */
  3372. goog.GoogModuleDependency.prototype.transform = function(contents) {
  3373. if (this.needsTranspile_) {
  3374. contents = this.transpiler_.transpile(contents, this.getPathName());
  3375. }
  3376. if (!goog.LOAD_MODULE_USING_EVAL || !goog.isDef(goog.global.JSON)) {
  3377. return '' +
  3378. 'goog.loadModule(function(exports) {' +
  3379. '"use strict";' + contents +
  3380. '\n' + // terminate any trailing single line comment.
  3381. ';return exports' +
  3382. '});' +
  3383. '\n//# sourceURL=' + this.path + '\n';
  3384. } else {
  3385. return '' +
  3386. 'goog.loadModule(' +
  3387. goog.global.JSON.stringify(
  3388. contents + '\n//# sourceURL=' + this.path + '\n') +
  3389. ');';
  3390. }
  3391. };
  3392. /**
  3393. * Whether the browser is IE9 or earlier, which needs special handling
  3394. * for deferred modules.
  3395. * @const @private {boolean}
  3396. */
  3397. goog.DebugLoader_.IS_OLD_IE_ = !!(
  3398. !goog.global.atob && goog.global.document && goog.global.document['all']);
  3399. /**
  3400. * @param {string} relPath
  3401. * @param {!Array<string>|undefined} provides
  3402. * @param {!Array<string>} requires
  3403. * @param {boolean|!Object<string>=} opt_loadFlags
  3404. * @see goog.addDependency
  3405. */
  3406. goog.DebugLoader_.prototype.addDependency = function(
  3407. relPath, provides, requires, opt_loadFlags) {
  3408. provides = provides || [];
  3409. relPath = relPath.replace(/\\/g, '/');
  3410. var path = goog.normalizePath_(goog.basePath + relPath);
  3411. if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') {
  3412. opt_loadFlags = opt_loadFlags ? {'module': goog.ModuleType.GOOG} : {};
  3413. }
  3414. var dep = this.factory_.createDependency(
  3415. path, relPath, provides, requires, opt_loadFlags,
  3416. goog.transpiler_.needsTranspile(
  3417. opt_loadFlags['lang'] || 'es3', opt_loadFlags['module']));
  3418. this.dependencies_[path] = dep;
  3419. for (var i = 0; i < provides.length; i++) {
  3420. this.idToPath_[provides[i]] = path;
  3421. }
  3422. this.idToPath_[relPath] = path;
  3423. };
  3424. /**
  3425. * Creates goog.Dependency instances for the debug loader to load.
  3426. *
  3427. * Should be overridden to have the debug loader use custom subclasses of
  3428. * goog.Dependency.
  3429. *
  3430. * @param {!goog.Transpiler} transpiler
  3431. * @struct @constructor
  3432. */
  3433. goog.DependencyFactory = function(transpiler) {
  3434. /** @protected @const */
  3435. this.transpiler = transpiler;
  3436. };
  3437. /**
  3438. * @param {string} path Absolute path of the file.
  3439. * @param {string} relativePath Path relative to closure’s base.js.
  3440. * @param {!Array<string>} provides Array of provided goog.provide/module ids.
  3441. * @param {!Array<string>} requires Array of required goog.provide/module /
  3442. * relative ES6 module paths.
  3443. * @param {!Object<string, string>} loadFlags
  3444. * @param {boolean} needsTranspile True if the file needs to be transpiled
  3445. * per the goog.Transpiler.
  3446. * @return {!goog.Dependency}
  3447. */
  3448. goog.DependencyFactory.prototype.createDependency = function(
  3449. path, relativePath, provides, requires, loadFlags, needsTranspile) {
  3450. if (loadFlags['module'] == goog.ModuleType.GOOG) {
  3451. return new goog.GoogModuleDependency(
  3452. path, relativePath, provides, requires, loadFlags, needsTranspile,
  3453. this.transpiler);
  3454. } else if (needsTranspile) {
  3455. return new goog.TranspiledDependency(
  3456. path, relativePath, provides, requires, loadFlags, this.transpiler);
  3457. } else {
  3458. if (loadFlags['module'] == goog.ModuleType.ES6) {
  3459. return new goog.Es6ModuleDependency(
  3460. path, relativePath, provides, requires, loadFlags);
  3461. } else {
  3462. return new goog.Dependency(
  3463. path, relativePath, provides, requires, loadFlags);
  3464. }
  3465. }
  3466. };
  3467. /** @private @const */
  3468. goog.debugLoader_ = new goog.DebugLoader_();
  3469. /**
  3470. * Loads the Closure Dependency file.
  3471. *
  3472. * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base
  3473. * loaded, setDependencyFactory called, and then this called. i.e. allows
  3474. * custom loading of the deps file.
  3475. */
  3476. goog.loadClosureDeps = function() {
  3477. goog.debugLoader_.loadClosureDeps();
  3478. };
  3479. /**
  3480. * Sets the dependency factory, which can be used to create custom
  3481. * goog.Dependency implementations to control how dependencies are loaded.
  3482. *
  3483. * Note: if you wish to call this function and provide your own implemnetation
  3484. * it is a wise idea to set CLOSURE_NO_DEPS to true, otherwise the dependency
  3485. * file and all of its goog.addDependency calls will use the default factory.
  3486. * You can call goog.loadClosureDeps to load the Closure dependency file
  3487. * later, after your factory is injected.
  3488. *
  3489. * @param {!goog.DependencyFactory} factory
  3490. */
  3491. goog.setDependencyFactory = function(factory) {
  3492. goog.debugLoader_.setDependencyFactory(factory);
  3493. };
  3494. if (!goog.global.CLOSURE_NO_DEPS) {
  3495. goog.debugLoader_.loadClosureDeps();
  3496. }
  3497. /**
  3498. * Bootstraps the given namespaces and calls the callback once they are
  3499. * available either via goog.require. This is a replacement for using
  3500. * `goog.require` to bootstrap Closure JavaScript. Previously a `goog.require`
  3501. * in an HTML file would guarantee that the require'd namespace was available
  3502. * in the next immediate script tag. With ES6 modules this no longer a
  3503. * guarantee.
  3504. *
  3505. * @param {!Array<string>} namespaces
  3506. * @param {function(): ?} callback Function to call once all the namespaces
  3507. * have loaded. Always called asynchronously.
  3508. */
  3509. goog.bootstrap = function(namespaces, callback) {
  3510. goog.debugLoader_.bootstrap(namespaces, callback);
  3511. };
  3512. }