-
Notifications
You must be signed in to change notification settings - Fork 354
/
firebase-namespace.ts
476 lines (417 loc) · 17.8 KB
/
firebase-namespace.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/*!
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs = require('fs');
import {Agent} from 'http';
import {deepExtend} from './utils/deep-copy';
import {AppErrorCodes, FirebaseAppError} from './utils/error';
import {AppHook, FirebaseApp, FirebaseAppOptions} from './firebase-app';
import {FirebaseServiceFactory, FirebaseServiceInterface} from './firebase-service';
import {
Credential,
RefreshTokenCredential,
ServiceAccountCredential,
getApplicationDefault,
} from './auth/credential';
import {Auth} from './auth/auth';
import {Messaging} from './messaging/messaging';
import {Storage} from './storage/storage';
import {Database} from '@firebase/database';
import {Firestore} from '@google-cloud/firestore';
import {InstanceId} from './instance-id/instance-id';
import {ProjectManagement} from './project-management/project-management';
import { SecurityRules } from './security-rules/security-rules';
import * as validator from './utils/validator';
const DEFAULT_APP_NAME = '[DEFAULT]';
/**
* Constant holding the environment variable name with the default config.
* If the environment variable contains a string that starts with '{' it will be parsed as JSON,
* otherwise it will be assumed to be pointing to a file.
*/
export const FIREBASE_CONFIG_VAR: string = 'FIREBASE_CONFIG';
let globalAppDefaultCred: Credential;
const globalCertCreds: { [key: string]: ServiceAccountCredential } = {};
const globalRefreshTokenCreds: { [key: string]: RefreshTokenCredential } = {};
export interface FirebaseServiceNamespace <T> {
(app?: FirebaseApp): T;
[key: string]: any;
}
/**
* Internals of a FirebaseNamespace instance.
*/
export class FirebaseNamespaceInternals {
public serviceFactories: {[serviceName: string]: FirebaseServiceFactory} = {};
private apps_: {[appName: string]: FirebaseApp} = {};
private appHooks_: {[service: string]: AppHook} = {};
constructor(public firebase_: {[key: string]: any}) {}
/**
* Initializes the FirebaseApp instance.
*
* @param {FirebaseAppOptions} options Optional options for the FirebaseApp instance. If none present
* will try to initialize from the FIREBASE_CONFIG environment variable.
* If the environment variable contains a string that starts with '{'
* it will be parsed as JSON,
* otherwise it will be assumed to be pointing to a file.
* @param {string} [appName] Optional name of the FirebaseApp instance.
*
* @return {FirebaseApp} A new FirebaseApp instance.
*/
public initializeApp(options?: FirebaseAppOptions, appName = DEFAULT_APP_NAME): FirebaseApp {
if (typeof options === 'undefined') {
options = this.loadOptionsFromEnvVar();
options.credential = getApplicationDefault();
}
if (typeof appName !== 'string' || appName === '') {
throw new FirebaseAppError(
AppErrorCodes.INVALID_APP_NAME,
`Invalid Firebase app name "${appName}" provided. App name must be a non-empty string.`,
);
} else if (appName in this.apps_) {
if (appName === DEFAULT_APP_NAME) {
throw new FirebaseAppError(
AppErrorCodes.DUPLICATE_APP,
'The default Firebase app already exists. This means you called initializeApp() ' +
'more than once without providing an app name as the second argument. In most cases ' +
'you only need to call initializeApp() once. But if you do want to initialize ' +
'multiple apps, pass a second argument to initializeApp() to give each app a unique ' +
'name.',
);
} else {
throw new FirebaseAppError(
AppErrorCodes.DUPLICATE_APP,
`Firebase app named "${appName}" already exists. This means you called initializeApp() ` +
'more than once with the same app name as the second argument. Make sure you provide a ' +
'unique name every time you call initializeApp().',
);
}
}
const app = new FirebaseApp(options, appName, this);
this.apps_[appName] = app;
this.callAppHooks_(app, 'create');
return app;
}
/**
* Returns the FirebaseApp instance with the provided name (or the default FirebaseApp instance
* if no name is provided).
*
* @param {string} [appName=DEFAULT_APP_NAME] Optional name of the FirebaseApp instance to return.
* @return {FirebaseApp} The FirebaseApp instance which has the provided name.
*/
public app(appName = DEFAULT_APP_NAME): FirebaseApp {
if (typeof appName !== 'string' || appName === '') {
throw new FirebaseAppError(
AppErrorCodes.INVALID_APP_NAME,
`Invalid Firebase app name "${appName}" provided. App name must be a non-empty string.`,
);
} else if (!(appName in this.apps_)) {
let errorMessage: string = (appName === DEFAULT_APP_NAME)
? 'The default Firebase app does not exist. ' : `Firebase app named "${appName}" does not exist. `;
errorMessage += 'Make sure you call initializeApp() before using any of the Firebase services.';
throw new FirebaseAppError(AppErrorCodes.NO_APP, errorMessage);
}
return this.apps_[appName];
}
/*
* Returns an array of all the non-deleted FirebaseApp instances.
*
* @return {Array<FirebaseApp>} An array of all the non-deleted FirebaseApp instances
*/
public get apps(): FirebaseApp[] {
// Return a copy so the caller cannot mutate the array
return Object.keys(this.apps_).map((appName) => this.apps_[appName]);
}
/*
* Removes the specified FirebaseApp instance.
*
* @param {string} appName The name of the FirebaseApp instance to remove.
*/
public removeApp(appName: string): void {
if (typeof appName === 'undefined') {
throw new FirebaseAppError(
AppErrorCodes.INVALID_APP_NAME,
`No Firebase app name provided. App name must be a non-empty string.`,
);
}
const appToRemove = this.app(appName);
this.callAppHooks_(appToRemove, 'delete');
delete this.apps_[appName];
}
/*
* Registers a new service on this Firebase namespace.
*
* @param {string} serviceName The name of the Firebase service to register.
* @param {FirebaseServiceFactory} createService A factory method to generate an instance of the Firebase service.
* @param {object} [serviceProperties] Optional properties to extend this Firebase namespace with.
* @param {AppHook} [appHook] Optional callback that handles app-related events like app creation and deletion.
* @return {FirebaseServiceNamespace<FirebaseServiceInterface>} The Firebase service's namespace.
*/
public registerService(serviceName: string,
createService: FirebaseServiceFactory,
serviceProperties?: object,
appHook?: AppHook): FirebaseServiceNamespace<FirebaseServiceInterface> {
let errorMessage;
if (typeof serviceName === 'undefined') {
errorMessage = `No service name provided. Service name must be a non-empty string.`;
} else if (typeof serviceName !== 'string' || serviceName === '') {
errorMessage = `Invalid service name "${serviceName}" provided. Service name must be a non-empty string.`;
} else if (serviceName in this.serviceFactories) {
errorMessage = `Firebase service named "${serviceName}" has already been registered.`;
}
if (typeof errorMessage !== 'undefined') {
throw new FirebaseAppError(
AppErrorCodes.INTERNAL_ERROR,
`INTERNAL ASSERT FAILED: ${errorMessage}`,
);
}
this.serviceFactories[serviceName] = createService;
if (appHook) {
this.appHooks_[serviceName] = appHook;
}
let serviceNamespace: FirebaseServiceNamespace<FirebaseServiceInterface>;
// The service namespace is an accessor function which takes a FirebaseApp instance
// or uses the default app if no FirebaseApp instance is provided
serviceNamespace = (appArg?: FirebaseApp) => {
if (typeof appArg === 'undefined') {
appArg = this.app();
}
// Forward service instance lookup to the FirebaseApp
return (appArg as any)[serviceName]();
};
// ... and a container for service-level properties.
if (serviceProperties !== undefined) {
deepExtend(serviceNamespace, serviceProperties);
}
// Monkey-patch the service namespace onto the Firebase namespace
this.firebase_[serviceName] = serviceNamespace;
return serviceNamespace;
}
/**
* Calls the app hooks corresponding to the provided event name for each service within the
* provided FirebaseApp instance.
*
* @param {FirebaseApp} app The FirebaseApp instance whose app hooks to call.
* @param {string} eventName The event name representing which app hooks to call.
*/
private callAppHooks_(app: FirebaseApp, eventName: string) {
Object.keys(this.serviceFactories).forEach((serviceName) => {
if (this.appHooks_[serviceName]) {
this.appHooks_[serviceName](eventName, app);
}
});
}
/**
* Parse the file pointed to by the FIREBASE_CONFIG_VAR, if it exists.
* Or if the FIREBASE_CONFIG_ENV contains a valid JSON object, parse it directly.
* If the environment variable contains a string that starts with '{' it will be parsed as JSON,
* otherwise it will be assumed to be pointing to a file.
*/
private loadOptionsFromEnvVar(): FirebaseAppOptions {
const config = process.env[FIREBASE_CONFIG_VAR];
if (!validator.isNonEmptyString(config)) {
return {};
}
try {
const contents = config.startsWith('{') ? config : fs.readFileSync(config, 'utf8');
return JSON.parse(contents) as FirebaseAppOptions;
} catch (error) {
// Throw a nicely formed error message if the file contents cannot be parsed
throw new FirebaseAppError(
AppErrorCodes.INVALID_APP_OPTIONS,
'Failed to parse app options file: ' + error,
);
}
}
}
const firebaseCredential = {
cert: (serviceAccountPathOrObject: string | object, httpAgent?: Agent): Credential => {
const stringifiedServiceAccount = JSON.stringify(serviceAccountPathOrObject);
if (!(stringifiedServiceAccount in globalCertCreds)) {
globalCertCreds[stringifiedServiceAccount] = new ServiceAccountCredential(serviceAccountPathOrObject, httpAgent);
}
return globalCertCreds[stringifiedServiceAccount];
},
refreshToken: (refreshTokenPathOrObject: string | object, httpAgent?: Agent): Credential => {
const stringifiedRefreshToken = JSON.stringify(refreshTokenPathOrObject);
if (!(stringifiedRefreshToken in globalRefreshTokenCreds)) {
globalRefreshTokenCreds[stringifiedRefreshToken] = new RefreshTokenCredential(
refreshTokenPathOrObject, httpAgent);
}
return globalRefreshTokenCreds[stringifiedRefreshToken];
},
applicationDefault: (httpAgent?: Agent): Credential => {
if (typeof globalAppDefaultCred === 'undefined') {
globalAppDefaultCred = getApplicationDefault(httpAgent);
}
return globalAppDefaultCred;
},
};
/**
* Global Firebase context object.
*/
export class FirebaseNamespace {
// Hack to prevent Babel from modifying the object returned as the default admin namespace.
/* tslint:disable:variable-name */
public __esModule = true;
/* tslint:enable:variable-name */
public credential = firebaseCredential;
public SDK_VERSION = '<XXX_SDK_VERSION_XXX>';
public INTERNAL: FirebaseNamespaceInternals;
/* tslint:disable */
// TODO(jwenger): Database is the only consumer of firebase.Promise. We should update it to use
// use the native Promise and then remove this.
public Promise: any = Promise;
/* tslint:enable */
constructor() {
this.INTERNAL = new FirebaseNamespaceInternals(this);
}
/**
* Gets the `Auth` service namespace. The returned namespace can be used to get the
* `Auth` service for the default app or an explicitly specified app.
*/
get auth(): FirebaseServiceNamespace<Auth> {
const fn: FirebaseServiceNamespace<Auth> = (app?: FirebaseApp) => {
return this.ensureApp(app).auth();
};
const auth = require('./auth/auth').Auth;
return Object.assign(fn, {Auth: auth});
}
/**
* Gets the `Database` service namespace. The returned namespace can be used to get the
* `Database` service for the default app or an explicitly specified app.
*/
get database(): FirebaseServiceNamespace<Database> {
const fn: FirebaseServiceNamespace<Database> = (app?: FirebaseApp) => {
return this.ensureApp(app).database();
};
return Object.assign(fn, require('@firebase/database'));
}
/**
* Gets the `Messaging` service namespace. The returned namespace can be used to get the
* `Messaging` service for the default app or an explicitly specified app.
*/
get messaging(): FirebaseServiceNamespace<Messaging> {
const fn: FirebaseServiceNamespace<Messaging> = (app?: FirebaseApp) => {
return this.ensureApp(app).messaging();
};
const messaging = require('./messaging/messaging').Messaging;
return Object.assign(fn, {Messaging: messaging});
}
/**
* Gets the `Storage` service namespace. The returned namespace can be used to get the
* `Storage` service for the default app or an explicitly specified app.
*/
get storage(): FirebaseServiceNamespace<Storage> {
const fn: FirebaseServiceNamespace<Storage> = (app?: FirebaseApp) => {
return this.ensureApp(app).storage();
};
const storage = require('./storage/storage').Storage;
return Object.assign(fn, {Storage: storage});
}
/**
* Gets the `Firestore` service namespace. The returned namespace can be used to get the
* `Firestore` service for the default app or an explicitly specified app.
*/
get firestore(): FirebaseServiceNamespace<Firestore> {
let fn: FirebaseServiceNamespace<Firestore> = (app?: FirebaseApp) => {
return this.ensureApp(app).firestore();
};
const firestore = require('@google-cloud/firestore');
fn = Object.assign(fn, firestore.Firestore);
// `v1beta1` and `v1` are lazy-loaded in the Firestore SDK. We use the same trick here
// to avoid triggering this lazy-loading upon initialization.
Object.defineProperty(fn, 'v1beta1', {
get: () => {
return firestore.v1beta1;
},
});
Object.defineProperty(fn, 'v1', {
get: () => {
return firestore.v1;
},
});
return fn;
}
/**
* Gets the `InstanceId` service namespace. The returned namespace can be used to get the
* `Instance` service for the default app or an explicitly specified app.
*/
get instanceId(): FirebaseServiceNamespace<InstanceId> {
const fn: FirebaseServiceNamespace<InstanceId> = (app?: FirebaseApp) => {
return this.ensureApp(app).instanceId();
};
const instanceId = require('./instance-id/instance-id').InstanceId;
return Object.assign(fn, {InstanceId: instanceId});
}
/**
* Gets the `ProjectManagement` service namespace. The returned namespace can be used to get the
* `ProjectManagement` service for the default app or an explicitly specified app.
*/
get projectManagement(): FirebaseServiceNamespace<ProjectManagement> {
const fn: FirebaseServiceNamespace<ProjectManagement> = (app?: FirebaseApp) => {
return this.ensureApp(app).projectManagement();
};
const projectManagement = require('./project-management/project-management').ProjectManagement;
return Object.assign(fn, {ProjectManagement: projectManagement});
}
/**
* Gets the `SecurityRules` service namespace. The returned namespace can be used to get the
* `SecurityRules` service for the default app or an explicitly specified app.
*/
get securityRules(): FirebaseServiceNamespace<SecurityRules> {
const fn: FirebaseServiceNamespace<SecurityRules> = (app?: FirebaseApp) => {
return this.ensureApp(app).securityRules();
};
const securityRules = require('./security-rules/security-rules').SecurityRules;
return Object.assign(fn, {SecurityRules: securityRules});
}
/**
* Initializes the FirebaseApp instance.
*
* @param {FirebaseAppOptions} [options] Optional options for the FirebaseApp instance.
* If none present will try to initialize from the FIREBASE_CONFIG environment variable.
* If the environment variable contains a string that starts with '{' it will be parsed as JSON,
* otherwise it will be assumed to be pointing to a file.
* @param {string} [appName] Optional name of the FirebaseApp instance.
*
* @return {FirebaseApp} A new FirebaseApp instance.
*/
public initializeApp(options?: FirebaseAppOptions, appName?: string): FirebaseApp {
return this.INTERNAL.initializeApp(options, appName);
}
/**
* Returns the FirebaseApp instance with the provided name (or the default FirebaseApp instance
* if no name is provided).
*
* @param {string} [appName] Optional name of the FirebaseApp instance to return.
* @return {FirebaseApp} The FirebaseApp instance which has the provided name.
*/
public app(appName?: string): FirebaseApp {
return this.INTERNAL.app(appName);
}
/*
* Returns an array of all the non-deleted FirebaseApp instances.
*
* @return {Array<FirebaseApp>} An array of all the non-deleted FirebaseApp instances
*/
public get apps(): FirebaseApp[] {
return this.INTERNAL.apps;
}
private ensureApp(app?: FirebaseApp): FirebaseApp {
if (typeof app === 'undefined') {
app = this.app();
}
return app;
}
}