1919import { spawn } from 'child-process-promise' ;
2020import { ChildProcess } from 'child_process' ;
2121import * as fs from 'fs' ;
22+ import * as os from 'os' ;
2223import * as path from 'path' ;
2324import * as request from 'request' ;
2425// @ts -ignore
@@ -28,13 +29,25 @@ export abstract class Emulator {
2829 binaryPath : string | null = null ;
2930 emulator : ChildProcess | null = null ;
3031
32+ cacheDirectory : string ;
33+ cacheBinaryPath : string ;
34+
3135 constructor (
3236 private binaryName : string ,
3337 private binaryUrl : string ,
3438 public port : number
35- ) { }
39+ ) {
40+ this . cacheDirectory = path . join ( os . homedir ( ) , `.cache/firebase-js-sdk` ) ;
41+ this . cacheBinaryPath = path . join ( this . cacheDirectory , binaryName ) ;
42+ }
3643
3744 download ( ) : Promise < void > {
45+ if ( fs . existsSync ( this . cacheBinaryPath ) ) {
46+ console . log ( `Emulator found in cache: ${ this . cacheBinaryPath } ` ) ;
47+ this . binaryPath = this . cacheBinaryPath ;
48+ return Promise . resolve ( ) ;
49+ }
50+
3851 return new Promise < void > ( ( resolve , reject ) => {
3952 tmp . dir ( ( err : Error | null , dir : string ) => {
4053 if ( err ) reject ( err ) ;
@@ -55,6 +68,10 @@ export abstract class Emulator {
5568 if ( err ) reject ( err ) ;
5669 console . log ( `Changed emulator file permissions to 'rwxr-xr-x'.` ) ;
5770 this . binaryPath = filepath ;
71+
72+ if ( this . copyToCache ( ) ) {
73+ console . log ( `Cached emulator at ${ this . cacheBinaryPath } ` ) ;
74+ }
5875 resolve ( ) ;
5976 } ) ;
6077 } )
@@ -129,4 +146,23 @@ export abstract class Emulator {
129146 fs . unlinkSync ( this . binaryPath ) ;
130147 }
131148 }
149+
150+ private copyToCache ( ) : boolean {
151+ if ( ! this . binaryPath ) {
152+ return false ;
153+ }
154+
155+ try {
156+ if ( ! fs . existsSync ( this . cacheDirectory ) ) {
157+ fs . mkdirSync ( this . cacheDirectory , { recursive : true } ) ;
158+ }
159+ fs . copyFileSync ( this . binaryPath , this . cacheBinaryPath ) ;
160+
161+ return true ;
162+ } catch ( e ) {
163+ console . warn ( `Unable to cache ${ this . binaryName } ` , e ) ;
164+ }
165+
166+ return false ;
167+ }
132168}
0 commit comments