index.node.esm.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  1. /**
  2. * @license
  3. * Copyright 2017 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /**
  18. * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.
  19. */
  20. const CONSTANTS = {
  21. /**
  22. * @define {boolean} Whether this is the client Node.js SDK.
  23. */
  24. NODE_CLIENT: false,
  25. /**
  26. * @define {boolean} Whether this is the Admin Node.js SDK.
  27. */
  28. NODE_ADMIN: false,
  29. /**
  30. * Firebase SDK Version
  31. */
  32. SDK_VERSION: '${JSCORE_VERSION}'
  33. };
  34. /**
  35. * @license
  36. * Copyright 2017 Google LLC
  37. *
  38. * Licensed under the Apache License, Version 2.0 (the "License");
  39. * you may not use this file except in compliance with the License.
  40. * You may obtain a copy of the License at
  41. *
  42. * http://www.apache.org/licenses/LICENSE-2.0
  43. *
  44. * Unless required by applicable law or agreed to in writing, software
  45. * distributed under the License is distributed on an "AS IS" BASIS,
  46. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  47. * See the License for the specific language governing permissions and
  48. * limitations under the License.
  49. */
  50. /**
  51. * Throws an error if the provided assertion is falsy
  52. */
  53. const assert = function (assertion, message) {
  54. if (!assertion) {
  55. throw assertionError(message);
  56. }
  57. };
  58. /**
  59. * Returns an Error object suitable for throwing.
  60. */
  61. const assertionError = function (message) {
  62. return new Error('Firebase Database (' +
  63. CONSTANTS.SDK_VERSION +
  64. ') INTERNAL ASSERT FAILED: ' +
  65. message);
  66. };
  67. /**
  68. * @license
  69. * Copyright 2017 Google LLC
  70. *
  71. * Licensed under the Apache License, Version 2.0 (the "License");
  72. * you may not use this file except in compliance with the License.
  73. * You may obtain a copy of the License at
  74. *
  75. * http://www.apache.org/licenses/LICENSE-2.0
  76. *
  77. * Unless required by applicable law or agreed to in writing, software
  78. * distributed under the License is distributed on an "AS IS" BASIS,
  79. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  80. * See the License for the specific language governing permissions and
  81. * limitations under the License.
  82. */
  83. const stringToByteArray$1 = function (str) {
  84. // TODO(user): Use native implementations if/when available
  85. const out = [];
  86. let p = 0;
  87. for (let i = 0; i < str.length; i++) {
  88. let c = str.charCodeAt(i);
  89. if (c < 128) {
  90. out[p++] = c;
  91. }
  92. else if (c < 2048) {
  93. out[p++] = (c >> 6) | 192;
  94. out[p++] = (c & 63) | 128;
  95. }
  96. else if ((c & 0xfc00) === 0xd800 &&
  97. i + 1 < str.length &&
  98. (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
  99. // Surrogate Pair
  100. c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
  101. out[p++] = (c >> 18) | 240;
  102. out[p++] = ((c >> 12) & 63) | 128;
  103. out[p++] = ((c >> 6) & 63) | 128;
  104. out[p++] = (c & 63) | 128;
  105. }
  106. else {
  107. out[p++] = (c >> 12) | 224;
  108. out[p++] = ((c >> 6) & 63) | 128;
  109. out[p++] = (c & 63) | 128;
  110. }
  111. }
  112. return out;
  113. };
  114. /**
  115. * Turns an array of numbers into the string given by the concatenation of the
  116. * characters to which the numbers correspond.
  117. * @param bytes Array of numbers representing characters.
  118. * @return Stringification of the array.
  119. */
  120. const byteArrayToString = function (bytes) {
  121. // TODO(user): Use native implementations if/when available
  122. const out = [];
  123. let pos = 0, c = 0;
  124. while (pos < bytes.length) {
  125. const c1 = bytes[pos++];
  126. if (c1 < 128) {
  127. out[c++] = String.fromCharCode(c1);
  128. }
  129. else if (c1 > 191 && c1 < 224) {
  130. const c2 = bytes[pos++];
  131. out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
  132. }
  133. else if (c1 > 239 && c1 < 365) {
  134. // Surrogate Pair
  135. const c2 = bytes[pos++];
  136. const c3 = bytes[pos++];
  137. const c4 = bytes[pos++];
  138. const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -
  139. 0x10000;
  140. out[c++] = String.fromCharCode(0xd800 + (u >> 10));
  141. out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
  142. }
  143. else {
  144. const c2 = bytes[pos++];
  145. const c3 = bytes[pos++];
  146. out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  147. }
  148. }
  149. return out.join('');
  150. };
  151. // We define it as an object literal instead of a class because a class compiled down to es5 can't
  152. // be treeshaked. https://github.com/rollup/rollup/issues/1691
  153. // Static lookup maps, lazily populated by init_()
  154. // TODO(dlarocque): Define this as a class, since we no longer target ES5.
  155. const base64 = {
  156. /**
  157. * Maps bytes to characters.
  158. */
  159. byteToCharMap_: null,
  160. /**
  161. * Maps characters to bytes.
  162. */
  163. charToByteMap_: null,
  164. /**
  165. * Maps bytes to websafe characters.
  166. * @private
  167. */
  168. byteToCharMapWebSafe_: null,
  169. /**
  170. * Maps websafe characters to bytes.
  171. * @private
  172. */
  173. charToByteMapWebSafe_: null,
  174. /**
  175. * Our default alphabet, shared between
  176. * ENCODED_VALS and ENCODED_VALS_WEBSAFE
  177. */
  178. ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',
  179. /**
  180. * Our default alphabet. Value 64 (=) is special; it means "nothing."
  181. */
  182. get ENCODED_VALS() {
  183. return this.ENCODED_VALS_BASE + '+/=';
  184. },
  185. /**
  186. * Our websafe alphabet.
  187. */
  188. get ENCODED_VALS_WEBSAFE() {
  189. return this.ENCODED_VALS_BASE + '-_.';
  190. },
  191. /**
  192. * Whether this browser supports the atob and btoa functions. This extension
  193. * started at Mozilla but is now implemented by many browsers. We use the
  194. * ASSUME_* variables to avoid pulling in the full useragent detection library
  195. * but still allowing the standard per-browser compilations.
  196. *
  197. */
  198. HAS_NATIVE_SUPPORT: typeof atob === 'function',
  199. /**
  200. * Base64-encode an array of bytes.
  201. *
  202. * @param input An array of bytes (numbers with
  203. * value in [0, 255]) to encode.
  204. * @param webSafe Boolean indicating we should use the
  205. * alternative alphabet.
  206. * @return The base64 encoded string.
  207. */
  208. encodeByteArray(input, webSafe) {
  209. if (!Array.isArray(input)) {
  210. throw Error('encodeByteArray takes an array as a parameter');
  211. }
  212. this.init_();
  213. const byteToCharMap = webSafe
  214. ? this.byteToCharMapWebSafe_
  215. : this.byteToCharMap_;
  216. const output = [];
  217. for (let i = 0; i < input.length; i += 3) {
  218. const byte1 = input[i];
  219. const haveByte2 = i + 1 < input.length;
  220. const byte2 = haveByte2 ? input[i + 1] : 0;
  221. const haveByte3 = i + 2 < input.length;
  222. const byte3 = haveByte3 ? input[i + 2] : 0;
  223. const outByte1 = byte1 >> 2;
  224. const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
  225. let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);
  226. let outByte4 = byte3 & 0x3f;
  227. if (!haveByte3) {
  228. outByte4 = 64;
  229. if (!haveByte2) {
  230. outByte3 = 64;
  231. }
  232. }
  233. output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
  234. }
  235. return output.join('');
  236. },
  237. /**
  238. * Base64-encode a string.
  239. *
  240. * @param input A string to encode.
  241. * @param webSafe If true, we should use the
  242. * alternative alphabet.
  243. * @return The base64 encoded string.
  244. */
  245. encodeString(input, webSafe) {
  246. // Shortcut for Mozilla browsers that implement
  247. // a native base64 encoder in the form of "btoa/atob"
  248. if (this.HAS_NATIVE_SUPPORT && !webSafe) {
  249. return btoa(input);
  250. }
  251. return this.encodeByteArray(stringToByteArray$1(input), webSafe);
  252. },
  253. /**
  254. * Base64-decode a string.
  255. *
  256. * @param input to decode.
  257. * @param webSafe True if we should use the
  258. * alternative alphabet.
  259. * @return string representing the decoded value.
  260. */
  261. decodeString(input, webSafe) {
  262. // Shortcut for Mozilla browsers that implement
  263. // a native base64 encoder in the form of "btoa/atob"
  264. if (this.HAS_NATIVE_SUPPORT && !webSafe) {
  265. return atob(input);
  266. }
  267. return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
  268. },
  269. /**
  270. * Base64-decode a string.
  271. *
  272. * In base-64 decoding, groups of four characters are converted into three
  273. * bytes. If the encoder did not apply padding, the input length may not
  274. * be a multiple of 4.
  275. *
  276. * In this case, the last group will have fewer than 4 characters, and
  277. * padding will be inferred. If the group has one or two characters, it decodes
  278. * to one byte. If the group has three characters, it decodes to two bytes.
  279. *
  280. * @param input Input to decode.
  281. * @param webSafe True if we should use the web-safe alphabet.
  282. * @return bytes representing the decoded value.
  283. */
  284. decodeStringToByteArray(input, webSafe) {
  285. this.init_();
  286. const charToByteMap = webSafe
  287. ? this.charToByteMapWebSafe_
  288. : this.charToByteMap_;
  289. const output = [];
  290. for (let i = 0; i < input.length;) {
  291. const byte1 = charToByteMap[input.charAt(i++)];
  292. const haveByte2 = i < input.length;
  293. const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
  294. ++i;
  295. const haveByte3 = i < input.length;
  296. const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;
  297. ++i;
  298. const haveByte4 = i < input.length;
  299. const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;
  300. ++i;
  301. if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
  302. throw new DecodeBase64StringError();
  303. }
  304. const outByte1 = (byte1 << 2) | (byte2 >> 4);
  305. output.push(outByte1);
  306. if (byte3 !== 64) {
  307. const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);
  308. output.push(outByte2);
  309. if (byte4 !== 64) {
  310. const outByte3 = ((byte3 << 6) & 0xc0) | byte4;
  311. output.push(outByte3);
  312. }
  313. }
  314. }
  315. return output;
  316. },
  317. /**
  318. * Lazy static initialization function. Called before
  319. * accessing any of the static map variables.
  320. * @private
  321. */
  322. init_() {
  323. if (!this.byteToCharMap_) {
  324. this.byteToCharMap_ = {};
  325. this.charToByteMap_ = {};
  326. this.byteToCharMapWebSafe_ = {};
  327. this.charToByteMapWebSafe_ = {};
  328. // We want quick mappings back and forth, so we precompute two maps.
  329. for (let i = 0; i < this.ENCODED_VALS.length; i++) {
  330. this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);
  331. this.charToByteMap_[this.byteToCharMap_[i]] = i;
  332. this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);
  333. this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;
  334. // Be forgiving when decoding and correctly decode both encodings.
  335. if (i >= this.ENCODED_VALS_BASE.length) {
  336. this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;
  337. this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;
  338. }
  339. }
  340. }
  341. }
  342. };
  343. /**
  344. * An error encountered while decoding base64 string.
  345. */
  346. class DecodeBase64StringError extends Error {
  347. constructor() {
  348. super(...arguments);
  349. this.name = 'DecodeBase64StringError';
  350. }
  351. }
  352. /**
  353. * URL-safe base64 encoding
  354. */
  355. const base64Encode = function (str) {
  356. const utf8Bytes = stringToByteArray$1(str);
  357. return base64.encodeByteArray(utf8Bytes, true);
  358. };
  359. /**
  360. * URL-safe base64 encoding (without "." padding in the end).
  361. * e.g. Used in JSON Web Token (JWT) parts.
  362. */
  363. const base64urlEncodeWithoutPadding = function (str) {
  364. // Use base64url encoding and remove padding in the end (dot characters).
  365. return base64Encode(str).replace(/\./g, '');
  366. };
  367. /**
  368. * URL-safe base64 decoding
  369. *
  370. * NOTE: DO NOT use the global atob() function - it does NOT support the
  371. * base64Url variant encoding.
  372. *
  373. * @param str To be decoded
  374. * @return Decoded result, if possible
  375. */
  376. const base64Decode = function (str) {
  377. try {
  378. return base64.decodeString(str, true);
  379. }
  380. catch (e) {
  381. console.error('base64Decode failed: ', e);
  382. }
  383. return null;
  384. };
  385. /**
  386. * @license
  387. * Copyright 2017 Google LLC
  388. *
  389. * Licensed under the Apache License, Version 2.0 (the "License");
  390. * you may not use this file except in compliance with the License.
  391. * You may obtain a copy of the License at
  392. *
  393. * http://www.apache.org/licenses/LICENSE-2.0
  394. *
  395. * Unless required by applicable law or agreed to in writing, software
  396. * distributed under the License is distributed on an "AS IS" BASIS,
  397. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  398. * See the License for the specific language governing permissions and
  399. * limitations under the License.
  400. */
  401. /**
  402. * Do a deep-copy of basic JavaScript Objects or Arrays.
  403. */
  404. function deepCopy(value) {
  405. return deepExtend(undefined, value);
  406. }
  407. /**
  408. * Copy properties from source to target (recursively allows extension
  409. * of Objects and Arrays). Scalar values in the target are over-written.
  410. * If target is undefined, an object of the appropriate type will be created
  411. * (and returned).
  412. *
  413. * We recursively copy all child properties of plain Objects in the source- so
  414. * that namespace- like dictionaries are merged.
  415. *
  416. * Note that the target can be a function, in which case the properties in
  417. * the source Object are copied onto it as static properties of the Function.
  418. *
  419. * Note: we don't merge __proto__ to prevent prototype pollution
  420. */
  421. function deepExtend(target, source) {
  422. if (!(source instanceof Object)) {
  423. return source;
  424. }
  425. switch (source.constructor) {
  426. case Date:
  427. // Treat Dates like scalars; if the target date object had any child
  428. // properties - they will be lost!
  429. const dateValue = source;
  430. return new Date(dateValue.getTime());
  431. case Object:
  432. if (target === undefined) {
  433. target = {};
  434. }
  435. break;
  436. case Array:
  437. // Always copy the array source and overwrite the target.
  438. target = [];
  439. break;
  440. default:
  441. // Not a plain Object - treat it as a scalar.
  442. return source;
  443. }
  444. for (const prop in source) {
  445. // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202
  446. if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {
  447. continue;
  448. }
  449. target[prop] = deepExtend(target[prop], source[prop]);
  450. }
  451. return target;
  452. }
  453. function isValidKey(key) {
  454. return key !== '__proto__';
  455. }
  456. /**
  457. * @license
  458. * Copyright 2022 Google LLC
  459. *
  460. * Licensed under the Apache License, Version 2.0 (the "License");
  461. * you may not use this file except in compliance with the License.
  462. * You may obtain a copy of the License at
  463. *
  464. * http://www.apache.org/licenses/LICENSE-2.0
  465. *
  466. * Unless required by applicable law or agreed to in writing, software
  467. * distributed under the License is distributed on an "AS IS" BASIS,
  468. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  469. * See the License for the specific language governing permissions and
  470. * limitations under the License.
  471. */
  472. /**
  473. * Polyfill for `globalThis` object.
  474. * @returns the `globalThis` object for the given environment.
  475. * @public
  476. */
  477. function getGlobal() {
  478. if (typeof self !== 'undefined') {
  479. return self;
  480. }
  481. if (typeof window !== 'undefined') {
  482. return window;
  483. }
  484. if (typeof global !== 'undefined') {
  485. return global;
  486. }
  487. throw new Error('Unable to locate global object.');
  488. }
  489. /**
  490. * @license
  491. * Copyright 2022 Google LLC
  492. *
  493. * Licensed under the Apache License, Version 2.0 (the "License");
  494. * you may not use this file except in compliance with the License.
  495. * You may obtain a copy of the License at
  496. *
  497. * http://www.apache.org/licenses/LICENSE-2.0
  498. *
  499. * Unless required by applicable law or agreed to in writing, software
  500. * distributed under the License is distributed on an "AS IS" BASIS,
  501. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  502. * See the License for the specific language governing permissions and
  503. * limitations under the License.
  504. */
  505. const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;
  506. /**
  507. * Attempt to read defaults from a JSON string provided to
  508. * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in
  509. * process(.)env(.)__FIREBASE_DEFAULTS_PATH__
  510. * The dots are in parens because certain compilers (Vite?) cannot
  511. * handle seeing that variable in comments.
  512. * See https://github.com/firebase/firebase-js-sdk/issues/6838
  513. */
  514. const getDefaultsFromEnvVariable = () => {
  515. if (typeof process === 'undefined' || typeof process.env === 'undefined') {
  516. return;
  517. }
  518. const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;
  519. if (defaultsJsonString) {
  520. return JSON.parse(defaultsJsonString);
  521. }
  522. };
  523. const getDefaultsFromCookie = () => {
  524. if (typeof document === 'undefined') {
  525. return;
  526. }
  527. let match;
  528. try {
  529. match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);
  530. }
  531. catch (e) {
  532. // Some environments such as Angular Universal SSR have a
  533. // `document` object but error on accessing `document.cookie`.
  534. return;
  535. }
  536. const decoded = match && base64Decode(match[1]);
  537. return decoded && JSON.parse(decoded);
  538. };
  539. /**
  540. * Get the __FIREBASE_DEFAULTS__ object. It checks in order:
  541. * (1) if such an object exists as a property of `globalThis`
  542. * (2) if such an object was provided on a shell environment variable
  543. * (3) if such an object exists in a cookie
  544. * @public
  545. */
  546. const getDefaults = () => {
  547. try {
  548. return (getDefaultsFromGlobal() ||
  549. getDefaultsFromEnvVariable() ||
  550. getDefaultsFromCookie());
  551. }
  552. catch (e) {
  553. /**
  554. * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due
  555. * to any environment case we have not accounted for. Log to
  556. * info instead of swallowing so we can find these unknown cases
  557. * and add paths for them if needed.
  558. */
  559. console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);
  560. return;
  561. }
  562. };
  563. /**
  564. * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object
  565. * for the given product.
  566. * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available
  567. * @public
  568. */
  569. const getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };
  570. /**
  571. * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object
  572. * for the given product.
  573. * @returns a pair of hostname and port like `["::1", 4000]` if available
  574. * @public
  575. */
  576. const getDefaultEmulatorHostnameAndPort = (productName) => {
  577. const host = getDefaultEmulatorHost(productName);
  578. if (!host) {
  579. return undefined;
  580. }
  581. const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.
  582. if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {
  583. throw new Error(`Invalid host ${host} with no separate hostname and port!`);
  584. }
  585. // eslint-disable-next-line no-restricted-globals
  586. const port = parseInt(host.substring(separatorIndex + 1), 10);
  587. if (host[0] === '[') {
  588. // Bracket-quoted `[ipv6addr]:port` => return "ipv6addr" (without brackets).
  589. return [host.substring(1, separatorIndex - 1), port];
  590. }
  591. else {
  592. return [host.substring(0, separatorIndex), port];
  593. }
  594. };
  595. /**
  596. * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.
  597. * @public
  598. */
  599. const getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };
  600. /**
  601. * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties
  602. * prefixed by "_")
  603. * @public
  604. */
  605. const getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };
  606. /**
  607. * @license
  608. * Copyright 2017 Google LLC
  609. *
  610. * Licensed under the Apache License, Version 2.0 (the "License");
  611. * you may not use this file except in compliance with the License.
  612. * You may obtain a copy of the License at
  613. *
  614. * http://www.apache.org/licenses/LICENSE-2.0
  615. *
  616. * Unless required by applicable law or agreed to in writing, software
  617. * distributed under the License is distributed on an "AS IS" BASIS,
  618. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  619. * See the License for the specific language governing permissions and
  620. * limitations under the License.
  621. */
  622. class Deferred {
  623. constructor() {
  624. this.reject = () => { };
  625. this.resolve = () => { };
  626. this.promise = new Promise((resolve, reject) => {
  627. this.resolve = resolve;
  628. this.reject = reject;
  629. });
  630. }
  631. /**
  632. * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around
  633. * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
  634. * and returns a node-style callback which will resolve or reject the Deferred's promise.
  635. */
  636. wrapCallback(callback) {
  637. return (error, value) => {
  638. if (error) {
  639. this.reject(error);
  640. }
  641. else {
  642. this.resolve(value);
  643. }
  644. if (typeof callback === 'function') {
  645. // Attaching noop handler just in case developer wasn't expecting
  646. // promises
  647. this.promise.catch(() => { });
  648. // Some of our callbacks don't expect a value and our own tests
  649. // assert that the parameter length is 1
  650. if (callback.length === 1) {
  651. callback(error);
  652. }
  653. else {
  654. callback(error, value);
  655. }
  656. }
  657. };
  658. }
  659. }
  660. /**
  661. * @license
  662. * Copyright 2021 Google LLC
  663. *
  664. * Licensed under the Apache License, Version 2.0 (the "License");
  665. * you may not use this file except in compliance with the License.
  666. * You may obtain a copy of the License at
  667. *
  668. * http://www.apache.org/licenses/LICENSE-2.0
  669. *
  670. * Unless required by applicable law or agreed to in writing, software
  671. * distributed under the License is distributed on an "AS IS" BASIS,
  672. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  673. * See the License for the specific language governing permissions and
  674. * limitations under the License.
  675. */
  676. function createMockUserToken(token, projectId) {
  677. if (token.uid) {
  678. throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');
  679. }
  680. // Unsecured JWTs use "none" as the algorithm.
  681. const header = {
  682. alg: 'none',
  683. type: 'JWT'
  684. };
  685. const project = projectId || 'demo-project';
  686. const iat = token.iat || 0;
  687. const sub = token.sub || token.user_id;
  688. if (!sub) {
  689. throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");
  690. }
  691. const payload = Object.assign({
  692. // Set all required fields to decent defaults
  693. iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {
  694. sign_in_provider: 'custom',
  695. identities: {}
  696. } }, token);
  697. // Unsecured JWTs use the empty string as a signature.
  698. const signature = '';
  699. return [
  700. base64urlEncodeWithoutPadding(JSON.stringify(header)),
  701. base64urlEncodeWithoutPadding(JSON.stringify(payload)),
  702. signature
  703. ].join('.');
  704. }
  705. /**
  706. * @license
  707. * Copyright 2017 Google LLC
  708. *
  709. * Licensed under the Apache License, Version 2.0 (the "License");
  710. * you may not use this file except in compliance with the License.
  711. * You may obtain a copy of the License at
  712. *
  713. * http://www.apache.org/licenses/LICENSE-2.0
  714. *
  715. * Unless required by applicable law or agreed to in writing, software
  716. * distributed under the License is distributed on an "AS IS" BASIS,
  717. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  718. * See the License for the specific language governing permissions and
  719. * limitations under the License.
  720. */
  721. /**
  722. * Returns navigator.userAgent string or '' if it's not defined.
  723. * @return user agent string
  724. */
  725. function getUA() {
  726. if (typeof navigator !== 'undefined' &&
  727. typeof navigator['userAgent'] === 'string') {
  728. return navigator['userAgent'];
  729. }
  730. else {
  731. return '';
  732. }
  733. }
  734. /**
  735. * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.
  736. *
  737. * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap
  738. * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally
  739. * wait for a callback.
  740. */
  741. function isMobileCordova() {
  742. return (typeof window !== 'undefined' &&
  743. // @ts-ignore Setting up an broadly applicable index signature for Window
  744. // just to deal with this case would probably be a bad idea.
  745. !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&
  746. /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));
  747. }
  748. /**
  749. * Detect Node.js.
  750. *
  751. * @return true if Node.js environment is detected or specified.
  752. */
  753. // Node detection logic from: https://github.com/iliakan/detect-node/
  754. function isNode() {
  755. var _a;
  756. const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;
  757. if (forceEnvironment === 'node') {
  758. return true;
  759. }
  760. else if (forceEnvironment === 'browser') {
  761. return false;
  762. }
  763. try {
  764. return (Object.prototype.toString.call(global.process) === '[object process]');
  765. }
  766. catch (e) {
  767. return false;
  768. }
  769. }
  770. /**
  771. * Detect Browser Environment.
  772. * Note: This will return true for certain test frameworks that are incompletely
  773. * mimicking a browser, and should not lead to assuming all browser APIs are
  774. * available.
  775. */
  776. function isBrowser() {
  777. return typeof window !== 'undefined' || isWebWorker();
  778. }
  779. /**
  780. * Detect Web Worker context.
  781. */
  782. function isWebWorker() {
  783. return (typeof WorkerGlobalScope !== 'undefined' &&
  784. typeof self !== 'undefined' &&
  785. self instanceof WorkerGlobalScope);
  786. }
  787. /**
  788. * Detect Cloudflare Worker context.
  789. */
  790. function isCloudflareWorker() {
  791. return (typeof navigator !== 'undefined' &&
  792. navigator.userAgent === 'Cloudflare-Workers');
  793. }
  794. function isBrowserExtension() {
  795. const runtime = typeof chrome === 'object'
  796. ? chrome.runtime
  797. : typeof browser === 'object'
  798. ? browser.runtime
  799. : undefined;
  800. return typeof runtime === 'object' && runtime.id !== undefined;
  801. }
  802. /**
  803. * Detect React Native.
  804. *
  805. * @return true if ReactNative environment is detected.
  806. */
  807. function isReactNative() {
  808. return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');
  809. }
  810. /** Detects Electron apps. */
  811. function isElectron() {
  812. return getUA().indexOf('Electron/') >= 0;
  813. }
  814. /** Detects Internet Explorer. */
  815. function isIE() {
  816. const ua = getUA();
  817. return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;
  818. }
  819. /** Detects Universal Windows Platform apps. */
  820. function isUWP() {
  821. return getUA().indexOf('MSAppHost/') >= 0;
  822. }
  823. /**
  824. * Detect whether the current SDK build is the Node version.
  825. *
  826. * @return true if it's the Node SDK build.
  827. */
  828. function isNodeSdk() {
  829. return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;
  830. }
  831. /** Returns true if we are running in Safari. */
  832. function isSafari() {
  833. return (!isNode() &&
  834. !!navigator.userAgent &&
  835. navigator.userAgent.includes('Safari') &&
  836. !navigator.userAgent.includes('Chrome'));
  837. }
  838. /**
  839. * This method checks if indexedDB is supported by current browser/service worker context
  840. * @return true if indexedDB is supported by current browser/service worker context
  841. */
  842. function isIndexedDBAvailable() {
  843. try {
  844. return typeof indexedDB === 'object';
  845. }
  846. catch (e) {
  847. return false;
  848. }
  849. }
  850. /**
  851. * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject
  852. * if errors occur during the database open operation.
  853. *
  854. * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox
  855. * private browsing)
  856. */
  857. function validateIndexedDBOpenable() {
  858. return new Promise((resolve, reject) => {
  859. try {
  860. let preExist = true;
  861. const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';
  862. const request = self.indexedDB.open(DB_CHECK_NAME);
  863. request.onsuccess = () => {
  864. request.result.close();
  865. // delete database only when it doesn't pre-exist
  866. if (!preExist) {
  867. self.indexedDB.deleteDatabase(DB_CHECK_NAME);
  868. }
  869. resolve(true);
  870. };
  871. request.onupgradeneeded = () => {
  872. preExist = false;
  873. };
  874. request.onerror = () => {
  875. var _a;
  876. reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');
  877. };
  878. }
  879. catch (error) {
  880. reject(error);
  881. }
  882. });
  883. }
  884. /**
  885. *
  886. * This method checks whether cookie is enabled within current browser
  887. * @return true if cookie is enabled within current browser
  888. */
  889. function areCookiesEnabled() {
  890. if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {
  891. return false;
  892. }
  893. return true;
  894. }
  895. /**
  896. * @license
  897. * Copyright 2017 Google LLC
  898. *
  899. * Licensed under the Apache License, Version 2.0 (the "License");
  900. * you may not use this file except in compliance with the License.
  901. * You may obtain a copy of the License at
  902. *
  903. * http://www.apache.org/licenses/LICENSE-2.0
  904. *
  905. * Unless required by applicable law or agreed to in writing, software
  906. * distributed under the License is distributed on an "AS IS" BASIS,
  907. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  908. * See the License for the specific language governing permissions and
  909. * limitations under the License.
  910. */
  911. /**
  912. * @fileoverview Standardized Firebase Error.
  913. *
  914. * Usage:
  915. *
  916. * // TypeScript string literals for type-safe codes
  917. * type Err =
  918. * 'unknown' |
  919. * 'object-not-found'
  920. * ;
  921. *
  922. * // Closure enum for type-safe error codes
  923. * // at-enum {string}
  924. * var Err = {
  925. * UNKNOWN: 'unknown',
  926. * OBJECT_NOT_FOUND: 'object-not-found',
  927. * }
  928. *
  929. * let errors: Map<Err, string> = {
  930. * 'generic-error': "Unknown error",
  931. * 'file-not-found': "Could not find file: {$file}",
  932. * };
  933. *
  934. * // Type-safe function - must pass a valid error code as param.
  935. * let error = new ErrorFactory<Err>('service', 'Service', errors);
  936. *
  937. * ...
  938. * throw error.create(Err.GENERIC);
  939. * ...
  940. * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});
  941. * ...
  942. * // Service: Could not file file: foo.txt (service/file-not-found).
  943. *
  944. * catch (e) {
  945. * assert(e.message === "Could not find file: foo.txt.");
  946. * if ((e as FirebaseError)?.code === 'service/file-not-found') {
  947. * console.log("Could not read file: " + e['file']);
  948. * }
  949. * }
  950. */
  951. const ERROR_NAME = 'FirebaseError';
  952. // Based on code from:
  953. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
  954. class FirebaseError extends Error {
  955. constructor(
  956. /** The error code for this error. */
  957. code, message,
  958. /** Custom data for this error. */
  959. customData) {
  960. super(message);
  961. this.code = code;
  962. this.customData = customData;
  963. /** The custom name for all FirebaseErrors. */
  964. this.name = ERROR_NAME;
  965. // Fix For ES5
  966. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  967. // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
  968. // which we can now use since we no longer target ES5.
  969. Object.setPrototypeOf(this, FirebaseError.prototype);
  970. // Maintains proper stack trace for where our error was thrown.
  971. // Only available on V8.
  972. if (Error.captureStackTrace) {
  973. Error.captureStackTrace(this, ErrorFactory.prototype.create);
  974. }
  975. }
  976. }
  977. class ErrorFactory {
  978. constructor(service, serviceName, errors) {
  979. this.service = service;
  980. this.serviceName = serviceName;
  981. this.errors = errors;
  982. }
  983. create(code, ...data) {
  984. const customData = data[0] || {};
  985. const fullCode = `${this.service}/${code}`;
  986. const template = this.errors[code];
  987. const message = template ? replaceTemplate(template, customData) : 'Error';
  988. // Service Name: Error message (service/code).
  989. const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
  990. const error = new FirebaseError(fullCode, fullMessage, customData);
  991. return error;
  992. }
  993. }
  994. function replaceTemplate(template, data) {
  995. return template.replace(PATTERN, (_, key) => {
  996. const value = data[key];
  997. return value != null ? String(value) : `<${key}?>`;
  998. });
  999. }
  1000. const PATTERN = /\{\$([^}]+)}/g;
  1001. /**
  1002. * @license
  1003. * Copyright 2017 Google LLC
  1004. *
  1005. * Licensed under the Apache License, Version 2.0 (the "License");
  1006. * you may not use this file except in compliance with the License.
  1007. * You may obtain a copy of the License at
  1008. *
  1009. * http://www.apache.org/licenses/LICENSE-2.0
  1010. *
  1011. * Unless required by applicable law or agreed to in writing, software
  1012. * distributed under the License is distributed on an "AS IS" BASIS,
  1013. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1014. * See the License for the specific language governing permissions and
  1015. * limitations under the License.
  1016. */
  1017. /**
  1018. * Evaluates a JSON string into a javascript object.
  1019. *
  1020. * @param {string} str A string containing JSON.
  1021. * @return {*} The javascript object representing the specified JSON.
  1022. */
  1023. function jsonEval(str) {
  1024. return JSON.parse(str);
  1025. }
  1026. /**
  1027. * Returns JSON representing a javascript object.
  1028. * @param {*} data JavaScript object to be stringified.
  1029. * @return {string} The JSON contents of the object.
  1030. */
  1031. function stringify(data) {
  1032. return JSON.stringify(data);
  1033. }
  1034. /**
  1035. * @license
  1036. * Copyright 2017 Google LLC
  1037. *
  1038. * Licensed under the Apache License, Version 2.0 (the "License");
  1039. * you may not use this file except in compliance with the License.
  1040. * You may obtain a copy of the License at
  1041. *
  1042. * http://www.apache.org/licenses/LICENSE-2.0
  1043. *
  1044. * Unless required by applicable law or agreed to in writing, software
  1045. * distributed under the License is distributed on an "AS IS" BASIS,
  1046. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1047. * See the License for the specific language governing permissions and
  1048. * limitations under the License.
  1049. */
  1050. /**
  1051. * Decodes a Firebase auth. token into constituent parts.
  1052. *
  1053. * Notes:
  1054. * - May return with invalid / incomplete claims if there's no native base64 decoding support.
  1055. * - Doesn't check if the token is actually valid.
  1056. */
  1057. const decode = function (token) {
  1058. let header = {}, claims = {}, data = {}, signature = '';
  1059. try {
  1060. const parts = token.split('.');
  1061. header = jsonEval(base64Decode(parts[0]) || '');
  1062. claims = jsonEval(base64Decode(parts[1]) || '');
  1063. signature = parts[2];
  1064. data = claims['d'] || {};
  1065. delete claims['d'];
  1066. }
  1067. catch (e) { }
  1068. return {
  1069. header,
  1070. claims,
  1071. data,
  1072. signature
  1073. };
  1074. };
  1075. /**
  1076. * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the
  1077. * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.
  1078. *
  1079. * Notes:
  1080. * - May return a false negative if there's no native base64 decoding support.
  1081. * - Doesn't check if the token is actually valid.
  1082. */
  1083. const isValidTimestamp = function (token) {
  1084. const claims = decode(token).claims;
  1085. const now = Math.floor(new Date().getTime() / 1000);
  1086. let validSince = 0, validUntil = 0;
  1087. if (typeof claims === 'object') {
  1088. if (claims.hasOwnProperty('nbf')) {
  1089. validSince = claims['nbf'];
  1090. }
  1091. else if (claims.hasOwnProperty('iat')) {
  1092. validSince = claims['iat'];
  1093. }
  1094. if (claims.hasOwnProperty('exp')) {
  1095. validUntil = claims['exp'];
  1096. }
  1097. else {
  1098. // token will expire after 24h by default
  1099. validUntil = validSince + 86400;
  1100. }
  1101. }
  1102. return (!!now &&
  1103. !!validSince &&
  1104. !!validUntil &&
  1105. now >= validSince &&
  1106. now <= validUntil);
  1107. };
  1108. /**
  1109. * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.
  1110. *
  1111. * Notes:
  1112. * - May return null if there's no native base64 decoding support.
  1113. * - Doesn't check if the token is actually valid.
  1114. */
  1115. const issuedAtTime = function (token) {
  1116. const claims = decode(token).claims;
  1117. if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {
  1118. return claims['iat'];
  1119. }
  1120. return null;
  1121. };
  1122. /**
  1123. * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.
  1124. *
  1125. * Notes:
  1126. * - May return a false negative if there's no native base64 decoding support.
  1127. * - Doesn't check if the token is actually valid.
  1128. */
  1129. const isValidFormat = function (token) {
  1130. const decoded = decode(token), claims = decoded.claims;
  1131. return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');
  1132. };
  1133. /**
  1134. * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.
  1135. *
  1136. * Notes:
  1137. * - May return a false negative if there's no native base64 decoding support.
  1138. * - Doesn't check if the token is actually valid.
  1139. */
  1140. const isAdmin = function (token) {
  1141. const claims = decode(token).claims;
  1142. return typeof claims === 'object' && claims['admin'] === true;
  1143. };
  1144. /**
  1145. * @license
  1146. * Copyright 2017 Google LLC
  1147. *
  1148. * Licensed under the Apache License, Version 2.0 (the "License");
  1149. * you may not use this file except in compliance with the License.
  1150. * You may obtain a copy of the License at
  1151. *
  1152. * http://www.apache.org/licenses/LICENSE-2.0
  1153. *
  1154. * Unless required by applicable law or agreed to in writing, software
  1155. * distributed under the License is distributed on an "AS IS" BASIS,
  1156. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1157. * See the License for the specific language governing permissions and
  1158. * limitations under the License.
  1159. */
  1160. function contains(obj, key) {
  1161. return Object.prototype.hasOwnProperty.call(obj, key);
  1162. }
  1163. function safeGet(obj, key) {
  1164. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1165. return obj[key];
  1166. }
  1167. else {
  1168. return undefined;
  1169. }
  1170. }
  1171. function isEmpty(obj) {
  1172. for (const key in obj) {
  1173. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1174. return false;
  1175. }
  1176. }
  1177. return true;
  1178. }
  1179. function map(obj, fn, contextObj) {
  1180. const res = {};
  1181. for (const key in obj) {
  1182. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1183. res[key] = fn.call(contextObj, obj[key], key, obj);
  1184. }
  1185. }
  1186. return res;
  1187. }
  1188. /**
  1189. * Deep equal two objects. Support Arrays and Objects.
  1190. */
  1191. function deepEqual(a, b) {
  1192. if (a === b) {
  1193. return true;
  1194. }
  1195. const aKeys = Object.keys(a);
  1196. const bKeys = Object.keys(b);
  1197. for (const k of aKeys) {
  1198. if (!bKeys.includes(k)) {
  1199. return false;
  1200. }
  1201. const aProp = a[k];
  1202. const bProp = b[k];
  1203. if (isObject(aProp) && isObject(bProp)) {
  1204. if (!deepEqual(aProp, bProp)) {
  1205. return false;
  1206. }
  1207. }
  1208. else if (aProp !== bProp) {
  1209. return false;
  1210. }
  1211. }
  1212. for (const k of bKeys) {
  1213. if (!aKeys.includes(k)) {
  1214. return false;
  1215. }
  1216. }
  1217. return true;
  1218. }
  1219. function isObject(thing) {
  1220. return thing !== null && typeof thing === 'object';
  1221. }
  1222. /**
  1223. * @license
  1224. * Copyright 2022 Google LLC
  1225. *
  1226. * Licensed under the Apache License, Version 2.0 (the "License");
  1227. * you may not use this file except in compliance with the License.
  1228. * You may obtain a copy of the License at
  1229. *
  1230. * http://www.apache.org/licenses/LICENSE-2.0
  1231. *
  1232. * Unless required by applicable law or agreed to in writing, software
  1233. * distributed under the License is distributed on an "AS IS" BASIS,
  1234. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1235. * See the License for the specific language governing permissions and
  1236. * limitations under the License.
  1237. */
  1238. /**
  1239. * Rejects if the given promise doesn't resolve in timeInMS milliseconds.
  1240. * @internal
  1241. */
  1242. function promiseWithTimeout(promise, timeInMS = 2000) {
  1243. const deferredPromise = new Deferred();
  1244. setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);
  1245. promise.then(deferredPromise.resolve, deferredPromise.reject);
  1246. return deferredPromise.promise;
  1247. }
  1248. /**
  1249. * @license
  1250. * Copyright 2017 Google LLC
  1251. *
  1252. * Licensed under the Apache License, Version 2.0 (the "License");
  1253. * you may not use this file except in compliance with the License.
  1254. * You may obtain a copy of the License at
  1255. *
  1256. * http://www.apache.org/licenses/LICENSE-2.0
  1257. *
  1258. * Unless required by applicable law or agreed to in writing, software
  1259. * distributed under the License is distributed on an "AS IS" BASIS,
  1260. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1261. * See the License for the specific language governing permissions and
  1262. * limitations under the License.
  1263. */
  1264. /**
  1265. * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a
  1266. * params object (e.g. {arg: 'val', arg2: 'val2'})
  1267. * Note: You must prepend it with ? when adding it to a URL.
  1268. */
  1269. function querystring(querystringParams) {
  1270. const params = [];
  1271. for (const [key, value] of Object.entries(querystringParams)) {
  1272. if (Array.isArray(value)) {
  1273. value.forEach(arrayVal => {
  1274. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));
  1275. });
  1276. }
  1277. else {
  1278. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  1279. }
  1280. }
  1281. return params.length ? '&' + params.join('&') : '';
  1282. }
  1283. /**
  1284. * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object
  1285. * (e.g. {arg: 'val', arg2: 'val2'})
  1286. */
  1287. function querystringDecode(querystring) {
  1288. const obj = {};
  1289. const tokens = querystring.replace(/^\?/, '').split('&');
  1290. tokens.forEach(token => {
  1291. if (token) {
  1292. const [key, value] = token.split('=');
  1293. obj[decodeURIComponent(key)] = decodeURIComponent(value);
  1294. }
  1295. });
  1296. return obj;
  1297. }
  1298. /**
  1299. * Extract the query string part of a URL, including the leading question mark (if present).
  1300. */
  1301. function extractQuerystring(url) {
  1302. const queryStart = url.indexOf('?');
  1303. if (!queryStart) {
  1304. return '';
  1305. }
  1306. const fragmentStart = url.indexOf('#', queryStart);
  1307. return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);
  1308. }
  1309. /**
  1310. * @license
  1311. * Copyright 2017 Google LLC
  1312. *
  1313. * Licensed under the Apache License, Version 2.0 (the "License");
  1314. * you may not use this file except in compliance with the License.
  1315. * You may obtain a copy of the License at
  1316. *
  1317. * http://www.apache.org/licenses/LICENSE-2.0
  1318. *
  1319. * Unless required by applicable law or agreed to in writing, software
  1320. * distributed under the License is distributed on an "AS IS" BASIS,
  1321. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1322. * See the License for the specific language governing permissions and
  1323. * limitations under the License.
  1324. */
  1325. /**
  1326. * @fileoverview SHA-1 cryptographic hash.
  1327. * Variable names follow the notation in FIPS PUB 180-3:
  1328. * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.
  1329. *
  1330. * Usage:
  1331. * var sha1 = new sha1();
  1332. * sha1.update(bytes);
  1333. * var hash = sha1.digest();
  1334. *
  1335. * Performance:
  1336. * Chrome 23: ~400 Mbit/s
  1337. * Firefox 16: ~250 Mbit/s
  1338. *
  1339. */
  1340. /**
  1341. * SHA-1 cryptographic hash constructor.
  1342. *
  1343. * The properties declared here are discussed in the above algorithm document.
  1344. * @constructor
  1345. * @final
  1346. * @struct
  1347. */
  1348. class Sha1 {
  1349. constructor() {
  1350. /**
  1351. * Holds the previous values of accumulated variables a-e in the compress_
  1352. * function.
  1353. * @private
  1354. */
  1355. this.chain_ = [];
  1356. /**
  1357. * A buffer holding the partially computed hash result.
  1358. * @private
  1359. */
  1360. this.buf_ = [];
  1361. /**
  1362. * An array of 80 bytes, each a part of the message to be hashed. Referred to
  1363. * as the message schedule in the docs.
  1364. * @private
  1365. */
  1366. this.W_ = [];
  1367. /**
  1368. * Contains data needed to pad messages less than 64 bytes.
  1369. * @private
  1370. */
  1371. this.pad_ = [];
  1372. /**
  1373. * @private {number}
  1374. */
  1375. this.inbuf_ = 0;
  1376. /**
  1377. * @private {number}
  1378. */
  1379. this.total_ = 0;
  1380. this.blockSize = 512 / 8;
  1381. this.pad_[0] = 128;
  1382. for (let i = 1; i < this.blockSize; ++i) {
  1383. this.pad_[i] = 0;
  1384. }
  1385. this.reset();
  1386. }
  1387. reset() {
  1388. this.chain_[0] = 0x67452301;
  1389. this.chain_[1] = 0xefcdab89;
  1390. this.chain_[2] = 0x98badcfe;
  1391. this.chain_[3] = 0x10325476;
  1392. this.chain_[4] = 0xc3d2e1f0;
  1393. this.inbuf_ = 0;
  1394. this.total_ = 0;
  1395. }
  1396. /**
  1397. * Internal compress helper function.
  1398. * @param buf Block to compress.
  1399. * @param offset Offset of the block in the buffer.
  1400. * @private
  1401. */
  1402. compress_(buf, offset) {
  1403. if (!offset) {
  1404. offset = 0;
  1405. }
  1406. const W = this.W_;
  1407. // get 16 big endian words
  1408. if (typeof buf === 'string') {
  1409. for (let i = 0; i < 16; i++) {
  1410. // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS
  1411. // have a bug that turns the post-increment ++ operator into pre-increment
  1412. // during JIT compilation. We have code that depends heavily on SHA-1 for
  1413. // correctness and which is affected by this bug, so I've removed all uses
  1414. // of post-increment ++ in which the result value is used. We can revert
  1415. // this change once the Safari bug
  1416. // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and
  1417. // most clients have been updated.
  1418. W[i] =
  1419. (buf.charCodeAt(offset) << 24) |
  1420. (buf.charCodeAt(offset + 1) << 16) |
  1421. (buf.charCodeAt(offset + 2) << 8) |
  1422. buf.charCodeAt(offset + 3);
  1423. offset += 4;
  1424. }
  1425. }
  1426. else {
  1427. for (let i = 0; i < 16; i++) {
  1428. W[i] =
  1429. (buf[offset] << 24) |
  1430. (buf[offset + 1] << 16) |
  1431. (buf[offset + 2] << 8) |
  1432. buf[offset + 3];
  1433. offset += 4;
  1434. }
  1435. }
  1436. // expand to 80 words
  1437. for (let i = 16; i < 80; i++) {
  1438. const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
  1439. W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;
  1440. }
  1441. let a = this.chain_[0];
  1442. let b = this.chain_[1];
  1443. let c = this.chain_[2];
  1444. let d = this.chain_[3];
  1445. let e = this.chain_[4];
  1446. let f, k;
  1447. // TODO(user): Try to unroll this loop to speed up the computation.
  1448. for (let i = 0; i < 80; i++) {
  1449. if (i < 40) {
  1450. if (i < 20) {
  1451. f = d ^ (b & (c ^ d));
  1452. k = 0x5a827999;
  1453. }
  1454. else {
  1455. f = b ^ c ^ d;
  1456. k = 0x6ed9eba1;
  1457. }
  1458. }
  1459. else {
  1460. if (i < 60) {
  1461. f = (b & c) | (d & (b | c));
  1462. k = 0x8f1bbcdc;
  1463. }
  1464. else {
  1465. f = b ^ c ^ d;
  1466. k = 0xca62c1d6;
  1467. }
  1468. }
  1469. const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;
  1470. e = d;
  1471. d = c;
  1472. c = ((b << 30) | (b >>> 2)) & 0xffffffff;
  1473. b = a;
  1474. a = t;
  1475. }
  1476. this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;
  1477. this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;
  1478. this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;
  1479. this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;
  1480. this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;
  1481. }
  1482. update(bytes, length) {
  1483. // TODO(johnlenz): tighten the function signature and remove this check
  1484. if (bytes == null) {
  1485. return;
  1486. }
  1487. if (length === undefined) {
  1488. length = bytes.length;
  1489. }
  1490. const lengthMinusBlock = length - this.blockSize;
  1491. let n = 0;
  1492. // Using local instead of member variables gives ~5% speedup on Firefox 16.
  1493. const buf = this.buf_;
  1494. let inbuf = this.inbuf_;
  1495. // The outer while loop should execute at most twice.
  1496. while (n < length) {
  1497. // When we have no data in the block to top up, we can directly process the
  1498. // input buffer (assuming it contains sufficient data). This gives ~25%
  1499. // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that
  1500. // the data is provided in large chunks (or in multiples of 64 bytes).
  1501. if (inbuf === 0) {
  1502. while (n <= lengthMinusBlock) {
  1503. this.compress_(bytes, n);
  1504. n += this.blockSize;
  1505. }
  1506. }
  1507. if (typeof bytes === 'string') {
  1508. while (n < length) {
  1509. buf[inbuf] = bytes.charCodeAt(n);
  1510. ++inbuf;
  1511. ++n;
  1512. if (inbuf === this.blockSize) {
  1513. this.compress_(buf);
  1514. inbuf = 0;
  1515. // Jump to the outer loop so we use the full-block optimization.
  1516. break;
  1517. }
  1518. }
  1519. }
  1520. else {
  1521. while (n < length) {
  1522. buf[inbuf] = bytes[n];
  1523. ++inbuf;
  1524. ++n;
  1525. if (inbuf === this.blockSize) {
  1526. this.compress_(buf);
  1527. inbuf = 0;
  1528. // Jump to the outer loop so we use the full-block optimization.
  1529. break;
  1530. }
  1531. }
  1532. }
  1533. }
  1534. this.inbuf_ = inbuf;
  1535. this.total_ += length;
  1536. }
  1537. /** @override */
  1538. digest() {
  1539. const digest = [];
  1540. let totalBits = this.total_ * 8;
  1541. // Add pad 0x80 0x00*.
  1542. if (this.inbuf_ < 56) {
  1543. this.update(this.pad_, 56 - this.inbuf_);
  1544. }
  1545. else {
  1546. this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));
  1547. }
  1548. // Add # bits.
  1549. for (let i = this.blockSize - 1; i >= 56; i--) {
  1550. this.buf_[i] = totalBits & 255;
  1551. totalBits /= 256; // Don't use bit-shifting here!
  1552. }
  1553. this.compress_(this.buf_);
  1554. let n = 0;
  1555. for (let i = 0; i < 5; i++) {
  1556. for (let j = 24; j >= 0; j -= 8) {
  1557. digest[n] = (this.chain_[i] >> j) & 255;
  1558. ++n;
  1559. }
  1560. }
  1561. return digest;
  1562. }
  1563. }
  1564. /**
  1565. * Helper to make a Subscribe function (just like Promise helps make a
  1566. * Thenable).
  1567. *
  1568. * @param executor Function which can make calls to a single Observer
  1569. * as a proxy.
  1570. * @param onNoObservers Callback when count of Observers goes to zero.
  1571. */
  1572. function createSubscribe(executor, onNoObservers) {
  1573. const proxy = new ObserverProxy(executor, onNoObservers);
  1574. return proxy.subscribe.bind(proxy);
  1575. }
  1576. /**
  1577. * Implement fan-out for any number of Observers attached via a subscribe
  1578. * function.
  1579. */
  1580. class ObserverProxy {
  1581. /**
  1582. * @param executor Function which can make calls to a single Observer
  1583. * as a proxy.
  1584. * @param onNoObservers Callback when count of Observers goes to zero.
  1585. */
  1586. constructor(executor, onNoObservers) {
  1587. this.observers = [];
  1588. this.unsubscribes = [];
  1589. this.observerCount = 0;
  1590. // Micro-task scheduling by calling task.then().
  1591. this.task = Promise.resolve();
  1592. this.finalized = false;
  1593. this.onNoObservers = onNoObservers;
  1594. // Call the executor asynchronously so subscribers that are called
  1595. // synchronously after the creation of the subscribe function
  1596. // can still receive the very first value generated in the executor.
  1597. this.task
  1598. .then(() => {
  1599. executor(this);
  1600. })
  1601. .catch(e => {
  1602. this.error(e);
  1603. });
  1604. }
  1605. next(value) {
  1606. this.forEachObserver((observer) => {
  1607. observer.next(value);
  1608. });
  1609. }
  1610. error(error) {
  1611. this.forEachObserver((observer) => {
  1612. observer.error(error);
  1613. });
  1614. this.close(error);
  1615. }
  1616. complete() {
  1617. this.forEachObserver((observer) => {
  1618. observer.complete();
  1619. });
  1620. this.close();
  1621. }
  1622. /**
  1623. * Subscribe function that can be used to add an Observer to the fan-out list.
  1624. *
  1625. * - We require that no event is sent to a subscriber synchronously to their
  1626. * call to subscribe().
  1627. */
  1628. subscribe(nextOrObserver, error, complete) {
  1629. let observer;
  1630. if (nextOrObserver === undefined &&
  1631. error === undefined &&
  1632. complete === undefined) {
  1633. throw new Error('Missing Observer.');
  1634. }
  1635. // Assemble an Observer object when passed as callback functions.
  1636. if (implementsAnyMethods(nextOrObserver, [
  1637. 'next',
  1638. 'error',
  1639. 'complete'
  1640. ])) {
  1641. observer = nextOrObserver;
  1642. }
  1643. else {
  1644. observer = {
  1645. next: nextOrObserver,
  1646. error,
  1647. complete
  1648. };
  1649. }
  1650. if (observer.next === undefined) {
  1651. observer.next = noop;
  1652. }
  1653. if (observer.error === undefined) {
  1654. observer.error = noop;
  1655. }
  1656. if (observer.complete === undefined) {
  1657. observer.complete = noop;
  1658. }
  1659. const unsub = this.unsubscribeOne.bind(this, this.observers.length);
  1660. // Attempt to subscribe to a terminated Observable - we
  1661. // just respond to the Observer with the final error or complete
  1662. // event.
  1663. if (this.finalized) {
  1664. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1665. this.task.then(() => {
  1666. try {
  1667. if (this.finalError) {
  1668. observer.error(this.finalError);
  1669. }
  1670. else {
  1671. observer.complete();
  1672. }
  1673. }
  1674. catch (e) {
  1675. // nothing
  1676. }
  1677. return;
  1678. });
  1679. }
  1680. this.observers.push(observer);
  1681. return unsub;
  1682. }
  1683. // Unsubscribe is synchronous - we guarantee that no events are sent to
  1684. // any unsubscribed Observer.
  1685. unsubscribeOne(i) {
  1686. if (this.observers === undefined || this.observers[i] === undefined) {
  1687. return;
  1688. }
  1689. delete this.observers[i];
  1690. this.observerCount -= 1;
  1691. if (this.observerCount === 0 && this.onNoObservers !== undefined) {
  1692. this.onNoObservers(this);
  1693. }
  1694. }
  1695. forEachObserver(fn) {
  1696. if (this.finalized) {
  1697. // Already closed by previous event....just eat the additional values.
  1698. return;
  1699. }
  1700. // Since sendOne calls asynchronously - there is no chance that
  1701. // this.observers will become undefined.
  1702. for (let i = 0; i < this.observers.length; i++) {
  1703. this.sendOne(i, fn);
  1704. }
  1705. }
  1706. // Call the Observer via one of it's callback function. We are careful to
  1707. // confirm that the observe has not been unsubscribed since this asynchronous
  1708. // function had been queued.
  1709. sendOne(i, fn) {
  1710. // Execute the callback asynchronously
  1711. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1712. this.task.then(() => {
  1713. if (this.observers !== undefined && this.observers[i] !== undefined) {
  1714. try {
  1715. fn(this.observers[i]);
  1716. }
  1717. catch (e) {
  1718. // Ignore exceptions raised in Observers or missing methods of an
  1719. // Observer.
  1720. // Log error to console. b/31404806
  1721. if (typeof console !== 'undefined' && console.error) {
  1722. console.error(e);
  1723. }
  1724. }
  1725. }
  1726. });
  1727. }
  1728. close(err) {
  1729. if (this.finalized) {
  1730. return;
  1731. }
  1732. this.finalized = true;
  1733. if (err !== undefined) {
  1734. this.finalError = err;
  1735. }
  1736. // Proxy is no longer needed - garbage collect references
  1737. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1738. this.task.then(() => {
  1739. this.observers = undefined;
  1740. this.onNoObservers = undefined;
  1741. });
  1742. }
  1743. }
  1744. /** Turn synchronous function into one called asynchronously. */
  1745. // eslint-disable-next-line @typescript-eslint/ban-types
  1746. function async(fn, onError) {
  1747. return (...args) => {
  1748. Promise.resolve(true)
  1749. .then(() => {
  1750. fn(...args);
  1751. })
  1752. .catch((error) => {
  1753. if (onError) {
  1754. onError(error);
  1755. }
  1756. });
  1757. };
  1758. }
  1759. /**
  1760. * Return true if the object passed in implements any of the named methods.
  1761. */
  1762. function implementsAnyMethods(obj, methods) {
  1763. if (typeof obj !== 'object' || obj === null) {
  1764. return false;
  1765. }
  1766. for (const method of methods) {
  1767. if (method in obj && typeof obj[method] === 'function') {
  1768. return true;
  1769. }
  1770. }
  1771. return false;
  1772. }
  1773. function noop() {
  1774. // do nothing
  1775. }
  1776. /**
  1777. * @license
  1778. * Copyright 2017 Google LLC
  1779. *
  1780. * Licensed under the Apache License, Version 2.0 (the "License");
  1781. * you may not use this file except in compliance with the License.
  1782. * You may obtain a copy of the License at
  1783. *
  1784. * http://www.apache.org/licenses/LICENSE-2.0
  1785. *
  1786. * Unless required by applicable law or agreed to in writing, software
  1787. * distributed under the License is distributed on an "AS IS" BASIS,
  1788. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1789. * See the License for the specific language governing permissions and
  1790. * limitations under the License.
  1791. */
  1792. /**
  1793. * Check to make sure the appropriate number of arguments are provided for a public function.
  1794. * Throws an error if it fails.
  1795. *
  1796. * @param fnName The function name
  1797. * @param minCount The minimum number of arguments to allow for the function call
  1798. * @param maxCount The maximum number of argument to allow for the function call
  1799. * @param argCount The actual number of arguments provided.
  1800. */
  1801. const validateArgCount = function (fnName, minCount, maxCount, argCount) {
  1802. let argError;
  1803. if (argCount < minCount) {
  1804. argError = 'at least ' + minCount;
  1805. }
  1806. else if (argCount > maxCount) {
  1807. argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;
  1808. }
  1809. if (argError) {
  1810. const error = fnName +
  1811. ' failed: Was called with ' +
  1812. argCount +
  1813. (argCount === 1 ? ' argument.' : ' arguments.') +
  1814. ' Expects ' +
  1815. argError +
  1816. '.';
  1817. throw new Error(error);
  1818. }
  1819. };
  1820. /**
  1821. * Generates a string to prefix an error message about failed argument validation
  1822. *
  1823. * @param fnName The function name
  1824. * @param argName The name of the argument
  1825. * @return The prefix to add to the error thrown for validation.
  1826. */
  1827. function errorPrefix(fnName, argName) {
  1828. return `${fnName} failed: ${argName} argument `;
  1829. }
  1830. /**
  1831. * @param fnName
  1832. * @param argumentNumber
  1833. * @param namespace
  1834. * @param optional
  1835. */
  1836. function validateNamespace(fnName, namespace, optional) {
  1837. if (optional && !namespace) {
  1838. return;
  1839. }
  1840. if (typeof namespace !== 'string') {
  1841. //TODO: I should do more validation here. We only allow certain chars in namespaces.
  1842. throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');
  1843. }
  1844. }
  1845. function validateCallback(fnName, argumentName,
  1846. // eslint-disable-next-line @typescript-eslint/ban-types
  1847. callback, optional) {
  1848. if (optional && !callback) {
  1849. return;
  1850. }
  1851. if (typeof callback !== 'function') {
  1852. throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');
  1853. }
  1854. }
  1855. function validateContextObject(fnName, argumentName, context, optional) {
  1856. if (optional && !context) {
  1857. return;
  1858. }
  1859. if (typeof context !== 'object' || context === null) {
  1860. throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');
  1861. }
  1862. }
  1863. /**
  1864. * @license
  1865. * Copyright 2017 Google LLC
  1866. *
  1867. * Licensed under the Apache License, Version 2.0 (the "License");
  1868. * you may not use this file except in compliance with the License.
  1869. * You may obtain a copy of the License at
  1870. *
  1871. * http://www.apache.org/licenses/LICENSE-2.0
  1872. *
  1873. * Unless required by applicable law or agreed to in writing, software
  1874. * distributed under the License is distributed on an "AS IS" BASIS,
  1875. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1876. * See the License for the specific language governing permissions and
  1877. * limitations under the License.
  1878. */
  1879. // Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they
  1880. // automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs,
  1881. // so it's been modified.
  1882. // Note that not all Unicode characters appear as single characters in JavaScript strings.
  1883. // fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters
  1884. // use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first
  1885. // character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate
  1886. // pair).
  1887. // See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3
  1888. /**
  1889. * @param {string} str
  1890. * @return {Array}
  1891. */
  1892. const stringToByteArray = function (str) {
  1893. const out = [];
  1894. let p = 0;
  1895. for (let i = 0; i < str.length; i++) {
  1896. let c = str.charCodeAt(i);
  1897. // Is this the lead surrogate in a surrogate pair?
  1898. if (c >= 0xd800 && c <= 0xdbff) {
  1899. const high = c - 0xd800; // the high 10 bits.
  1900. i++;
  1901. assert(i < str.length, 'Surrogate pair missing trail surrogate.');
  1902. const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.
  1903. c = 0x10000 + (high << 10) + low;
  1904. }
  1905. if (c < 128) {
  1906. out[p++] = c;
  1907. }
  1908. else if (c < 2048) {
  1909. out[p++] = (c >> 6) | 192;
  1910. out[p++] = (c & 63) | 128;
  1911. }
  1912. else if (c < 65536) {
  1913. out[p++] = (c >> 12) | 224;
  1914. out[p++] = ((c >> 6) & 63) | 128;
  1915. out[p++] = (c & 63) | 128;
  1916. }
  1917. else {
  1918. out[p++] = (c >> 18) | 240;
  1919. out[p++] = ((c >> 12) & 63) | 128;
  1920. out[p++] = ((c >> 6) & 63) | 128;
  1921. out[p++] = (c & 63) | 128;
  1922. }
  1923. }
  1924. return out;
  1925. };
  1926. /**
  1927. * Calculate length without actually converting; useful for doing cheaper validation.
  1928. * @param {string} str
  1929. * @return {number}
  1930. */
  1931. const stringLength = function (str) {
  1932. let p = 0;
  1933. for (let i = 0; i < str.length; i++) {
  1934. const c = str.charCodeAt(i);
  1935. if (c < 128) {
  1936. p++;
  1937. }
  1938. else if (c < 2048) {
  1939. p += 2;
  1940. }
  1941. else if (c >= 0xd800 && c <= 0xdbff) {
  1942. // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.
  1943. p += 4;
  1944. i++; // skip trail surrogate.
  1945. }
  1946. else {
  1947. p += 3;
  1948. }
  1949. }
  1950. return p;
  1951. };
  1952. /**
  1953. * @license
  1954. * Copyright 2022 Google LLC
  1955. *
  1956. * Licensed under the Apache License, Version 2.0 (the "License");
  1957. * you may not use this file except in compliance with the License.
  1958. * You may obtain a copy of the License at
  1959. *
  1960. * http://www.apache.org/licenses/LICENSE-2.0
  1961. *
  1962. * Unless required by applicable law or agreed to in writing, software
  1963. * distributed under the License is distributed on an "AS IS" BASIS,
  1964. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1965. * See the License for the specific language governing permissions and
  1966. * limitations under the License.
  1967. */
  1968. /**
  1969. * Copied from https://stackoverflow.com/a/2117523
  1970. * Generates a new uuid.
  1971. * @public
  1972. */
  1973. const uuidv4 = function () {
  1974. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
  1975. const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;
  1976. return v.toString(16);
  1977. });
  1978. };
  1979. /**
  1980. * @license
  1981. * Copyright 2019 Google LLC
  1982. *
  1983. * Licensed under the Apache License, Version 2.0 (the "License");
  1984. * you may not use this file except in compliance with the License.
  1985. * You may obtain a copy of the License at
  1986. *
  1987. * http://www.apache.org/licenses/LICENSE-2.0
  1988. *
  1989. * Unless required by applicable law or agreed to in writing, software
  1990. * distributed under the License is distributed on an "AS IS" BASIS,
  1991. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1992. * See the License for the specific language governing permissions and
  1993. * limitations under the License.
  1994. */
  1995. /**
  1996. * The amount of milliseconds to exponentially increase.
  1997. */
  1998. const DEFAULT_INTERVAL_MILLIS = 1000;
  1999. /**
  2000. * The factor to backoff by.
  2001. * Should be a number greater than 1.
  2002. */
  2003. const DEFAULT_BACKOFF_FACTOR = 2;
  2004. /**
  2005. * The maximum milliseconds to increase to.
  2006. *
  2007. * <p>Visible for testing
  2008. */
  2009. const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.
  2010. /**
  2011. * The percentage of backoff time to randomize by.
  2012. * See
  2013. * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic
  2014. * for context.
  2015. *
  2016. * <p>Visible for testing
  2017. */
  2018. const RANDOM_FACTOR = 0.5;
  2019. /**
  2020. * Based on the backoff method from
  2021. * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.
  2022. * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.
  2023. */
  2024. function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {
  2025. // Calculates an exponentially increasing value.
  2026. // Deviation: calculates value from count and a constant interval, so we only need to save value
  2027. // and count to restore state.
  2028. const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);
  2029. // A random "fuzz" to avoid waves of retries.
  2030. // Deviation: randomFactor is required.
  2031. const randomWait = Math.round(
  2032. // A fraction of the backoff value to add/subtract.
  2033. // Deviation: changes multiplication order to improve readability.
  2034. RANDOM_FACTOR *
  2035. currBaseValue *
  2036. // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines
  2037. // if we add or subtract.
  2038. (Math.random() - 0.5) *
  2039. 2);
  2040. // Limits backoff to max to avoid effectively permanent backoff.
  2041. return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);
  2042. }
  2043. /**
  2044. * @license
  2045. * Copyright 2020 Google LLC
  2046. *
  2047. * Licensed under the Apache License, Version 2.0 (the "License");
  2048. * you may not use this file except in compliance with the License.
  2049. * You may obtain a copy of the License at
  2050. *
  2051. * http://www.apache.org/licenses/LICENSE-2.0
  2052. *
  2053. * Unless required by applicable law or agreed to in writing, software
  2054. * distributed under the License is distributed on an "AS IS" BASIS,
  2055. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2056. * See the License for the specific language governing permissions and
  2057. * limitations under the License.
  2058. */
  2059. /**
  2060. * Provide English ordinal letters after a number
  2061. */
  2062. function ordinal(i) {
  2063. if (!Number.isFinite(i)) {
  2064. return `${i}`;
  2065. }
  2066. return i + indicator(i);
  2067. }
  2068. function indicator(i) {
  2069. i = Math.abs(i);
  2070. const cent = i % 100;
  2071. if (cent >= 10 && cent <= 20) {
  2072. return 'th';
  2073. }
  2074. const dec = i % 10;
  2075. if (dec === 1) {
  2076. return 'st';
  2077. }
  2078. if (dec === 2) {
  2079. return 'nd';
  2080. }
  2081. if (dec === 3) {
  2082. return 'rd';
  2083. }
  2084. return 'th';
  2085. }
  2086. /**
  2087. * @license
  2088. * Copyright 2021 Google LLC
  2089. *
  2090. * Licensed under the Apache License, Version 2.0 (the "License");
  2091. * you may not use this file except in compliance with the License.
  2092. * You may obtain a copy of the License at
  2093. *
  2094. * http://www.apache.org/licenses/LICENSE-2.0
  2095. *
  2096. * Unless required by applicable law or agreed to in writing, software
  2097. * distributed under the License is distributed on an "AS IS" BASIS,
  2098. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2099. * See the License for the specific language governing permissions and
  2100. * limitations under the License.
  2101. */
  2102. function getModularInstance(service) {
  2103. if (service && service._delegate) {
  2104. return service._delegate;
  2105. }
  2106. else {
  2107. return service;
  2108. }
  2109. }
  2110. /**
  2111. * @license
  2112. * Copyright 2017 Google LLC
  2113. *
  2114. * Licensed under the Apache License, Version 2.0 (the "License");
  2115. * you may not use this file except in compliance with the License.
  2116. * You may obtain a copy of the License at
  2117. *
  2118. * http://www.apache.org/licenses/LICENSE-2.0
  2119. *
  2120. * Unless required by applicable law or agreed to in writing, software
  2121. * distributed under the License is distributed on an "AS IS" BASIS,
  2122. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2123. * See the License for the specific language governing permissions and
  2124. * limitations under the License.
  2125. */
  2126. // Overriding the constant (we should be the only ones doing this)
  2127. CONSTANTS.NODE_CLIENT = true;
  2128. export { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isCloudflareWorker, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, isWebWorker, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };
  2129. //# sourceMappingURL=index.node.esm.js.map