@firebase/installations 0.6.9 → 0.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1424 +0,0 @@
1
- import { getApp, _getProvider, _registerComponent, registerVersion } from '@firebase/app';
2
- import { Component } from '@firebase/component';
3
- import { __awaiter, __generator, __spreadArray, __read, __values, __assign } from 'tslib';
4
- import { ErrorFactory, FirebaseError } from '@firebase/util';
5
- import { openDB } from 'idb';
6
-
7
- var name = "@firebase/installations";
8
- var version = "0.6.9";
9
-
10
- /**
11
- * @license
12
- * Copyright 2019 Google LLC
13
- *
14
- * Licensed under the Apache License, Version 2.0 (the "License");
15
- * you may not use this file except in compliance with the License.
16
- * You may obtain a copy of the License at
17
- *
18
- * http://www.apache.org/licenses/LICENSE-2.0
19
- *
20
- * Unless required by applicable law or agreed to in writing, software
21
- * distributed under the License is distributed on an "AS IS" BASIS,
22
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
- * See the License for the specific language governing permissions and
24
- * limitations under the License.
25
- */
26
- var PENDING_TIMEOUT_MS = 10000;
27
- var PACKAGE_VERSION = "w:".concat(version);
28
- var INTERNAL_AUTH_VERSION = 'FIS_v2';
29
- var INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';
30
- var TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour
31
- var SERVICE = 'installations';
32
- var SERVICE_NAME = 'Installations';
33
-
34
- /**
35
- * @license
36
- * Copyright 2019 Google LLC
37
- *
38
- * Licensed under the Apache License, Version 2.0 (the "License");
39
- * you may not use this file except in compliance with the License.
40
- * You may obtain a copy of the License at
41
- *
42
- * http://www.apache.org/licenses/LICENSE-2.0
43
- *
44
- * Unless required by applicable law or agreed to in writing, software
45
- * distributed under the License is distributed on an "AS IS" BASIS,
46
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
47
- * See the License for the specific language governing permissions and
48
- * limitations under the License.
49
- */
50
- var _a;
51
- var ERROR_DESCRIPTION_MAP = (_a = {},
52
- _a["missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */] = 'Missing App configuration value: "{$valueName}"',
53
- _a["not-registered" /* ErrorCode.NOT_REGISTERED */] = 'Firebase Installation is not registered.',
54
- _a["installation-not-found" /* ErrorCode.INSTALLATION_NOT_FOUND */] = 'Firebase Installation not found.',
55
- _a["request-failed" /* ErrorCode.REQUEST_FAILED */] = '{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',
56
- _a["app-offline" /* ErrorCode.APP_OFFLINE */] = 'Could not process request. Application offline.',
57
- _a["delete-pending-registration" /* ErrorCode.DELETE_PENDING_REGISTRATION */] = "Can't delete installation while there is a pending registration request.",
58
- _a);
59
- var ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);
60
- /** Returns true if error is a FirebaseError that is based on an error from the server. */
61
- function isServerError(error) {
62
- return (error instanceof FirebaseError &&
63
- error.code.includes("request-failed" /* ErrorCode.REQUEST_FAILED */));
64
- }
65
-
66
- /**
67
- * @license
68
- * Copyright 2019 Google LLC
69
- *
70
- * Licensed under the Apache License, Version 2.0 (the "License");
71
- * you may not use this file except in compliance with the License.
72
- * You may obtain a copy of the License at
73
- *
74
- * http://www.apache.org/licenses/LICENSE-2.0
75
- *
76
- * Unless required by applicable law or agreed to in writing, software
77
- * distributed under the License is distributed on an "AS IS" BASIS,
78
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
79
- * See the License for the specific language governing permissions and
80
- * limitations under the License.
81
- */
82
- function getInstallationsEndpoint(_a) {
83
- var projectId = _a.projectId;
84
- return "".concat(INSTALLATIONS_API_URL, "/projects/").concat(projectId, "/installations");
85
- }
86
- function extractAuthTokenInfoFromResponse(response) {
87
- return {
88
- token: response.token,
89
- requestStatus: 2 /* RequestStatus.COMPLETED */,
90
- expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),
91
- creationTime: Date.now()
92
- };
93
- }
94
- function getErrorFromResponse(requestName, response) {
95
- return __awaiter(this, void 0, void 0, function () {
96
- var responseJson, errorData;
97
- return __generator(this, function (_a) {
98
- switch (_a.label) {
99
- case 0: return [4 /*yield*/, response.json()];
100
- case 1:
101
- responseJson = _a.sent();
102
- errorData = responseJson.error;
103
- return [2 /*return*/, ERROR_FACTORY.create("request-failed" /* ErrorCode.REQUEST_FAILED */, {
104
- requestName: requestName,
105
- serverCode: errorData.code,
106
- serverMessage: errorData.message,
107
- serverStatus: errorData.status
108
- })];
109
- }
110
- });
111
- });
112
- }
113
- function getHeaders(_a) {
114
- var apiKey = _a.apiKey;
115
- return new Headers({
116
- 'Content-Type': 'application/json',
117
- Accept: 'application/json',
118
- 'x-goog-api-key': apiKey
119
- });
120
- }
121
- function getHeadersWithAuth(appConfig, _a) {
122
- var refreshToken = _a.refreshToken;
123
- var headers = getHeaders(appConfig);
124
- headers.append('Authorization', getAuthorizationHeader(refreshToken));
125
- return headers;
126
- }
127
- /**
128
- * Calls the passed in fetch wrapper and returns the response.
129
- * If the returned response has a status of 5xx, re-runs the function once and
130
- * returns the response.
131
- */
132
- function retryIfServerError(fn) {
133
- return __awaiter(this, void 0, void 0, function () {
134
- var result;
135
- return __generator(this, function (_a) {
136
- switch (_a.label) {
137
- case 0: return [4 /*yield*/, fn()];
138
- case 1:
139
- result = _a.sent();
140
- if (result.status >= 500 && result.status < 600) {
141
- // Internal Server Error. Retry request.
142
- return [2 /*return*/, fn()];
143
- }
144
- return [2 /*return*/, result];
145
- }
146
- });
147
- });
148
- }
149
- function getExpiresInFromResponseExpiresIn(responseExpiresIn) {
150
- // This works because the server will never respond with fractions of a second.
151
- return Number(responseExpiresIn.replace('s', '000'));
152
- }
153
- function getAuthorizationHeader(refreshToken) {
154
- return "".concat(INTERNAL_AUTH_VERSION, " ").concat(refreshToken);
155
- }
156
-
157
- /**
158
- * @license
159
- * Copyright 2019 Google LLC
160
- *
161
- * Licensed under the Apache License, Version 2.0 (the "License");
162
- * you may not use this file except in compliance with the License.
163
- * You may obtain a copy of the License at
164
- *
165
- * http://www.apache.org/licenses/LICENSE-2.0
166
- *
167
- * Unless required by applicable law or agreed to in writing, software
168
- * distributed under the License is distributed on an "AS IS" BASIS,
169
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
170
- * See the License for the specific language governing permissions and
171
- * limitations under the License.
172
- */
173
- function createInstallationRequest(_a, _b) {
174
- var appConfig = _a.appConfig, heartbeatServiceProvider = _a.heartbeatServiceProvider;
175
- var fid = _b.fid;
176
- return __awaiter(this, void 0, void 0, function () {
177
- var endpoint, headers, heartbeatService, heartbeatsHeader, body, request, response, responseValue, registeredInstallationEntry;
178
- return __generator(this, function (_c) {
179
- switch (_c.label) {
180
- case 0:
181
- endpoint = getInstallationsEndpoint(appConfig);
182
- headers = getHeaders(appConfig);
183
- heartbeatService = heartbeatServiceProvider.getImmediate({
184
- optional: true
185
- });
186
- if (!heartbeatService) return [3 /*break*/, 2];
187
- return [4 /*yield*/, heartbeatService.getHeartbeatsHeader()];
188
- case 1:
189
- heartbeatsHeader = _c.sent();
190
- if (heartbeatsHeader) {
191
- headers.append('x-firebase-client', heartbeatsHeader);
192
- }
193
- _c.label = 2;
194
- case 2:
195
- body = {
196
- fid: fid,
197
- authVersion: INTERNAL_AUTH_VERSION,
198
- appId: appConfig.appId,
199
- sdkVersion: PACKAGE_VERSION
200
- };
201
- request = {
202
- method: 'POST',
203
- headers: headers,
204
- body: JSON.stringify(body)
205
- };
206
- return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })];
207
- case 3:
208
- response = _c.sent();
209
- if (!response.ok) return [3 /*break*/, 5];
210
- return [4 /*yield*/, response.json()];
211
- case 4:
212
- responseValue = _c.sent();
213
- registeredInstallationEntry = {
214
- fid: responseValue.fid || fid,
215
- registrationStatus: 2 /* RequestStatus.COMPLETED */,
216
- refreshToken: responseValue.refreshToken,
217
- authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)
218
- };
219
- return [2 /*return*/, registeredInstallationEntry];
220
- case 5: return [4 /*yield*/, getErrorFromResponse('Create Installation', response)];
221
- case 6: throw _c.sent();
222
- }
223
- });
224
- });
225
- }
226
-
227
- /**
228
- * @license
229
- * Copyright 2019 Google LLC
230
- *
231
- * Licensed under the Apache License, Version 2.0 (the "License");
232
- * you may not use this file except in compliance with the License.
233
- * You may obtain a copy of the License at
234
- *
235
- * http://www.apache.org/licenses/LICENSE-2.0
236
- *
237
- * Unless required by applicable law or agreed to in writing, software
238
- * distributed under the License is distributed on an "AS IS" BASIS,
239
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
240
- * See the License for the specific language governing permissions and
241
- * limitations under the License.
242
- */
243
- /** Returns a promise that resolves after given time passes. */
244
- function sleep(ms) {
245
- return new Promise(function (resolve) {
246
- setTimeout(resolve, ms);
247
- });
248
- }
249
-
250
- /**
251
- * @license
252
- * Copyright 2019 Google LLC
253
- *
254
- * Licensed under the Apache License, Version 2.0 (the "License");
255
- * you may not use this file except in compliance with the License.
256
- * You may obtain a copy of the License at
257
- *
258
- * http://www.apache.org/licenses/LICENSE-2.0
259
- *
260
- * Unless required by applicable law or agreed to in writing, software
261
- * distributed under the License is distributed on an "AS IS" BASIS,
262
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
263
- * See the License for the specific language governing permissions and
264
- * limitations under the License.
265
- */
266
- function bufferToBase64UrlSafe(array) {
267
- var b64 = btoa(String.fromCharCode.apply(String, __spreadArray([], __read(array), false)));
268
- return b64.replace(/\+/g, '-').replace(/\//g, '_');
269
- }
270
-
271
- /**
272
- * @license
273
- * Copyright 2019 Google LLC
274
- *
275
- * Licensed under the Apache License, Version 2.0 (the "License");
276
- * you may not use this file except in compliance with the License.
277
- * You may obtain a copy of the License at
278
- *
279
- * http://www.apache.org/licenses/LICENSE-2.0
280
- *
281
- * Unless required by applicable law or agreed to in writing, software
282
- * distributed under the License is distributed on an "AS IS" BASIS,
283
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
284
- * See the License for the specific language governing permissions and
285
- * limitations under the License.
286
- */
287
- var VALID_FID_PATTERN = /^[cdef][\w-]{21}$/;
288
- var INVALID_FID = '';
289
- /**
290
- * Generates a new FID using random values from Web Crypto API.
291
- * Returns an empty string if FID generation fails for any reason.
292
- */
293
- function generateFid() {
294
- try {
295
- // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5
296
- // bytes. our implementation generates a 17 byte array instead.
297
- var fidByteArray = new Uint8Array(17);
298
- var crypto_1 = self.crypto || self.msCrypto;
299
- crypto_1.getRandomValues(fidByteArray);
300
- // Replace the first 4 random bits with the constant FID header of 0b0111.
301
- fidByteArray[0] = 112 + (fidByteArray[0] % 16);
302
- var fid = encode(fidByteArray);
303
- return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;
304
- }
305
- catch (_a) {
306
- // FID generation errored
307
- return INVALID_FID;
308
- }
309
- }
310
- /** Converts a FID Uint8Array to a base64 string representation. */
311
- function encode(fidByteArray) {
312
- var b64String = bufferToBase64UrlSafe(fidByteArray);
313
- // Remove the 23rd character that was added because of the extra 4 bits at the
314
- // end of our 17 byte array, and the '=' padding.
315
- return b64String.substr(0, 22);
316
- }
317
-
318
- /**
319
- * @license
320
- * Copyright 2019 Google LLC
321
- *
322
- * Licensed under the Apache License, Version 2.0 (the "License");
323
- * you may not use this file except in compliance with the License.
324
- * You may obtain a copy of the License at
325
- *
326
- * http://www.apache.org/licenses/LICENSE-2.0
327
- *
328
- * Unless required by applicable law or agreed to in writing, software
329
- * distributed under the License is distributed on an "AS IS" BASIS,
330
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
331
- * See the License for the specific language governing permissions and
332
- * limitations under the License.
333
- */
334
- /** Returns a string key that can be used to identify the app. */
335
- function getKey(appConfig) {
336
- return "".concat(appConfig.appName, "!").concat(appConfig.appId);
337
- }
338
-
339
- /**
340
- * @license
341
- * Copyright 2019 Google LLC
342
- *
343
- * Licensed under the Apache License, Version 2.0 (the "License");
344
- * you may not use this file except in compliance with the License.
345
- * You may obtain a copy of the License at
346
- *
347
- * http://www.apache.org/licenses/LICENSE-2.0
348
- *
349
- * Unless required by applicable law or agreed to in writing, software
350
- * distributed under the License is distributed on an "AS IS" BASIS,
351
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
352
- * See the License for the specific language governing permissions and
353
- * limitations under the License.
354
- */
355
- var fidChangeCallbacks = new Map();
356
- /**
357
- * Calls the onIdChange callbacks with the new FID value, and broadcasts the
358
- * change to other tabs.
359
- */
360
- function fidChanged(appConfig, fid) {
361
- var key = getKey(appConfig);
362
- callFidChangeCallbacks(key, fid);
363
- broadcastFidChange(key, fid);
364
- }
365
- function addCallback(appConfig, callback) {
366
- // Open the broadcast channel if it's not already open,
367
- // to be able to listen to change events from other tabs.
368
- getBroadcastChannel();
369
- var key = getKey(appConfig);
370
- var callbackSet = fidChangeCallbacks.get(key);
371
- if (!callbackSet) {
372
- callbackSet = new Set();
373
- fidChangeCallbacks.set(key, callbackSet);
374
- }
375
- callbackSet.add(callback);
376
- }
377
- function removeCallback(appConfig, callback) {
378
- var key = getKey(appConfig);
379
- var callbackSet = fidChangeCallbacks.get(key);
380
- if (!callbackSet) {
381
- return;
382
- }
383
- callbackSet.delete(callback);
384
- if (callbackSet.size === 0) {
385
- fidChangeCallbacks.delete(key);
386
- }
387
- // Close broadcast channel if there are no more callbacks.
388
- closeBroadcastChannel();
389
- }
390
- function callFidChangeCallbacks(key, fid) {
391
- var e_1, _a;
392
- var callbacks = fidChangeCallbacks.get(key);
393
- if (!callbacks) {
394
- return;
395
- }
396
- try {
397
- for (var callbacks_1 = __values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) {
398
- var callback = callbacks_1_1.value;
399
- callback(fid);
400
- }
401
- }
402
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
403
- finally {
404
- try {
405
- if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1);
406
- }
407
- finally { if (e_1) throw e_1.error; }
408
- }
409
- }
410
- function broadcastFidChange(key, fid) {
411
- var channel = getBroadcastChannel();
412
- if (channel) {
413
- channel.postMessage({ key: key, fid: fid });
414
- }
415
- closeBroadcastChannel();
416
- }
417
- var broadcastChannel = null;
418
- /** Opens and returns a BroadcastChannel if it is supported by the browser. */
419
- function getBroadcastChannel() {
420
- if (!broadcastChannel && 'BroadcastChannel' in self) {
421
- broadcastChannel = new BroadcastChannel('[Firebase] FID Change');
422
- broadcastChannel.onmessage = function (e) {
423
- callFidChangeCallbacks(e.data.key, e.data.fid);
424
- };
425
- }
426
- return broadcastChannel;
427
- }
428
- function closeBroadcastChannel() {
429
- if (fidChangeCallbacks.size === 0 && broadcastChannel) {
430
- broadcastChannel.close();
431
- broadcastChannel = null;
432
- }
433
- }
434
-
435
- /**
436
- * @license
437
- * Copyright 2019 Google LLC
438
- *
439
- * Licensed under the Apache License, Version 2.0 (the "License");
440
- * you may not use this file except in compliance with the License.
441
- * You may obtain a copy of the License at
442
- *
443
- * http://www.apache.org/licenses/LICENSE-2.0
444
- *
445
- * Unless required by applicable law or agreed to in writing, software
446
- * distributed under the License is distributed on an "AS IS" BASIS,
447
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
448
- * See the License for the specific language governing permissions and
449
- * limitations under the License.
450
- */
451
- var DATABASE_NAME = 'firebase-installations-database';
452
- var DATABASE_VERSION = 1;
453
- var OBJECT_STORE_NAME = 'firebase-installations-store';
454
- var dbPromise = null;
455
- function getDbPromise() {
456
- if (!dbPromise) {
457
- dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {
458
- upgrade: function (db, oldVersion) {
459
- // We don't use 'break' in this switch statement, the fall-through
460
- // behavior is what we want, because if there are multiple versions between
461
- // the old version and the current version, we want ALL the migrations
462
- // that correspond to those versions to run, not only the last one.
463
- // eslint-disable-next-line default-case
464
- switch (oldVersion) {
465
- case 0:
466
- db.createObjectStore(OBJECT_STORE_NAME);
467
- }
468
- }
469
- });
470
- }
471
- return dbPromise;
472
- }
473
- /** Assigns or overwrites the record for the given key with the given value. */
474
- function set(appConfig, value) {
475
- return __awaiter(this, void 0, void 0, function () {
476
- var key, db, tx, objectStore, oldValue;
477
- return __generator(this, function (_a) {
478
- switch (_a.label) {
479
- case 0:
480
- key = getKey(appConfig);
481
- return [4 /*yield*/, getDbPromise()];
482
- case 1:
483
- db = _a.sent();
484
- tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
485
- objectStore = tx.objectStore(OBJECT_STORE_NAME);
486
- return [4 /*yield*/, objectStore.get(key)];
487
- case 2:
488
- oldValue = (_a.sent());
489
- return [4 /*yield*/, objectStore.put(value, key)];
490
- case 3:
491
- _a.sent();
492
- return [4 /*yield*/, tx.done];
493
- case 4:
494
- _a.sent();
495
- if (!oldValue || oldValue.fid !== value.fid) {
496
- fidChanged(appConfig, value.fid);
497
- }
498
- return [2 /*return*/, value];
499
- }
500
- });
501
- });
502
- }
503
- /** Removes record(s) from the objectStore that match the given key. */
504
- function remove(appConfig) {
505
- return __awaiter(this, void 0, void 0, function () {
506
- var key, db, tx;
507
- return __generator(this, function (_a) {
508
- switch (_a.label) {
509
- case 0:
510
- key = getKey(appConfig);
511
- return [4 /*yield*/, getDbPromise()];
512
- case 1:
513
- db = _a.sent();
514
- tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
515
- return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).delete(key)];
516
- case 2:
517
- _a.sent();
518
- return [4 /*yield*/, tx.done];
519
- case 3:
520
- _a.sent();
521
- return [2 /*return*/];
522
- }
523
- });
524
- });
525
- }
526
- /**
527
- * Atomically updates a record with the result of updateFn, which gets
528
- * called with the current value. If newValue is undefined, the record is
529
- * deleted instead.
530
- * @return Updated value
531
- */
532
- function update(appConfig, updateFn) {
533
- return __awaiter(this, void 0, void 0, function () {
534
- var key, db, tx, store, oldValue, newValue;
535
- return __generator(this, function (_a) {
536
- switch (_a.label) {
537
- case 0:
538
- key = getKey(appConfig);
539
- return [4 /*yield*/, getDbPromise()];
540
- case 1:
541
- db = _a.sent();
542
- tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
543
- store = tx.objectStore(OBJECT_STORE_NAME);
544
- return [4 /*yield*/, store.get(key)];
545
- case 2:
546
- oldValue = (_a.sent());
547
- newValue = updateFn(oldValue);
548
- if (!(newValue === undefined)) return [3 /*break*/, 4];
549
- return [4 /*yield*/, store.delete(key)];
550
- case 3:
551
- _a.sent();
552
- return [3 /*break*/, 6];
553
- case 4: return [4 /*yield*/, store.put(newValue, key)];
554
- case 5:
555
- _a.sent();
556
- _a.label = 6;
557
- case 6: return [4 /*yield*/, tx.done];
558
- case 7:
559
- _a.sent();
560
- if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {
561
- fidChanged(appConfig, newValue.fid);
562
- }
563
- return [2 /*return*/, newValue];
564
- }
565
- });
566
- });
567
- }
568
-
569
- /**
570
- * @license
571
- * Copyright 2019 Google LLC
572
- *
573
- * Licensed under the Apache License, Version 2.0 (the "License");
574
- * you may not use this file except in compliance with the License.
575
- * You may obtain a copy of the License at
576
- *
577
- * http://www.apache.org/licenses/LICENSE-2.0
578
- *
579
- * Unless required by applicable law or agreed to in writing, software
580
- * distributed under the License is distributed on an "AS IS" BASIS,
581
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
582
- * See the License for the specific language governing permissions and
583
- * limitations under the License.
584
- */
585
- /**
586
- * Updates and returns the InstallationEntry from the database.
587
- * Also triggers a registration request if it is necessary and possible.
588
- */
589
- function getInstallationEntry(installations) {
590
- return __awaiter(this, void 0, void 0, function () {
591
- var registrationPromise, installationEntry;
592
- var _a;
593
- return __generator(this, function (_b) {
594
- switch (_b.label) {
595
- case 0: return [4 /*yield*/, update(installations.appConfig, function (oldEntry) {
596
- var installationEntry = updateOrCreateInstallationEntry(oldEntry);
597
- var entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry);
598
- registrationPromise = entryWithPromise.registrationPromise;
599
- return entryWithPromise.installationEntry;
600
- })];
601
- case 1:
602
- installationEntry = _b.sent();
603
- if (!(installationEntry.fid === INVALID_FID)) return [3 /*break*/, 3];
604
- _a = {};
605
- return [4 /*yield*/, registrationPromise];
606
- case 2:
607
- // FID generation failed. Waiting for the FID from the server.
608
- return [2 /*return*/, (_a.installationEntry = _b.sent(), _a)];
609
- case 3: return [2 /*return*/, {
610
- installationEntry: installationEntry,
611
- registrationPromise: registrationPromise
612
- }];
613
- }
614
- });
615
- });
616
- }
617
- /**
618
- * Creates a new Installation Entry if one does not exist.
619
- * Also clears timed out pending requests.
620
- */
621
- function updateOrCreateInstallationEntry(oldEntry) {
622
- var entry = oldEntry || {
623
- fid: generateFid(),
624
- registrationStatus: 0 /* RequestStatus.NOT_STARTED */
625
- };
626
- return clearTimedOutRequest(entry);
627
- }
628
- /**
629
- * If the Firebase Installation is not registered yet, this will trigger the
630
- * registration and return an InProgressInstallationEntry.
631
- *
632
- * If registrationPromise does not exist, the installationEntry is guaranteed
633
- * to be registered.
634
- */
635
- function triggerRegistrationIfNecessary(installations, installationEntry) {
636
- if (installationEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {
637
- if (!navigator.onLine) {
638
- // Registration required but app is offline.
639
- var registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create("app-offline" /* ErrorCode.APP_OFFLINE */));
640
- return {
641
- installationEntry: installationEntry,
642
- registrationPromise: registrationPromiseWithError
643
- };
644
- }
645
- // Try registering. Change status to IN_PROGRESS.
646
- var inProgressEntry = {
647
- fid: installationEntry.fid,
648
- registrationStatus: 1 /* RequestStatus.IN_PROGRESS */,
649
- registrationTime: Date.now()
650
- };
651
- var registrationPromise = registerInstallation(installations, inProgressEntry);
652
- return { installationEntry: inProgressEntry, registrationPromise: registrationPromise };
653
- }
654
- else if (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {
655
- return {
656
- installationEntry: installationEntry,
657
- registrationPromise: waitUntilFidRegistration(installations)
658
- };
659
- }
660
- else {
661
- return { installationEntry: installationEntry };
662
- }
663
- }
664
- /** This will be executed only once for each new Firebase Installation. */
665
- function registerInstallation(installations, installationEntry) {
666
- return __awaiter(this, void 0, void 0, function () {
667
- var registeredInstallationEntry, e_1;
668
- return __generator(this, function (_a) {
669
- switch (_a.label) {
670
- case 0:
671
- _a.trys.push([0, 2, , 7]);
672
- return [4 /*yield*/, createInstallationRequest(installations, installationEntry)];
673
- case 1:
674
- registeredInstallationEntry = _a.sent();
675
- return [2 /*return*/, set(installations.appConfig, registeredInstallationEntry)];
676
- case 2:
677
- e_1 = _a.sent();
678
- if (!(isServerError(e_1) && e_1.customData.serverCode === 409)) return [3 /*break*/, 4];
679
- // Server returned a "FID cannot be used" error.
680
- // Generate a new ID next time.
681
- return [4 /*yield*/, remove(installations.appConfig)];
682
- case 3:
683
- // Server returned a "FID cannot be used" error.
684
- // Generate a new ID next time.
685
- _a.sent();
686
- return [3 /*break*/, 6];
687
- case 4:
688
- // Registration failed. Set FID as not registered.
689
- return [4 /*yield*/, set(installations.appConfig, {
690
- fid: installationEntry.fid,
691
- registrationStatus: 0 /* RequestStatus.NOT_STARTED */
692
- })];
693
- case 5:
694
- // Registration failed. Set FID as not registered.
695
- _a.sent();
696
- _a.label = 6;
697
- case 6: throw e_1;
698
- case 7: return [2 /*return*/];
699
- }
700
- });
701
- });
702
- }
703
- /** Call if FID registration is pending in another request. */
704
- function waitUntilFidRegistration(installations) {
705
- return __awaiter(this, void 0, void 0, function () {
706
- var entry, _a, installationEntry, registrationPromise;
707
- return __generator(this, function (_b) {
708
- switch (_b.label) {
709
- case 0: return [4 /*yield*/, updateInstallationRequest(installations.appConfig)];
710
- case 1:
711
- entry = _b.sent();
712
- _b.label = 2;
713
- case 2:
714
- if (!(entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */)) return [3 /*break*/, 5];
715
- // createInstallation request still in progress.
716
- return [4 /*yield*/, sleep(100)];
717
- case 3:
718
- // createInstallation request still in progress.
719
- _b.sent();
720
- return [4 /*yield*/, updateInstallationRequest(installations.appConfig)];
721
- case 4:
722
- entry = _b.sent();
723
- return [3 /*break*/, 2];
724
- case 5:
725
- if (!(entry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */)) return [3 /*break*/, 7];
726
- return [4 /*yield*/, getInstallationEntry(installations)];
727
- case 6:
728
- _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise;
729
- if (registrationPromise) {
730
- return [2 /*return*/, registrationPromise];
731
- }
732
- else {
733
- // if there is no registrationPromise, entry is registered.
734
- return [2 /*return*/, installationEntry];
735
- }
736
- case 7: return [2 /*return*/, entry];
737
- }
738
- });
739
- });
740
- }
741
- /**
742
- * Called only if there is a CreateInstallation request in progress.
743
- *
744
- * Updates the InstallationEntry in the DB based on the status of the
745
- * CreateInstallation request.
746
- *
747
- * Returns the updated InstallationEntry.
748
- */
749
- function updateInstallationRequest(appConfig) {
750
- return update(appConfig, function (oldEntry) {
751
- if (!oldEntry) {
752
- throw ERROR_FACTORY.create("installation-not-found" /* ErrorCode.INSTALLATION_NOT_FOUND */);
753
- }
754
- return clearTimedOutRequest(oldEntry);
755
- });
756
- }
757
- function clearTimedOutRequest(entry) {
758
- if (hasInstallationRequestTimedOut(entry)) {
759
- return {
760
- fid: entry.fid,
761
- registrationStatus: 0 /* RequestStatus.NOT_STARTED */
762
- };
763
- }
764
- return entry;
765
- }
766
- function hasInstallationRequestTimedOut(installationEntry) {
767
- return (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */ &&
768
- installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());
769
- }
770
-
771
- /**
772
- * @license
773
- * Copyright 2019 Google LLC
774
- *
775
- * Licensed under the Apache License, Version 2.0 (the "License");
776
- * you may not use this file except in compliance with the License.
777
- * You may obtain a copy of the License at
778
- *
779
- * http://www.apache.org/licenses/LICENSE-2.0
780
- *
781
- * Unless required by applicable law or agreed to in writing, software
782
- * distributed under the License is distributed on an "AS IS" BASIS,
783
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
784
- * See the License for the specific language governing permissions and
785
- * limitations under the License.
786
- */
787
- function generateAuthTokenRequest(_a, installationEntry) {
788
- var appConfig = _a.appConfig, heartbeatServiceProvider = _a.heartbeatServiceProvider;
789
- return __awaiter(this, void 0, void 0, function () {
790
- var endpoint, headers, heartbeatService, heartbeatsHeader, body, request, response, responseValue, completedAuthToken;
791
- return __generator(this, function (_b) {
792
- switch (_b.label) {
793
- case 0:
794
- endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);
795
- headers = getHeadersWithAuth(appConfig, installationEntry);
796
- heartbeatService = heartbeatServiceProvider.getImmediate({
797
- optional: true
798
- });
799
- if (!heartbeatService) return [3 /*break*/, 2];
800
- return [4 /*yield*/, heartbeatService.getHeartbeatsHeader()];
801
- case 1:
802
- heartbeatsHeader = _b.sent();
803
- if (heartbeatsHeader) {
804
- headers.append('x-firebase-client', heartbeatsHeader);
805
- }
806
- _b.label = 2;
807
- case 2:
808
- body = {
809
- installation: {
810
- sdkVersion: PACKAGE_VERSION,
811
- appId: appConfig.appId
812
- }
813
- };
814
- request = {
815
- method: 'POST',
816
- headers: headers,
817
- body: JSON.stringify(body)
818
- };
819
- return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })];
820
- case 3:
821
- response = _b.sent();
822
- if (!response.ok) return [3 /*break*/, 5];
823
- return [4 /*yield*/, response.json()];
824
- case 4:
825
- responseValue = _b.sent();
826
- completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);
827
- return [2 /*return*/, completedAuthToken];
828
- case 5: return [4 /*yield*/, getErrorFromResponse('Generate Auth Token', response)];
829
- case 6: throw _b.sent();
830
- }
831
- });
832
- });
833
- }
834
- function getGenerateAuthTokenEndpoint(appConfig, _a) {
835
- var fid = _a.fid;
836
- return "".concat(getInstallationsEndpoint(appConfig), "/").concat(fid, "/authTokens:generate");
837
- }
838
-
839
- /**
840
- * @license
841
- * Copyright 2019 Google LLC
842
- *
843
- * Licensed under the Apache License, Version 2.0 (the "License");
844
- * you may not use this file except in compliance with the License.
845
- * You may obtain a copy of the License at
846
- *
847
- * http://www.apache.org/licenses/LICENSE-2.0
848
- *
849
- * Unless required by applicable law or agreed to in writing, software
850
- * distributed under the License is distributed on an "AS IS" BASIS,
851
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
852
- * See the License for the specific language governing permissions and
853
- * limitations under the License.
854
- */
855
- /**
856
- * Returns a valid authentication token for the installation. Generates a new
857
- * token if one doesn't exist, is expired or about to expire.
858
- *
859
- * Should only be called if the Firebase Installation is registered.
860
- */
861
- function refreshAuthToken(installations, forceRefresh) {
862
- if (forceRefresh === void 0) { forceRefresh = false; }
863
- return __awaiter(this, void 0, void 0, function () {
864
- var tokenPromise, entry, authToken, _a;
865
- return __generator(this, function (_b) {
866
- switch (_b.label) {
867
- case 0: return [4 /*yield*/, update(installations.appConfig, function (oldEntry) {
868
- if (!isEntryRegistered(oldEntry)) {
869
- throw ERROR_FACTORY.create("not-registered" /* ErrorCode.NOT_REGISTERED */);
870
- }
871
- var oldAuthToken = oldEntry.authToken;
872
- if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {
873
- // There is a valid token in the DB.
874
- return oldEntry;
875
- }
876
- else if (oldAuthToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {
877
- // There already is a token request in progress.
878
- tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);
879
- return oldEntry;
880
- }
881
- else {
882
- // No token or token expired.
883
- if (!navigator.onLine) {
884
- throw ERROR_FACTORY.create("app-offline" /* ErrorCode.APP_OFFLINE */);
885
- }
886
- var inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);
887
- tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);
888
- return inProgressEntry;
889
- }
890
- })];
891
- case 1:
892
- entry = _b.sent();
893
- if (!tokenPromise) return [3 /*break*/, 3];
894
- return [4 /*yield*/, tokenPromise];
895
- case 2:
896
- _a = _b.sent();
897
- return [3 /*break*/, 4];
898
- case 3:
899
- _a = entry.authToken;
900
- _b.label = 4;
901
- case 4:
902
- authToken = _a;
903
- return [2 /*return*/, authToken];
904
- }
905
- });
906
- });
907
- }
908
- /**
909
- * Call only if FID is registered and Auth Token request is in progress.
910
- *
911
- * Waits until the current pending request finishes. If the request times out,
912
- * tries once in this thread as well.
913
- */
914
- function waitUntilAuthTokenRequest(installations, forceRefresh) {
915
- return __awaiter(this, void 0, void 0, function () {
916
- var entry, authToken;
917
- return __generator(this, function (_a) {
918
- switch (_a.label) {
919
- case 0: return [4 /*yield*/, updateAuthTokenRequest(installations.appConfig)];
920
- case 1:
921
- entry = _a.sent();
922
- _a.label = 2;
923
- case 2:
924
- if (!(entry.authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */)) return [3 /*break*/, 5];
925
- // generateAuthToken still in progress.
926
- return [4 /*yield*/, sleep(100)];
927
- case 3:
928
- // generateAuthToken still in progress.
929
- _a.sent();
930
- return [4 /*yield*/, updateAuthTokenRequest(installations.appConfig)];
931
- case 4:
932
- entry = _a.sent();
933
- return [3 /*break*/, 2];
934
- case 5:
935
- authToken = entry.authToken;
936
- if (authToken.requestStatus === 0 /* RequestStatus.NOT_STARTED */) {
937
- // The request timed out or failed in a different call. Try again.
938
- return [2 /*return*/, refreshAuthToken(installations, forceRefresh)];
939
- }
940
- else {
941
- return [2 /*return*/, authToken];
942
- }
943
- }
944
- });
945
- });
946
- }
947
- /**
948
- * Called only if there is a GenerateAuthToken request in progress.
949
- *
950
- * Updates the InstallationEntry in the DB based on the status of the
951
- * GenerateAuthToken request.
952
- *
953
- * Returns the updated InstallationEntry.
954
- */
955
- function updateAuthTokenRequest(appConfig) {
956
- return update(appConfig, function (oldEntry) {
957
- if (!isEntryRegistered(oldEntry)) {
958
- throw ERROR_FACTORY.create("not-registered" /* ErrorCode.NOT_REGISTERED */);
959
- }
960
- var oldAuthToken = oldEntry.authToken;
961
- if (hasAuthTokenRequestTimedOut(oldAuthToken)) {
962
- return __assign(__assign({}, oldEntry), { authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ } });
963
- }
964
- return oldEntry;
965
- });
966
- }
967
- function fetchAuthTokenFromServer(installations, installationEntry) {
968
- return __awaiter(this, void 0, void 0, function () {
969
- var authToken, updatedInstallationEntry, e_1, updatedInstallationEntry;
970
- return __generator(this, function (_a) {
971
- switch (_a.label) {
972
- case 0:
973
- _a.trys.push([0, 3, , 8]);
974
- return [4 /*yield*/, generateAuthTokenRequest(installations, installationEntry)];
975
- case 1:
976
- authToken = _a.sent();
977
- updatedInstallationEntry = __assign(__assign({}, installationEntry), { authToken: authToken });
978
- return [4 /*yield*/, set(installations.appConfig, updatedInstallationEntry)];
979
- case 2:
980
- _a.sent();
981
- return [2 /*return*/, authToken];
982
- case 3:
983
- e_1 = _a.sent();
984
- if (!(isServerError(e_1) &&
985
- (e_1.customData.serverCode === 401 || e_1.customData.serverCode === 404))) return [3 /*break*/, 5];
986
- // Server returned a "FID not found" or a "Invalid authentication" error.
987
- // Generate a new ID next time.
988
- return [4 /*yield*/, remove(installations.appConfig)];
989
- case 4:
990
- // Server returned a "FID not found" or a "Invalid authentication" error.
991
- // Generate a new ID next time.
992
- _a.sent();
993
- return [3 /*break*/, 7];
994
- case 5:
995
- updatedInstallationEntry = __assign(__assign({}, installationEntry), { authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ } });
996
- return [4 /*yield*/, set(installations.appConfig, updatedInstallationEntry)];
997
- case 6:
998
- _a.sent();
999
- _a.label = 7;
1000
- case 7: throw e_1;
1001
- case 8: return [2 /*return*/];
1002
- }
1003
- });
1004
- });
1005
- }
1006
- function isEntryRegistered(installationEntry) {
1007
- return (installationEntry !== undefined &&
1008
- installationEntry.registrationStatus === 2 /* RequestStatus.COMPLETED */);
1009
- }
1010
- function isAuthTokenValid(authToken) {
1011
- return (authToken.requestStatus === 2 /* RequestStatus.COMPLETED */ &&
1012
- !isAuthTokenExpired(authToken));
1013
- }
1014
- function isAuthTokenExpired(authToken) {
1015
- var now = Date.now();
1016
- return (now < authToken.creationTime ||
1017
- authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);
1018
- }
1019
- /** Returns an updated InstallationEntry with an InProgressAuthToken. */
1020
- function makeAuthTokenRequestInProgressEntry(oldEntry) {
1021
- var inProgressAuthToken = {
1022
- requestStatus: 1 /* RequestStatus.IN_PROGRESS */,
1023
- requestTime: Date.now()
1024
- };
1025
- return __assign(__assign({}, oldEntry), { authToken: inProgressAuthToken });
1026
- }
1027
- function hasAuthTokenRequestTimedOut(authToken) {
1028
- return (authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */ &&
1029
- authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());
1030
- }
1031
-
1032
- /**
1033
- * @license
1034
- * Copyright 2019 Google LLC
1035
- *
1036
- * Licensed under the Apache License, Version 2.0 (the "License");
1037
- * you may not use this file except in compliance with the License.
1038
- * You may obtain a copy of the License at
1039
- *
1040
- * http://www.apache.org/licenses/LICENSE-2.0
1041
- *
1042
- * Unless required by applicable law or agreed to in writing, software
1043
- * distributed under the License is distributed on an "AS IS" BASIS,
1044
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1045
- * See the License for the specific language governing permissions and
1046
- * limitations under the License.
1047
- */
1048
- /**
1049
- * Creates a Firebase Installation if there isn't one for the app and
1050
- * returns the Installation ID.
1051
- * @param installations - The `Installations` instance.
1052
- *
1053
- * @public
1054
- */
1055
- function getId(installations) {
1056
- return __awaiter(this, void 0, void 0, function () {
1057
- var installationsImpl, _a, installationEntry, registrationPromise;
1058
- return __generator(this, function (_b) {
1059
- switch (_b.label) {
1060
- case 0:
1061
- installationsImpl = installations;
1062
- return [4 /*yield*/, getInstallationEntry(installationsImpl)];
1063
- case 1:
1064
- _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise;
1065
- if (registrationPromise) {
1066
- registrationPromise.catch(console.error);
1067
- }
1068
- else {
1069
- // If the installation is already registered, update the authentication
1070
- // token if needed.
1071
- refreshAuthToken(installationsImpl).catch(console.error);
1072
- }
1073
- return [2 /*return*/, installationEntry.fid];
1074
- }
1075
- });
1076
- });
1077
- }
1078
-
1079
- /**
1080
- * @license
1081
- * Copyright 2019 Google LLC
1082
- *
1083
- * Licensed under the Apache License, Version 2.0 (the "License");
1084
- * you may not use this file except in compliance with the License.
1085
- * You may obtain a copy of the License at
1086
- *
1087
- * http://www.apache.org/licenses/LICENSE-2.0
1088
- *
1089
- * Unless required by applicable law or agreed to in writing, software
1090
- * distributed under the License is distributed on an "AS IS" BASIS,
1091
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1092
- * See the License for the specific language governing permissions and
1093
- * limitations under the License.
1094
- */
1095
- /**
1096
- * Returns a Firebase Installations auth token, identifying the current
1097
- * Firebase Installation.
1098
- * @param installations - The `Installations` instance.
1099
- * @param forceRefresh - Force refresh regardless of token expiration.
1100
- *
1101
- * @public
1102
- */
1103
- function getToken(installations, forceRefresh) {
1104
- if (forceRefresh === void 0) { forceRefresh = false; }
1105
- return __awaiter(this, void 0, void 0, function () {
1106
- var installationsImpl, authToken;
1107
- return __generator(this, function (_a) {
1108
- switch (_a.label) {
1109
- case 0:
1110
- installationsImpl = installations;
1111
- return [4 /*yield*/, completeInstallationRegistration(installationsImpl)];
1112
- case 1:
1113
- _a.sent();
1114
- return [4 /*yield*/, refreshAuthToken(installationsImpl, forceRefresh)];
1115
- case 2:
1116
- authToken = _a.sent();
1117
- return [2 /*return*/, authToken.token];
1118
- }
1119
- });
1120
- });
1121
- }
1122
- function completeInstallationRegistration(installations) {
1123
- return __awaiter(this, void 0, void 0, function () {
1124
- var registrationPromise;
1125
- return __generator(this, function (_a) {
1126
- switch (_a.label) {
1127
- case 0: return [4 /*yield*/, getInstallationEntry(installations)];
1128
- case 1:
1129
- registrationPromise = (_a.sent()).registrationPromise;
1130
- if (!registrationPromise) return [3 /*break*/, 3];
1131
- // A createInstallation request is in progress. Wait until it finishes.
1132
- return [4 /*yield*/, registrationPromise];
1133
- case 2:
1134
- // A createInstallation request is in progress. Wait until it finishes.
1135
- _a.sent();
1136
- _a.label = 3;
1137
- case 3: return [2 /*return*/];
1138
- }
1139
- });
1140
- });
1141
- }
1142
-
1143
- /**
1144
- * @license
1145
- * Copyright 2019 Google LLC
1146
- *
1147
- * Licensed under the Apache License, Version 2.0 (the "License");
1148
- * you may not use this file except in compliance with the License.
1149
- * You may obtain a copy of the License at
1150
- *
1151
- * http://www.apache.org/licenses/LICENSE-2.0
1152
- *
1153
- * Unless required by applicable law or agreed to in writing, software
1154
- * distributed under the License is distributed on an "AS IS" BASIS,
1155
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1156
- * See the License for the specific language governing permissions and
1157
- * limitations under the License.
1158
- */
1159
- function deleteInstallationRequest(appConfig, installationEntry) {
1160
- return __awaiter(this, void 0, void 0, function () {
1161
- var endpoint, headers, request, response;
1162
- return __generator(this, function (_a) {
1163
- switch (_a.label) {
1164
- case 0:
1165
- endpoint = getDeleteEndpoint(appConfig, installationEntry);
1166
- headers = getHeadersWithAuth(appConfig, installationEntry);
1167
- request = {
1168
- method: 'DELETE',
1169
- headers: headers
1170
- };
1171
- return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })];
1172
- case 1:
1173
- response = _a.sent();
1174
- if (!!response.ok) return [3 /*break*/, 3];
1175
- return [4 /*yield*/, getErrorFromResponse('Delete Installation', response)];
1176
- case 2: throw _a.sent();
1177
- case 3: return [2 /*return*/];
1178
- }
1179
- });
1180
- });
1181
- }
1182
- function getDeleteEndpoint(appConfig, _a) {
1183
- var fid = _a.fid;
1184
- return "".concat(getInstallationsEndpoint(appConfig), "/").concat(fid);
1185
- }
1186
-
1187
- /**
1188
- * @license
1189
- * Copyright 2019 Google LLC
1190
- *
1191
- * Licensed under the Apache License, Version 2.0 (the "License");
1192
- * you may not use this file except in compliance with the License.
1193
- * You may obtain a copy of the License at
1194
- *
1195
- * http://www.apache.org/licenses/LICENSE-2.0
1196
- *
1197
- * Unless required by applicable law or agreed to in writing, software
1198
- * distributed under the License is distributed on an "AS IS" BASIS,
1199
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1200
- * See the License for the specific language governing permissions and
1201
- * limitations under the License.
1202
- */
1203
- /**
1204
- * Deletes the Firebase Installation and all associated data.
1205
- * @param installations - The `Installations` instance.
1206
- *
1207
- * @public
1208
- */
1209
- function deleteInstallations(installations) {
1210
- return __awaiter(this, void 0, void 0, function () {
1211
- var appConfig, entry;
1212
- return __generator(this, function (_a) {
1213
- switch (_a.label) {
1214
- case 0:
1215
- appConfig = installations.appConfig;
1216
- return [4 /*yield*/, update(appConfig, function (oldEntry) {
1217
- if (oldEntry && oldEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {
1218
- // Delete the unregistered entry without sending a deleteInstallation request.
1219
- return undefined;
1220
- }
1221
- return oldEntry;
1222
- })];
1223
- case 1:
1224
- entry = _a.sent();
1225
- if (!entry) return [3 /*break*/, 6];
1226
- if (!(entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */)) return [3 /*break*/, 2];
1227
- // Can't delete while trying to register.
1228
- throw ERROR_FACTORY.create("delete-pending-registration" /* ErrorCode.DELETE_PENDING_REGISTRATION */);
1229
- case 2:
1230
- if (!(entry.registrationStatus === 2 /* RequestStatus.COMPLETED */)) return [3 /*break*/, 6];
1231
- if (!!navigator.onLine) return [3 /*break*/, 3];
1232
- throw ERROR_FACTORY.create("app-offline" /* ErrorCode.APP_OFFLINE */);
1233
- case 3: return [4 /*yield*/, deleteInstallationRequest(appConfig, entry)];
1234
- case 4:
1235
- _a.sent();
1236
- return [4 /*yield*/, remove(appConfig)];
1237
- case 5:
1238
- _a.sent();
1239
- _a.label = 6;
1240
- case 6: return [2 /*return*/];
1241
- }
1242
- });
1243
- });
1244
- }
1245
-
1246
- /**
1247
- * @license
1248
- * Copyright 2019 Google LLC
1249
- *
1250
- * Licensed under the Apache License, Version 2.0 (the "License");
1251
- * you may not use this file except in compliance with the License.
1252
- * You may obtain a copy of the License at
1253
- *
1254
- * http://www.apache.org/licenses/LICENSE-2.0
1255
- *
1256
- * Unless required by applicable law or agreed to in writing, software
1257
- * distributed under the License is distributed on an "AS IS" BASIS,
1258
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1259
- * See the License for the specific language governing permissions and
1260
- * limitations under the License.
1261
- */
1262
- /**
1263
- * Sets a new callback that will get called when Installation ID changes.
1264
- * Returns an unsubscribe function that will remove the callback when called.
1265
- * @param installations - The `Installations` instance.
1266
- * @param callback - The callback function that is invoked when FID changes.
1267
- * @returns A function that can be called to unsubscribe.
1268
- *
1269
- * @public
1270
- */
1271
- function onIdChange(installations, callback) {
1272
- var appConfig = installations.appConfig;
1273
- addCallback(appConfig, callback);
1274
- return function () {
1275
- removeCallback(appConfig, callback);
1276
- };
1277
- }
1278
-
1279
- /**
1280
- * @license
1281
- * Copyright 2020 Google LLC
1282
- *
1283
- * Licensed under the Apache License, Version 2.0 (the "License");
1284
- * you may not use this file except in compliance with the License.
1285
- * You may obtain a copy of the License at
1286
- *
1287
- * http://www.apache.org/licenses/LICENSE-2.0
1288
- *
1289
- * Unless required by applicable law or agreed to in writing, software
1290
- * distributed under the License is distributed on an "AS IS" BASIS,
1291
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1292
- * See the License for the specific language governing permissions and
1293
- * limitations under the License.
1294
- */
1295
- /**
1296
- * Returns an instance of {@link Installations} associated with the given
1297
- * {@link @firebase/app#FirebaseApp} instance.
1298
- * @param app - The {@link @firebase/app#FirebaseApp} instance.
1299
- *
1300
- * @public
1301
- */
1302
- function getInstallations(app) {
1303
- if (app === void 0) { app = getApp(); }
1304
- var installationsImpl = _getProvider(app, 'installations').getImmediate();
1305
- return installationsImpl;
1306
- }
1307
-
1308
- /**
1309
- * @license
1310
- * Copyright 2019 Google LLC
1311
- *
1312
- * Licensed under the Apache License, Version 2.0 (the "License");
1313
- * you may not use this file except in compliance with the License.
1314
- * You may obtain a copy of the License at
1315
- *
1316
- * http://www.apache.org/licenses/LICENSE-2.0
1317
- *
1318
- * Unless required by applicable law or agreed to in writing, software
1319
- * distributed under the License is distributed on an "AS IS" BASIS,
1320
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1321
- * See the License for the specific language governing permissions and
1322
- * limitations under the License.
1323
- */
1324
- function extractAppConfig(app) {
1325
- var e_1, _a;
1326
- if (!app || !app.options) {
1327
- throw getMissingValueError('App Configuration');
1328
- }
1329
- if (!app.name) {
1330
- throw getMissingValueError('App Name');
1331
- }
1332
- // Required app config keys
1333
- var configKeys = [
1334
- 'projectId',
1335
- 'apiKey',
1336
- 'appId'
1337
- ];
1338
- try {
1339
- for (var configKeys_1 = __values(configKeys), configKeys_1_1 = configKeys_1.next(); !configKeys_1_1.done; configKeys_1_1 = configKeys_1.next()) {
1340
- var keyName = configKeys_1_1.value;
1341
- if (!app.options[keyName]) {
1342
- throw getMissingValueError(keyName);
1343
- }
1344
- }
1345
- }
1346
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1347
- finally {
1348
- try {
1349
- if (configKeys_1_1 && !configKeys_1_1.done && (_a = configKeys_1.return)) _a.call(configKeys_1);
1350
- }
1351
- finally { if (e_1) throw e_1.error; }
1352
- }
1353
- return {
1354
- appName: app.name,
1355
- projectId: app.options.projectId,
1356
- apiKey: app.options.apiKey,
1357
- appId: app.options.appId
1358
- };
1359
- }
1360
- function getMissingValueError(valueName) {
1361
- return ERROR_FACTORY.create("missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {
1362
- valueName: valueName
1363
- });
1364
- }
1365
-
1366
- /**
1367
- * @license
1368
- * Copyright 2020 Google LLC
1369
- *
1370
- * Licensed under the Apache License, Version 2.0 (the "License");
1371
- * you may not use this file except in compliance with the License.
1372
- * You may obtain a copy of the License at
1373
- *
1374
- * http://www.apache.org/licenses/LICENSE-2.0
1375
- *
1376
- * Unless required by applicable law or agreed to in writing, software
1377
- * distributed under the License is distributed on an "AS IS" BASIS,
1378
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1379
- * See the License for the specific language governing permissions and
1380
- * limitations under the License.
1381
- */
1382
- var INSTALLATIONS_NAME = 'installations';
1383
- var INSTALLATIONS_NAME_INTERNAL = 'installations-internal';
1384
- var publicFactory = function (container) {
1385
- var app = container.getProvider('app').getImmediate();
1386
- // Throws if app isn't configured properly.
1387
- var appConfig = extractAppConfig(app);
1388
- var heartbeatServiceProvider = _getProvider(app, 'heartbeat');
1389
- var installationsImpl = {
1390
- app: app,
1391
- appConfig: appConfig,
1392
- heartbeatServiceProvider: heartbeatServiceProvider,
1393
- _delete: function () { return Promise.resolve(); }
1394
- };
1395
- return installationsImpl;
1396
- };
1397
- var internalFactory = function (container) {
1398
- var app = container.getProvider('app').getImmediate();
1399
- // Internal FIS instance relies on public FIS instance.
1400
- var installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();
1401
- var installationsInternal = {
1402
- getId: function () { return getId(installations); },
1403
- getToken: function (forceRefresh) { return getToken(installations, forceRefresh); }
1404
- };
1405
- return installationsInternal;
1406
- };
1407
- function registerInstallations() {
1408
- _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, "PUBLIC" /* ComponentType.PUBLIC */));
1409
- _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, "PRIVATE" /* ComponentType.PRIVATE */));
1410
- }
1411
-
1412
- /**
1413
- * The Firebase Installations Web SDK.
1414
- * This SDK does not work in a Node.js environment.
1415
- *
1416
- * @packageDocumentation
1417
- */
1418
- registerInstallations();
1419
- registerVersion(name, version);
1420
- // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
1421
- registerVersion(name, version, 'esm5');
1422
-
1423
- export { deleteInstallations, getId, getInstallations, getToken, onIdChange };
1424
- //# sourceMappingURL=index.esm.js.map