base.js 130 KB

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