import firebase from 'firebase/app' ; import 'firebase/firestore' ; import { AsyncProviders } from 'polar-shared/src/util/Providers' ; import { Firebase } from './Firebase' ; import { Logger } from "polar-shared/src/logger/Logger" ; import { Tracer } from 'polar-shared/src/util/Tracer' ; import { StoreCaches } from "polar-snapshot-cache/src/StoreCaches" ; import { IFirestore } from 'polar-snapshot-cache/src/store/IFirestore' ; const log = Logger . create ( ) ; const ENABLE_PERSISTENCE = StoreCaches . config . backing === 'none' ; const IS_NODE = typeof window === 'undefined' ; export namespace Firestore { let instance ; async function initDelegate ( opts ) { Firebase . init ( ) ; return await createInstance ( opts ) ; } const firestoreProvider = AsyncProviders . memoize1 < FirestoreOptions , firebase . firestore . Firestore > ( initDelegate ) ; /**
     * Allows us to init with custom options.
     */ export async function init ( opts = { enablePersistence : ENABLE_PERSISTENCE } ) { if ( instance ) { return ; } instance = await firestoreProvider ( opts ) ; return instance ; } export async function getInstance ( ) { await init ( ) ; return await StoreCaches . create ( ) . build ( instance ! as any ) ; } async function createInstance ( opts = { } ) { const doExecAsync = async ( ) : Promise < firebase . firestore . Firestore > => { try { log . notice ( "Initializing firestore..." ) ; const firestore = firebase . firestore ( ) ; const settings = { cacheSizeBytes : firebase . firestore . CACHE_SIZE_UNLIMITED } ; firestore . settings ( settings ) ; if ( opts . enablePersistence ) { await enablePersistence ( firestore ) ; } return firestore ; } finally { log . notice ( "Initializing firestore...done" ) ; } } ; return await Tracer . async ( doExecAsync , 'Firestore.createInstance' ) ; } async function enablePersistence ( firestore ) { const doExecAsync = async ( ) => { try { if ( ! IS_NODE ) { console . log ( "Enabling firestore persistence...." ) ; await firestore . enablePersistence ( { synchronizeTabs : true } ) ; console . log ( "Enabling firestore persistence....done" ) ; } } catch ( e ) { console . warn ( "Unable to use persistence. Data will not be cached locally: " , e ) ; } } ; await Tracer . async ( doExecAsync , 'Firestore.enablePersistence' ) ; } } export interface FirestoreOptions { readonly enablePersistence ? : boolean ; }