No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.node.esm.js 39KB

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