@firebase/installations 0.6.10 → 0.6.11

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