index.cjs.js 74 KB

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