Нет описания
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. import firebase from '@firebase/app-compat';
  2. import * as exp from '@firebase/auth/internal';
  3. import { Component } from '@firebase/component';
  4. import { isBrowserExtension, getUA, isReactNative, isNode, isIndexedDBAvailable, isIE, FirebaseError } from '@firebase/util';
  5. var name = "@firebase/auth-compat";
  6. var version = "0.3.1";
  7. /**
  8. * @license
  9. * Copyright 2020 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. const CORDOVA_ONDEVICEREADY_TIMEOUT_MS = 1000;
  24. function _getCurrentScheme() {
  25. var _a;
  26. return ((_a = self === null || self === void 0 ? void 0 : self.location) === null || _a === void 0 ? void 0 : _a.protocol) || null;
  27. }
  28. /**
  29. * @return {boolean} Whether the current environment is http or https.
  30. */
  31. function _isHttpOrHttps() {
  32. return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
  33. }
  34. /**
  35. * @param {?string=} ua The user agent.
  36. * @return {boolean} Whether the app is rendered in a mobile iOS or Android
  37. * Cordova environment.
  38. */
  39. function _isAndroidOrIosCordovaScheme(ua = getUA()) {
  40. return !!((_getCurrentScheme() === 'file:' ||
  41. _getCurrentScheme() === 'ionic:' ||
  42. _getCurrentScheme() === 'capacitor:') &&
  43. ua.toLowerCase().match(/iphone|ipad|ipod|android/));
  44. }
  45. /**
  46. * @return {boolean} Whether the environment is a native environment, where
  47. * CORS checks do not apply.
  48. */
  49. function _isNativeEnvironment() {
  50. return isReactNative() || isNode();
  51. }
  52. /**
  53. * Checks whether the user agent is IE11.
  54. * @return {boolean} True if it is IE11.
  55. */
  56. function _isIe11() {
  57. return isIE() && (document === null || document === void 0 ? void 0 : document.documentMode) === 11;
  58. }
  59. /**
  60. * Checks whether the user agent is Edge.
  61. * @param {string} userAgent The browser user agent string.
  62. * @return {boolean} True if it is Edge.
  63. */
  64. function _isEdge(ua = getUA()) {
  65. return /Edge\/\d+/.test(ua);
  66. }
  67. /**
  68. * @param {?string=} opt_userAgent The navigator user agent.
  69. * @return {boolean} Whether local storage is not synchronized between an iframe
  70. * and a popup of the same domain.
  71. */
  72. function _isLocalStorageNotSynchronized(ua = getUA()) {
  73. return _isIe11() || _isEdge(ua);
  74. }
  75. /** @return {boolean} Whether web storage is supported. */
  76. function _isWebStorageSupported() {
  77. try {
  78. const storage = self.localStorage;
  79. const key = exp._generateEventId();
  80. if (storage) {
  81. // setItem will throw an exception if we cannot access WebStorage (e.g.,
  82. // Safari in private mode).
  83. storage['setItem'](key, '1');
  84. storage['removeItem'](key);
  85. // For browsers where iframe web storage does not synchronize with a popup
  86. // of the same domain, indexedDB is used for persistent storage. These
  87. // browsers include IE11 and Edge.
  88. // Make sure it is supported (IE11 and Edge private mode does not support
  89. // that).
  90. if (_isLocalStorageNotSynchronized()) {
  91. // In such browsers, if indexedDB is not supported, an iframe cannot be
  92. // notified of the popup sign in result.
  93. return isIndexedDBAvailable();
  94. }
  95. return true;
  96. }
  97. }
  98. catch (e) {
  99. // localStorage is not available from a worker. Test availability of
  100. // indexedDB.
  101. return _isWorker() && isIndexedDBAvailable();
  102. }
  103. return false;
  104. }
  105. /**
  106. * @param {?Object=} global The optional global scope.
  107. * @return {boolean} Whether current environment is a worker.
  108. */
  109. function _isWorker() {
  110. // WorkerGlobalScope only defined in worker environment.
  111. return (typeof global !== 'undefined' &&
  112. 'WorkerGlobalScope' in global &&
  113. 'importScripts' in global);
  114. }
  115. function _isPopupRedirectSupported() {
  116. return ((_isHttpOrHttps() ||
  117. isBrowserExtension() ||
  118. _isAndroidOrIosCordovaScheme()) &&
  119. // React Native with remote debugging reports its location.protocol as
  120. // http.
  121. !_isNativeEnvironment() &&
  122. // Local storage has to be supported for browser popup and redirect
  123. // operations to work.
  124. _isWebStorageSupported() &&
  125. // DOM, popups and redirects are not supported within a worker.
  126. !_isWorker());
  127. }
  128. /** Quick check that indicates the platform *may* be Cordova */
  129. function _isLikelyCordova() {
  130. return _isAndroidOrIosCordovaScheme() && typeof document !== 'undefined';
  131. }
  132. async function _isCordova() {
  133. if (!_isLikelyCordova()) {
  134. return false;
  135. }
  136. return new Promise(resolve => {
  137. const timeoutId = setTimeout(() => {
  138. // We've waited long enough; the telltale Cordova event didn't happen
  139. resolve(false);
  140. }, CORDOVA_ONDEVICEREADY_TIMEOUT_MS);
  141. document.addEventListener('deviceready', () => {
  142. clearTimeout(timeoutId);
  143. resolve(true);
  144. });
  145. });
  146. }
  147. function _getSelfWindow() {
  148. return typeof window !== 'undefined' ? window : null;
  149. }
  150. /**
  151. * @license
  152. * Copyright 2020 Google LLC
  153. *
  154. * Licensed under the Apache License, Version 2.0 (the "License");
  155. * you may not use this file except in compliance with the License.
  156. * You may obtain a copy of the License at
  157. *
  158. * http://www.apache.org/licenses/LICENSE-2.0
  159. *
  160. * Unless required by applicable law or agreed to in writing, software
  161. * distributed under the License is distributed on an "AS IS" BASIS,
  162. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  163. * See the License for the specific language governing permissions and
  164. * limitations under the License.
  165. */
  166. const Persistence = {
  167. LOCAL: 'local',
  168. NONE: 'none',
  169. SESSION: 'session'
  170. };
  171. const _assert$3 = exp._assert;
  172. const PERSISTENCE_KEY = 'persistence';
  173. /**
  174. * Validates that an argument is a valid persistence value. If an invalid type
  175. * is specified, an error is thrown synchronously.
  176. */
  177. function _validatePersistenceArgument(auth, persistence) {
  178. _assert$3(Object.values(Persistence).includes(persistence), auth, "invalid-persistence-type" /* exp.AuthErrorCode.INVALID_PERSISTENCE */);
  179. // Validate if the specified type is supported in the current environment.
  180. if (isReactNative()) {
  181. // This is only supported in a browser.
  182. _assert$3(persistence !== Persistence.SESSION, auth, "unsupported-persistence-type" /* exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE */);
  183. return;
  184. }
  185. if (isNode()) {
  186. // Only none is supported in Node.js.
  187. _assert$3(persistence === Persistence.NONE, auth, "unsupported-persistence-type" /* exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE */);
  188. return;
  189. }
  190. if (_isWorker()) {
  191. // In a worker environment, either LOCAL or NONE are supported.
  192. // If indexedDB not supported and LOCAL provided, throw an error
  193. _assert$3(persistence === Persistence.NONE ||
  194. (persistence === Persistence.LOCAL && isIndexedDBAvailable()), auth, "unsupported-persistence-type" /* exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE */);
  195. return;
  196. }
  197. // This is restricted by what the browser supports.
  198. _assert$3(persistence === Persistence.NONE || _isWebStorageSupported(), auth, "unsupported-persistence-type" /* exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE */);
  199. }
  200. async function _savePersistenceForRedirect(auth) {
  201. await auth._initializationPromise;
  202. const session = getSessionStorageIfAvailable();
  203. const key = exp._persistenceKeyName(PERSISTENCE_KEY, auth.config.apiKey, auth.name);
  204. if (session) {
  205. session.setItem(key, auth._getPersistence());
  206. }
  207. }
  208. function _getPersistencesFromRedirect(apiKey, appName) {
  209. const session = getSessionStorageIfAvailable();
  210. if (!session) {
  211. return [];
  212. }
  213. const key = exp._persistenceKeyName(PERSISTENCE_KEY, apiKey, appName);
  214. const persistence = session.getItem(key);
  215. switch (persistence) {
  216. case Persistence.NONE:
  217. return [exp.inMemoryPersistence];
  218. case Persistence.LOCAL:
  219. return [exp.indexedDBLocalPersistence, exp.browserSessionPersistence];
  220. case Persistence.SESSION:
  221. return [exp.browserSessionPersistence];
  222. default:
  223. return [];
  224. }
  225. }
  226. /** Returns session storage, or null if the property access errors */
  227. function getSessionStorageIfAvailable() {
  228. var _a;
  229. try {
  230. return ((_a = _getSelfWindow()) === null || _a === void 0 ? void 0 : _a.sessionStorage) || null;
  231. }
  232. catch (e) {
  233. return null;
  234. }
  235. }
  236. /**
  237. * @license
  238. * Copyright 2020 Google LLC
  239. *
  240. * Licensed under the Apache License, Version 2.0 (the "License");
  241. * you may not use this file except in compliance with the License.
  242. * You may obtain a copy of the License at
  243. *
  244. * http://www.apache.org/licenses/LICENSE-2.0
  245. *
  246. * Unless required by applicable law or agreed to in writing, software
  247. * distributed under the License is distributed on an "AS IS" BASIS,
  248. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  249. * See the License for the specific language governing permissions and
  250. * limitations under the License.
  251. */
  252. const _assert$2 = exp._assert;
  253. /** Platform-agnostic popup-redirect resolver */
  254. class CompatPopupRedirectResolver {
  255. constructor() {
  256. // Create both resolvers for dynamic resolution later
  257. this.browserResolver = exp._getInstance(exp.browserPopupRedirectResolver);
  258. this.cordovaResolver = exp._getInstance(exp.cordovaPopupRedirectResolver);
  259. // The actual resolver in use: either browserResolver or cordovaResolver.
  260. this.underlyingResolver = null;
  261. this._redirectPersistence = exp.browserSessionPersistence;
  262. this._completeRedirectFn = exp._getRedirectResult;
  263. this._overrideRedirectResult = exp._overrideRedirectResult;
  264. }
  265. async _initialize(auth) {
  266. await this.selectUnderlyingResolver();
  267. return this.assertedUnderlyingResolver._initialize(auth);
  268. }
  269. async _openPopup(auth, provider, authType, eventId) {
  270. await this.selectUnderlyingResolver();
  271. return this.assertedUnderlyingResolver._openPopup(auth, provider, authType, eventId);
  272. }
  273. async _openRedirect(auth, provider, authType, eventId) {
  274. await this.selectUnderlyingResolver();
  275. return this.assertedUnderlyingResolver._openRedirect(auth, provider, authType, eventId);
  276. }
  277. _isIframeWebStorageSupported(auth, cb) {
  278. this.assertedUnderlyingResolver._isIframeWebStorageSupported(auth, cb);
  279. }
  280. _originValidation(auth) {
  281. return this.assertedUnderlyingResolver._originValidation(auth);
  282. }
  283. get _shouldInitProactively() {
  284. return _isLikelyCordova() || this.browserResolver._shouldInitProactively;
  285. }
  286. get assertedUnderlyingResolver() {
  287. _assert$2(this.underlyingResolver, "internal-error" /* exp.AuthErrorCode.INTERNAL_ERROR */);
  288. return this.underlyingResolver;
  289. }
  290. async selectUnderlyingResolver() {
  291. if (this.underlyingResolver) {
  292. return;
  293. }
  294. // We haven't yet determined whether or not we're in Cordova; go ahead
  295. // and determine that state now.
  296. const isCordova = await _isCordova();
  297. this.underlyingResolver = isCordova
  298. ? this.cordovaResolver
  299. : this.browserResolver;
  300. }
  301. }
  302. /**
  303. * @license
  304. * Copyright 2020 Google LLC
  305. *
  306. * Licensed under the Apache License, Version 2.0 (the "License");
  307. * you may not use this file except in compliance with the License.
  308. * You may obtain a copy of the License at
  309. *
  310. * http://www.apache.org/licenses/LICENSE-2.0
  311. *
  312. * Unless required by applicable law or agreed to in writing, software
  313. * distributed under the License is distributed on an "AS IS" BASIS,
  314. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  315. * See the License for the specific language governing permissions and
  316. * limitations under the License.
  317. */
  318. function unwrap(object) {
  319. return object.unwrap();
  320. }
  321. function wrapped(object) {
  322. return object.wrapped();
  323. }
  324. /**
  325. * @license
  326. * Copyright 2020 Google LLC
  327. *
  328. * Licensed under the Apache License, Version 2.0 (the "License");
  329. * you may not use this file except in compliance with the License.
  330. * You may obtain a copy of the License at
  331. *
  332. * http://www.apache.org/licenses/LICENSE-2.0
  333. *
  334. * Unless required by applicable law or agreed to in writing, software
  335. * distributed under the License is distributed on an "AS IS" BASIS,
  336. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  337. * See the License for the specific language governing permissions and
  338. * limitations under the License.
  339. */
  340. function credentialFromResponse(userCredential) {
  341. return credentialFromObject(userCredential);
  342. }
  343. function attachExtraErrorFields(auth, e) {
  344. var _a;
  345. // The response contains all fields from the server which may or may not
  346. // actually match the underlying type
  347. const response = (_a = e.customData) === null || _a === void 0 ? void 0 : _a._tokenResponse;
  348. if ((e === null || e === void 0 ? void 0 : e.code) === 'auth/multi-factor-auth-required') {
  349. const mfaErr = e;
  350. mfaErr.resolver = new MultiFactorResolver(auth, exp.getMultiFactorResolver(auth, e));
  351. }
  352. else if (response) {
  353. const credential = credentialFromObject(e);
  354. const credErr = e;
  355. if (credential) {
  356. credErr.credential = credential;
  357. credErr.tenantId = response.tenantId || undefined;
  358. credErr.email = response.email || undefined;
  359. credErr.phoneNumber = response.phoneNumber || undefined;
  360. }
  361. }
  362. }
  363. function credentialFromObject(object) {
  364. const { _tokenResponse } = (object instanceof FirebaseError ? object.customData : object);
  365. if (!_tokenResponse) {
  366. return null;
  367. }
  368. // Handle phone Auth credential responses, as they have a different format
  369. // from other backend responses (i.e. no providerId). This is also only the
  370. // case for user credentials (does not work for errors).
  371. if (!(object instanceof FirebaseError)) {
  372. if ('temporaryProof' in _tokenResponse && 'phoneNumber' in _tokenResponse) {
  373. return exp.PhoneAuthProvider.credentialFromResult(object);
  374. }
  375. }
  376. const providerId = _tokenResponse.providerId;
  377. // Email and password is not supported as there is no situation where the
  378. // server would return the password to the client.
  379. if (!providerId || providerId === exp.ProviderId.PASSWORD) {
  380. return null;
  381. }
  382. let provider;
  383. switch (providerId) {
  384. case exp.ProviderId.GOOGLE:
  385. provider = exp.GoogleAuthProvider;
  386. break;
  387. case exp.ProviderId.FACEBOOK:
  388. provider = exp.FacebookAuthProvider;
  389. break;
  390. case exp.ProviderId.GITHUB:
  391. provider = exp.GithubAuthProvider;
  392. break;
  393. case exp.ProviderId.TWITTER:
  394. provider = exp.TwitterAuthProvider;
  395. break;
  396. default:
  397. const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce } = _tokenResponse;
  398. if (!oauthAccessToken &&
  399. !oauthTokenSecret &&
  400. !oauthIdToken &&
  401. !pendingToken) {
  402. return null;
  403. }
  404. // TODO(avolkovi): uncomment this and get it working with SAML & OIDC
  405. if (pendingToken) {
  406. if (providerId.startsWith('saml.')) {
  407. return exp.SAMLAuthCredential._create(providerId, pendingToken);
  408. }
  409. else {
  410. // OIDC and non-default providers excluding Twitter.
  411. return exp.OAuthCredential._fromParams({
  412. providerId,
  413. signInMethod: providerId,
  414. pendingToken,
  415. idToken: oauthIdToken,
  416. accessToken: oauthAccessToken
  417. });
  418. }
  419. }
  420. return new exp.OAuthProvider(providerId).credential({
  421. idToken: oauthIdToken,
  422. accessToken: oauthAccessToken,
  423. rawNonce: nonce
  424. });
  425. }
  426. return object instanceof FirebaseError
  427. ? provider.credentialFromError(object)
  428. : provider.credentialFromResult(object);
  429. }
  430. function convertCredential(auth, credentialPromise) {
  431. return credentialPromise
  432. .catch(e => {
  433. if (e instanceof FirebaseError) {
  434. attachExtraErrorFields(auth, e);
  435. }
  436. throw e;
  437. })
  438. .then(credential => {
  439. const operationType = credential.operationType;
  440. const user = credential.user;
  441. return {
  442. operationType,
  443. credential: credentialFromResponse(credential),
  444. additionalUserInfo: exp.getAdditionalUserInfo(credential),
  445. user: User.getOrCreate(user)
  446. };
  447. });
  448. }
  449. async function convertConfirmationResult(auth, confirmationResultPromise) {
  450. const confirmationResultExp = await confirmationResultPromise;
  451. return {
  452. verificationId: confirmationResultExp.verificationId,
  453. confirm: (verificationCode) => convertCredential(auth, confirmationResultExp.confirm(verificationCode))
  454. };
  455. }
  456. class MultiFactorResolver {
  457. constructor(auth, resolver) {
  458. this.resolver = resolver;
  459. this.auth = wrapped(auth);
  460. }
  461. get session() {
  462. return this.resolver.session;
  463. }
  464. get hints() {
  465. return this.resolver.hints;
  466. }
  467. resolveSignIn(assertion) {
  468. return convertCredential(unwrap(this.auth), this.resolver.resolveSignIn(assertion));
  469. }
  470. }
  471. /**
  472. * @license
  473. * Copyright 2020 Google LLC
  474. *
  475. * Licensed under the Apache License, Version 2.0 (the "License");
  476. * you may not use this file except in compliance with the License.
  477. * You may obtain a copy of the License at
  478. *
  479. * http://www.apache.org/licenses/LICENSE-2.0
  480. *
  481. * Unless required by applicable law or agreed to in writing, software
  482. * distributed under the License is distributed on an "AS IS" BASIS,
  483. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  484. * See the License for the specific language governing permissions and
  485. * limitations under the License.
  486. */
  487. class User {
  488. constructor(_delegate) {
  489. this._delegate = _delegate;
  490. this.multiFactor = exp.multiFactor(_delegate);
  491. }
  492. static getOrCreate(user) {
  493. if (!User.USER_MAP.has(user)) {
  494. User.USER_MAP.set(user, new User(user));
  495. }
  496. return User.USER_MAP.get(user);
  497. }
  498. delete() {
  499. return this._delegate.delete();
  500. }
  501. reload() {
  502. return this._delegate.reload();
  503. }
  504. toJSON() {
  505. return this._delegate.toJSON();
  506. }
  507. getIdTokenResult(forceRefresh) {
  508. return this._delegate.getIdTokenResult(forceRefresh);
  509. }
  510. getIdToken(forceRefresh) {
  511. return this._delegate.getIdToken(forceRefresh);
  512. }
  513. linkAndRetrieveDataWithCredential(credential) {
  514. return this.linkWithCredential(credential);
  515. }
  516. async linkWithCredential(credential) {
  517. return convertCredential(this.auth, exp.linkWithCredential(this._delegate, credential));
  518. }
  519. async linkWithPhoneNumber(phoneNumber, applicationVerifier) {
  520. return convertConfirmationResult(this.auth, exp.linkWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier));
  521. }
  522. async linkWithPopup(provider) {
  523. return convertCredential(this.auth, exp.linkWithPopup(this._delegate, provider, CompatPopupRedirectResolver));
  524. }
  525. async linkWithRedirect(provider) {
  526. await _savePersistenceForRedirect(exp._castAuth(this.auth));
  527. return exp.linkWithRedirect(this._delegate, provider, CompatPopupRedirectResolver);
  528. }
  529. reauthenticateAndRetrieveDataWithCredential(credential) {
  530. return this.reauthenticateWithCredential(credential);
  531. }
  532. async reauthenticateWithCredential(credential) {
  533. return convertCredential(this.auth, exp.reauthenticateWithCredential(this._delegate, credential));
  534. }
  535. reauthenticateWithPhoneNumber(phoneNumber, applicationVerifier) {
  536. return convertConfirmationResult(this.auth, exp.reauthenticateWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier));
  537. }
  538. reauthenticateWithPopup(provider) {
  539. return convertCredential(this.auth, exp.reauthenticateWithPopup(this._delegate, provider, CompatPopupRedirectResolver));
  540. }
  541. async reauthenticateWithRedirect(provider) {
  542. await _savePersistenceForRedirect(exp._castAuth(this.auth));
  543. return exp.reauthenticateWithRedirect(this._delegate, provider, CompatPopupRedirectResolver);
  544. }
  545. sendEmailVerification(actionCodeSettings) {
  546. return exp.sendEmailVerification(this._delegate, actionCodeSettings);
  547. }
  548. async unlink(providerId) {
  549. await exp.unlink(this._delegate, providerId);
  550. return this;
  551. }
  552. updateEmail(newEmail) {
  553. return exp.updateEmail(this._delegate, newEmail);
  554. }
  555. updatePassword(newPassword) {
  556. return exp.updatePassword(this._delegate, newPassword);
  557. }
  558. updatePhoneNumber(phoneCredential) {
  559. return exp.updatePhoneNumber(this._delegate, phoneCredential);
  560. }
  561. updateProfile(profile) {
  562. return exp.updateProfile(this._delegate, profile);
  563. }
  564. verifyBeforeUpdateEmail(newEmail, actionCodeSettings) {
  565. return exp.verifyBeforeUpdateEmail(this._delegate, newEmail, actionCodeSettings);
  566. }
  567. get emailVerified() {
  568. return this._delegate.emailVerified;
  569. }
  570. get isAnonymous() {
  571. return this._delegate.isAnonymous;
  572. }
  573. get metadata() {
  574. return this._delegate.metadata;
  575. }
  576. get phoneNumber() {
  577. return this._delegate.phoneNumber;
  578. }
  579. get providerData() {
  580. return this._delegate.providerData;
  581. }
  582. get refreshToken() {
  583. return this._delegate.refreshToken;
  584. }
  585. get tenantId() {
  586. return this._delegate.tenantId;
  587. }
  588. get displayName() {
  589. return this._delegate.displayName;
  590. }
  591. get email() {
  592. return this._delegate.email;
  593. }
  594. get photoURL() {
  595. return this._delegate.photoURL;
  596. }
  597. get providerId() {
  598. return this._delegate.providerId;
  599. }
  600. get uid() {
  601. return this._delegate.uid;
  602. }
  603. get auth() {
  604. return this._delegate.auth;
  605. }
  606. }
  607. // Maintain a map so that there's always a 1:1 mapping between new User and
  608. // legacy compat users
  609. User.USER_MAP = new WeakMap();
  610. /**
  611. * @license
  612. * Copyright 2020 Google LLC
  613. *
  614. * Licensed under the Apache License, Version 2.0 (the "License");
  615. * you may not use this file except in compliance with the License.
  616. * You may obtain a copy of the License at
  617. *
  618. * http://www.apache.org/licenses/LICENSE-2.0
  619. *
  620. * Unless required by applicable law or agreed to in writing, software
  621. * distributed under the License is distributed on an "AS IS" BASIS,
  622. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  623. * See the License for the specific language governing permissions and
  624. * limitations under the License.
  625. */
  626. const _assert$1 = exp._assert;
  627. class Auth {
  628. constructor(app, provider) {
  629. this.app = app;
  630. if (provider.isInitialized()) {
  631. this._delegate = provider.getImmediate();
  632. this.linkUnderlyingAuth();
  633. return;
  634. }
  635. const { apiKey } = app.options;
  636. // TODO: platform needs to be determined using heuristics
  637. _assert$1(apiKey, "invalid-api-key" /* exp.AuthErrorCode.INVALID_API_KEY */, {
  638. appName: app.name
  639. });
  640. // TODO: platform needs to be determined using heuristics
  641. _assert$1(apiKey, "invalid-api-key" /* exp.AuthErrorCode.INVALID_API_KEY */, {
  642. appName: app.name
  643. });
  644. // Only use a popup/redirect resolver in browser environments
  645. const resolver = typeof window !== 'undefined' ? CompatPopupRedirectResolver : undefined;
  646. this._delegate = provider.initialize({
  647. options: {
  648. persistence: buildPersistenceHierarchy(apiKey, app.name),
  649. popupRedirectResolver: resolver
  650. }
  651. });
  652. this._delegate._updateErrorMap(exp.debugErrorMap);
  653. this.linkUnderlyingAuth();
  654. }
  655. get emulatorConfig() {
  656. return this._delegate.emulatorConfig;
  657. }
  658. get currentUser() {
  659. if (!this._delegate.currentUser) {
  660. return null;
  661. }
  662. return User.getOrCreate(this._delegate.currentUser);
  663. }
  664. get languageCode() {
  665. return this._delegate.languageCode;
  666. }
  667. set languageCode(languageCode) {
  668. this._delegate.languageCode = languageCode;
  669. }
  670. get settings() {
  671. return this._delegate.settings;
  672. }
  673. get tenantId() {
  674. return this._delegate.tenantId;
  675. }
  676. set tenantId(tid) {
  677. this._delegate.tenantId = tid;
  678. }
  679. useDeviceLanguage() {
  680. this._delegate.useDeviceLanguage();
  681. }
  682. signOut() {
  683. return this._delegate.signOut();
  684. }
  685. useEmulator(url, options) {
  686. exp.connectAuthEmulator(this._delegate, url, options);
  687. }
  688. applyActionCode(code) {
  689. return exp.applyActionCode(this._delegate, code);
  690. }
  691. checkActionCode(code) {
  692. return exp.checkActionCode(this._delegate, code);
  693. }
  694. confirmPasswordReset(code, newPassword) {
  695. return exp.confirmPasswordReset(this._delegate, code, newPassword);
  696. }
  697. async createUserWithEmailAndPassword(email, password) {
  698. return convertCredential(this._delegate, exp.createUserWithEmailAndPassword(this._delegate, email, password));
  699. }
  700. fetchProvidersForEmail(email) {
  701. return this.fetchSignInMethodsForEmail(email);
  702. }
  703. fetchSignInMethodsForEmail(email) {
  704. return exp.fetchSignInMethodsForEmail(this._delegate, email);
  705. }
  706. isSignInWithEmailLink(emailLink) {
  707. return exp.isSignInWithEmailLink(this._delegate, emailLink);
  708. }
  709. async getRedirectResult() {
  710. _assert$1(_isPopupRedirectSupported(), this._delegate, "operation-not-supported-in-this-environment" /* exp.AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  711. const credential = await exp.getRedirectResult(this._delegate, CompatPopupRedirectResolver);
  712. if (!credential) {
  713. return {
  714. credential: null,
  715. user: null
  716. };
  717. }
  718. return convertCredential(this._delegate, Promise.resolve(credential));
  719. }
  720. // This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.
  721. // It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it
  722. // out of autogenerated documentation pages to reduce accidental misuse.
  723. addFrameworkForLogging(framework) {
  724. exp.addFrameworkForLogging(this._delegate, framework);
  725. }
  726. onAuthStateChanged(nextOrObserver, errorFn, completed) {
  727. const { next, error, complete } = wrapObservers(nextOrObserver, errorFn, completed);
  728. return this._delegate.onAuthStateChanged(next, error, complete);
  729. }
  730. onIdTokenChanged(nextOrObserver, errorFn, completed) {
  731. const { next, error, complete } = wrapObservers(nextOrObserver, errorFn, completed);
  732. return this._delegate.onIdTokenChanged(next, error, complete);
  733. }
  734. sendSignInLinkToEmail(email, actionCodeSettings) {
  735. return exp.sendSignInLinkToEmail(this._delegate, email, actionCodeSettings);
  736. }
  737. sendPasswordResetEmail(email, actionCodeSettings) {
  738. return exp.sendPasswordResetEmail(this._delegate, email, actionCodeSettings || undefined);
  739. }
  740. async setPersistence(persistence) {
  741. _validatePersistenceArgument(this._delegate, persistence);
  742. let converted;
  743. switch (persistence) {
  744. case Persistence.SESSION:
  745. converted = exp.browserSessionPersistence;
  746. break;
  747. case Persistence.LOCAL:
  748. // Not using isIndexedDBAvailable() since it only checks if indexedDB is defined.
  749. const isIndexedDBFullySupported = await exp
  750. ._getInstance(exp.indexedDBLocalPersistence)
  751. ._isAvailable();
  752. converted = isIndexedDBFullySupported
  753. ? exp.indexedDBLocalPersistence
  754. : exp.browserLocalPersistence;
  755. break;
  756. case Persistence.NONE:
  757. converted = exp.inMemoryPersistence;
  758. break;
  759. default:
  760. return exp._fail("argument-error" /* exp.AuthErrorCode.ARGUMENT_ERROR */, {
  761. appName: this._delegate.name
  762. });
  763. }
  764. return this._delegate.setPersistence(converted);
  765. }
  766. signInAndRetrieveDataWithCredential(credential) {
  767. return this.signInWithCredential(credential);
  768. }
  769. signInAnonymously() {
  770. return convertCredential(this._delegate, exp.signInAnonymously(this._delegate));
  771. }
  772. signInWithCredential(credential) {
  773. return convertCredential(this._delegate, exp.signInWithCredential(this._delegate, credential));
  774. }
  775. signInWithCustomToken(token) {
  776. return convertCredential(this._delegate, exp.signInWithCustomToken(this._delegate, token));
  777. }
  778. signInWithEmailAndPassword(email, password) {
  779. return convertCredential(this._delegate, exp.signInWithEmailAndPassword(this._delegate, email, password));
  780. }
  781. signInWithEmailLink(email, emailLink) {
  782. return convertCredential(this._delegate, exp.signInWithEmailLink(this._delegate, email, emailLink));
  783. }
  784. signInWithPhoneNumber(phoneNumber, applicationVerifier) {
  785. return convertConfirmationResult(this._delegate, exp.signInWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier));
  786. }
  787. async signInWithPopup(provider) {
  788. _assert$1(_isPopupRedirectSupported(), this._delegate, "operation-not-supported-in-this-environment" /* exp.AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  789. return convertCredential(this._delegate, exp.signInWithPopup(this._delegate, provider, CompatPopupRedirectResolver));
  790. }
  791. async signInWithRedirect(provider) {
  792. _assert$1(_isPopupRedirectSupported(), this._delegate, "operation-not-supported-in-this-environment" /* exp.AuthErrorCode.OPERATION_NOT_SUPPORTED */);
  793. await _savePersistenceForRedirect(this._delegate);
  794. return exp.signInWithRedirect(this._delegate, provider, CompatPopupRedirectResolver);
  795. }
  796. updateCurrentUser(user) {
  797. // remove ts-ignore once overloads are defined for exp functions to accept compat objects
  798. // @ts-ignore
  799. return this._delegate.updateCurrentUser(user);
  800. }
  801. verifyPasswordResetCode(code) {
  802. return exp.verifyPasswordResetCode(this._delegate, code);
  803. }
  804. unwrap() {
  805. return this._delegate;
  806. }
  807. _delete() {
  808. return this._delegate._delete();
  809. }
  810. linkUnderlyingAuth() {
  811. this._delegate.wrapped = () => this;
  812. }
  813. }
  814. Auth.Persistence = Persistence;
  815. function wrapObservers(nextOrObserver, error, complete) {
  816. let next = nextOrObserver;
  817. if (typeof nextOrObserver !== 'function') {
  818. ({ next, error, complete } = nextOrObserver);
  819. }
  820. // We know 'next' is now a function
  821. const oldNext = next;
  822. const newNext = (user) => oldNext(user && User.getOrCreate(user));
  823. return {
  824. next: newNext,
  825. error: error,
  826. complete
  827. };
  828. }
  829. function buildPersistenceHierarchy(apiKey, appName) {
  830. // Note this is slightly different behavior: in this case, the stored
  831. // persistence is checked *first* rather than last. This is because we want
  832. // to prefer stored persistence type in the hierarchy. This is an empty
  833. // array if window is not available or there is no pending redirect
  834. const persistences = _getPersistencesFromRedirect(apiKey, appName);
  835. // If "self" is available, add indexedDB
  836. if (typeof self !== 'undefined' &&
  837. !persistences.includes(exp.indexedDBLocalPersistence)) {
  838. persistences.push(exp.indexedDBLocalPersistence);
  839. }
  840. // If "window" is available, add HTML Storage persistences
  841. if (typeof window !== 'undefined') {
  842. for (const persistence of [
  843. exp.browserLocalPersistence,
  844. exp.browserSessionPersistence
  845. ]) {
  846. if (!persistences.includes(persistence)) {
  847. persistences.push(persistence);
  848. }
  849. }
  850. }
  851. // Add in-memory as a final fallback
  852. if (!persistences.includes(exp.inMemoryPersistence)) {
  853. persistences.push(exp.inMemoryPersistence);
  854. }
  855. return persistences;
  856. }
  857. /**
  858. * @license
  859. * Copyright 2020 Google LLC
  860. *
  861. * Licensed under the Apache License, Version 2.0 (the "License");
  862. * you may not use this file except in compliance with the License.
  863. * You may obtain a copy of the License at
  864. *
  865. * http://www.apache.org/licenses/LICENSE-2.0
  866. *
  867. * Unless required by applicable law or agreed to in writing, software
  868. * distributed under the License is distributed on an "AS IS" BASIS,
  869. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  870. * See the License for the specific language governing permissions and
  871. * limitations under the License.
  872. */
  873. class PhoneAuthProvider {
  874. constructor() {
  875. this.providerId = 'phone';
  876. // TODO: remove ts-ignore when moving types from auth-types to auth-compat
  877. // @ts-ignore
  878. this._delegate = new exp.PhoneAuthProvider(unwrap(firebase.auth()));
  879. }
  880. static credential(verificationId, verificationCode) {
  881. return exp.PhoneAuthProvider.credential(verificationId, verificationCode);
  882. }
  883. verifyPhoneNumber(phoneInfoOptions, applicationVerifier) {
  884. return this._delegate.verifyPhoneNumber(
  885. // The implementation matches but the types are subtly incompatible
  886. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  887. phoneInfoOptions, applicationVerifier);
  888. }
  889. unwrap() {
  890. return this._delegate;
  891. }
  892. }
  893. PhoneAuthProvider.PHONE_SIGN_IN_METHOD = exp.PhoneAuthProvider.PHONE_SIGN_IN_METHOD;
  894. PhoneAuthProvider.PROVIDER_ID = exp.PhoneAuthProvider.PROVIDER_ID;
  895. /**
  896. * @license
  897. * Copyright 2020 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. const _assert = exp._assert;
  912. class RecaptchaVerifier {
  913. constructor(container, parameters, app = firebase.app()) {
  914. var _a;
  915. // API key is required for web client RPC calls.
  916. _assert((_a = app.options) === null || _a === void 0 ? void 0 : _a.apiKey, "invalid-api-key" /* exp.AuthErrorCode.INVALID_API_KEY */, {
  917. appName: app.name
  918. });
  919. this._delegate = new exp.RecaptchaVerifier(container,
  920. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  921. parameters,
  922. // TODO: remove ts-ignore when moving types from auth-types to auth-compat
  923. // @ts-ignore
  924. app.auth());
  925. this.type = this._delegate.type;
  926. }
  927. clear() {
  928. this._delegate.clear();
  929. }
  930. render() {
  931. return this._delegate.render();
  932. }
  933. verify() {
  934. return this._delegate.verify();
  935. }
  936. }
  937. /**
  938. * @license
  939. * Copyright 2020 Google LLC
  940. *
  941. * Licensed under the Apache License, Version 2.0 (the "License");
  942. * you may not use this file except in compliance with the License.
  943. * You may obtain a copy of the License at
  944. *
  945. * http://www.apache.org/licenses/LICENSE-2.0
  946. *
  947. * Unless required by applicable law or agreed to in writing, software
  948. * distributed under the License is distributed on an "AS IS" BASIS,
  949. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  950. * See the License for the specific language governing permissions and
  951. * limitations under the License.
  952. */
  953. const AUTH_TYPE = 'auth-compat';
  954. // Create auth components to register with firebase.
  955. // Provides Auth public APIs.
  956. function registerAuthCompat(instance) {
  957. instance.INTERNAL.registerComponent(new Component(AUTH_TYPE, container => {
  958. // getImmediate for FirebaseApp will always succeed
  959. const app = container.getProvider('app-compat').getImmediate();
  960. const authProvider = container.getProvider('auth');
  961. return new Auth(app, authProvider);
  962. }, "PUBLIC" /* ComponentType.PUBLIC */)
  963. .setServiceProps({
  964. ActionCodeInfo: {
  965. Operation: {
  966. EMAIL_SIGNIN: exp.ActionCodeOperation.EMAIL_SIGNIN,
  967. PASSWORD_RESET: exp.ActionCodeOperation.PASSWORD_RESET,
  968. RECOVER_EMAIL: exp.ActionCodeOperation.RECOVER_EMAIL,
  969. REVERT_SECOND_FACTOR_ADDITION: exp.ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION,
  970. VERIFY_AND_CHANGE_EMAIL: exp.ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,
  971. VERIFY_EMAIL: exp.ActionCodeOperation.VERIFY_EMAIL
  972. }
  973. },
  974. EmailAuthProvider: exp.EmailAuthProvider,
  975. FacebookAuthProvider: exp.FacebookAuthProvider,
  976. GithubAuthProvider: exp.GithubAuthProvider,
  977. GoogleAuthProvider: exp.GoogleAuthProvider,
  978. OAuthProvider: exp.OAuthProvider,
  979. SAMLAuthProvider: exp.SAMLAuthProvider,
  980. PhoneAuthProvider: PhoneAuthProvider,
  981. PhoneMultiFactorGenerator: exp.PhoneMultiFactorGenerator,
  982. RecaptchaVerifier: RecaptchaVerifier,
  983. TwitterAuthProvider: exp.TwitterAuthProvider,
  984. Auth,
  985. AuthCredential: exp.AuthCredential,
  986. Error: FirebaseError
  987. })
  988. .setInstantiationMode("LAZY" /* InstantiationMode.LAZY */)
  989. .setMultipleInstances(false));
  990. instance.registerVersion(name, version);
  991. }
  992. registerAuthCompat(firebase);
  993. //# sourceMappingURL=index.esm2017.js.map