@firebase/remote-config 0.4.10 → 0.4.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 (57) hide show
  1. package/dist/esm/index.esm2017.js +1193 -1193
  2. package/dist/esm/index.esm2017.js.map +1 -1
  3. package/dist/esm/src/api.d.ts +115 -115
  4. package/dist/esm/src/api2.d.ts +40 -40
  5. package/dist/esm/src/client/caching_client.d.ts +45 -45
  6. package/dist/esm/src/client/remote_config_fetch_client.d.ts +123 -123
  7. package/dist/esm/src/client/rest_client.d.ts +40 -40
  8. package/dist/esm/src/client/retrying_client.d.ts +49 -49
  9. package/dist/esm/src/constants.d.ts +17 -17
  10. package/dist/esm/src/errors.d.ts +62 -62
  11. package/dist/esm/src/index.d.ts +14 -14
  12. package/dist/esm/src/language.d.ts +26 -26
  13. package/dist/esm/src/public_types.d.ts +128 -128
  14. package/dist/esm/src/register.d.ts +2 -2
  15. package/dist/esm/src/remote_config.d.ts +79 -79
  16. package/dist/esm/src/storage/storage.d.ts +76 -76
  17. package/dist/esm/src/storage/storage_cache.d.ts +48 -48
  18. package/dist/esm/src/value.d.ts +26 -26
  19. package/dist/esm/test/client/caching_client.test.d.ts +17 -17
  20. package/dist/esm/test/client/rest_client.test.d.ts +17 -17
  21. package/dist/esm/test/client/retrying_client.test.d.ts +17 -17
  22. package/dist/esm/test/errors.test.d.ts +17 -17
  23. package/dist/esm/test/language.test.d.ts +17 -17
  24. package/dist/esm/test/remote_config.test.d.ts +17 -17
  25. package/dist/esm/test/setup.d.ts +17 -17
  26. package/dist/esm/test/storage/storage.test.d.ts +17 -17
  27. package/dist/esm/test/storage/storage_cache.test.d.ts +17 -17
  28. package/dist/esm/test/value.test.d.ts +17 -17
  29. package/dist/index.cjs.js +1193 -1193
  30. package/dist/index.cjs.js.map +1 -1
  31. package/dist/src/api.d.ts +115 -115
  32. package/dist/src/api2.d.ts +40 -40
  33. package/dist/src/client/caching_client.d.ts +45 -45
  34. package/dist/src/client/remote_config_fetch_client.d.ts +123 -123
  35. package/dist/src/client/rest_client.d.ts +40 -40
  36. package/dist/src/client/retrying_client.d.ts +49 -49
  37. package/dist/src/constants.d.ts +17 -17
  38. package/dist/src/errors.d.ts +62 -62
  39. package/dist/src/index.d.ts +14 -14
  40. package/dist/src/language.d.ts +26 -26
  41. package/dist/src/public_types.d.ts +128 -128
  42. package/dist/src/register.d.ts +2 -2
  43. package/dist/src/remote_config.d.ts +79 -79
  44. package/dist/src/storage/storage.d.ts +76 -76
  45. package/dist/src/storage/storage_cache.d.ts +48 -48
  46. package/dist/src/value.d.ts +26 -26
  47. package/dist/test/client/caching_client.test.d.ts +17 -17
  48. package/dist/test/client/rest_client.test.d.ts +17 -17
  49. package/dist/test/client/retrying_client.test.d.ts +17 -17
  50. package/dist/test/errors.test.d.ts +17 -17
  51. package/dist/test/language.test.d.ts +17 -17
  52. package/dist/test/remote_config.test.d.ts +17 -17
  53. package/dist/test/setup.d.ts +17 -17
  54. package/dist/test/storage/storage.test.d.ts +17 -17
  55. package/dist/test/storage/storage_cache.test.d.ts +17 -17
  56. package/dist/test/value.test.d.ts +17 -17
  57. package/package.json +7 -7
package/dist/index.cjs.js CHANGED
@@ -9,1228 +9,1228 @@ var logger = require('@firebase/logger');
9
9
  require('@firebase/installations');
10
10
 
11
11
  const name = "@firebase/remote-config";
12
- const version = "0.4.10";
12
+ const version = "0.4.11";
13
13
 
14
- /**
15
- * @license
16
- * Copyright 2019 Google LLC
17
- *
18
- * Licensed under the Apache License, Version 2.0 (the "License");
19
- * you may not use this file except in compliance with the License.
20
- * You may obtain a copy of the License at
21
- *
22
- * http://www.apache.org/licenses/LICENSE-2.0
23
- *
24
- * Unless required by applicable law or agreed to in writing, software
25
- * distributed under the License is distributed on an "AS IS" BASIS,
26
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27
- * See the License for the specific language governing permissions and
28
- * limitations under the License.
29
- */
30
- /**
31
- * Shims a minimal AbortSignal.
32
- *
33
- * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects
34
- * of networking, such as retries. Firebase doesn't use AbortController enough to justify a
35
- * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be
36
- * swapped out if/when we do.
37
- */
38
- class RemoteConfigAbortSignal {
39
- constructor() {
40
- this.listeners = [];
41
- }
42
- addEventListener(listener) {
43
- this.listeners.push(listener);
44
- }
45
- abort() {
46
- this.listeners.forEach(listener => listener());
47
- }
14
+ /**
15
+ * @license
16
+ * Copyright 2019 Google LLC
17
+ *
18
+ * Licensed under the Apache License, Version 2.0 (the "License");
19
+ * you may not use this file except in compliance with the License.
20
+ * You may obtain a copy of the License at
21
+ *
22
+ * http://www.apache.org/licenses/LICENSE-2.0
23
+ *
24
+ * Unless required by applicable law or agreed to in writing, software
25
+ * distributed under the License is distributed on an "AS IS" BASIS,
26
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27
+ * See the License for the specific language governing permissions and
28
+ * limitations under the License.
29
+ */
30
+ /**
31
+ * Shims a minimal AbortSignal.
32
+ *
33
+ * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects
34
+ * of networking, such as retries. Firebase doesn't use AbortController enough to justify a
35
+ * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be
36
+ * swapped out if/when we do.
37
+ */
38
+ class RemoteConfigAbortSignal {
39
+ constructor() {
40
+ this.listeners = [];
41
+ }
42
+ addEventListener(listener) {
43
+ this.listeners.push(listener);
44
+ }
45
+ abort() {
46
+ this.listeners.forEach(listener => listener());
47
+ }
48
48
  }
49
49
 
50
- /**
51
- * @license
52
- * Copyright 2020 Google LLC
53
- *
54
- * Licensed under the Apache License, Version 2.0 (the "License");
55
- * you may not use this file except in compliance with the License.
56
- * You may obtain a copy of the License at
57
- *
58
- * http://www.apache.org/licenses/LICENSE-2.0
59
- *
60
- * Unless required by applicable law or agreed to in writing, software
61
- * distributed under the License is distributed on an "AS IS" BASIS,
62
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
63
- * See the License for the specific language governing permissions and
64
- * limitations under the License.
65
- */
50
+ /**
51
+ * @license
52
+ * Copyright 2020 Google LLC
53
+ *
54
+ * Licensed under the Apache License, Version 2.0 (the "License");
55
+ * you may not use this file except in compliance with the License.
56
+ * You may obtain a copy of the License at
57
+ *
58
+ * http://www.apache.org/licenses/LICENSE-2.0
59
+ *
60
+ * Unless required by applicable law or agreed to in writing, software
61
+ * distributed under the License is distributed on an "AS IS" BASIS,
62
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
63
+ * See the License for the specific language governing permissions and
64
+ * limitations under the License.
65
+ */
66
66
  const RC_COMPONENT_NAME = 'remote-config';
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
- const ERROR_DESCRIPTION_MAP = {
85
- ["registration-window" /* ErrorCode.REGISTRATION_WINDOW */]: 'Undefined window object. This SDK only supports usage in a browser environment.',
86
- ["registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */]: 'Undefined project identifier. Check Firebase app initialization.',
87
- ["registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */]: 'Undefined API key. Check Firebase app initialization.',
88
- ["registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */]: 'Undefined app identifier. Check Firebase app initialization.',
89
- ["storage-open" /* ErrorCode.STORAGE_OPEN */]: 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',
90
- ["storage-get" /* ErrorCode.STORAGE_GET */]: 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',
91
- ["storage-set" /* ErrorCode.STORAGE_SET */]: 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',
92
- ["storage-delete" /* ErrorCode.STORAGE_DELETE */]: 'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.',
93
- ["fetch-client-network" /* ErrorCode.FETCH_NETWORK */]: 'Fetch client failed to connect to a network. Check Internet connection.' +
94
- ' Original error: {$originalErrorMessage}.',
95
- ["fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */]: 'The config fetch request timed out. ' +
96
- ' Configure timeout using "fetchTimeoutMillis" SDK setting.',
97
- ["fetch-throttle" /* ErrorCode.FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' +
98
- ' Configure timeout using "fetchTimeoutMillis" SDK setting.' +
99
- ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
100
- ["fetch-client-parse" /* ErrorCode.FETCH_PARSE */]: 'Fetch client could not parse response.' +
101
- ' Original error: {$originalErrorMessage}.',
102
- ["fetch-status" /* ErrorCode.FETCH_STATUS */]: 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',
103
- ["indexed-db-unavailable" /* ErrorCode.INDEXED_DB_UNAVAILABLE */]: 'Indexed DB is not supported by current browser'
104
- };
105
- const ERROR_FACTORY = new util.ErrorFactory('remoteconfig' /* service */, 'Remote Config' /* service name */, ERROR_DESCRIPTION_MAP);
106
- // Note how this is like typeof/instanceof, but for ErrorCode.
107
- function hasErrorCode(e, errorCode) {
108
- return e instanceof util.FirebaseError && e.code.indexOf(errorCode) !== -1;
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
+ const ERROR_DESCRIPTION_MAP = {
85
+ ["registration-window" /* ErrorCode.REGISTRATION_WINDOW */]: 'Undefined window object. This SDK only supports usage in a browser environment.',
86
+ ["registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */]: 'Undefined project identifier. Check Firebase app initialization.',
87
+ ["registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */]: 'Undefined API key. Check Firebase app initialization.',
88
+ ["registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */]: 'Undefined app identifier. Check Firebase app initialization.',
89
+ ["storage-open" /* ErrorCode.STORAGE_OPEN */]: 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',
90
+ ["storage-get" /* ErrorCode.STORAGE_GET */]: 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',
91
+ ["storage-set" /* ErrorCode.STORAGE_SET */]: 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',
92
+ ["storage-delete" /* ErrorCode.STORAGE_DELETE */]: 'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.',
93
+ ["fetch-client-network" /* ErrorCode.FETCH_NETWORK */]: 'Fetch client failed to connect to a network. Check Internet connection.' +
94
+ ' Original error: {$originalErrorMessage}.',
95
+ ["fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */]: 'The config fetch request timed out. ' +
96
+ ' Configure timeout using "fetchTimeoutMillis" SDK setting.',
97
+ ["fetch-throttle" /* ErrorCode.FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' +
98
+ ' Configure timeout using "fetchTimeoutMillis" SDK setting.' +
99
+ ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
100
+ ["fetch-client-parse" /* ErrorCode.FETCH_PARSE */]: 'Fetch client could not parse response.' +
101
+ ' Original error: {$originalErrorMessage}.',
102
+ ["fetch-status" /* ErrorCode.FETCH_STATUS */]: 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',
103
+ ["indexed-db-unavailable" /* ErrorCode.INDEXED_DB_UNAVAILABLE */]: 'Indexed DB is not supported by current browser'
104
+ };
105
+ const ERROR_FACTORY = new util.ErrorFactory('remoteconfig' /* service */, 'Remote Config' /* service name */, ERROR_DESCRIPTION_MAP);
106
+ // Note how this is like typeof/instanceof, but for ErrorCode.
107
+ function hasErrorCode(e, errorCode) {
108
+ return e instanceof util.FirebaseError && e.code.indexOf(errorCode) !== -1;
109
109
  }
110
110
 
111
- /**
112
- * @license
113
- * Copyright 2019 Google LLC
114
- *
115
- * Licensed under the Apache License, Version 2.0 (the "License");
116
- * you may not use this file except in compliance with the License.
117
- * You may obtain a copy of the License at
118
- *
119
- * http://www.apache.org/licenses/LICENSE-2.0
120
- *
121
- * Unless required by applicable law or agreed to in writing, software
122
- * distributed under the License is distributed on an "AS IS" BASIS,
123
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
124
- * See the License for the specific language governing permissions and
125
- * limitations under the License.
126
- */
127
- const DEFAULT_VALUE_FOR_BOOLEAN = false;
128
- const DEFAULT_VALUE_FOR_STRING = '';
129
- const DEFAULT_VALUE_FOR_NUMBER = 0;
130
- const BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on'];
131
- class Value {
132
- constructor(_source, _value = DEFAULT_VALUE_FOR_STRING) {
133
- this._source = _source;
134
- this._value = _value;
135
- }
136
- asString() {
137
- return this._value;
138
- }
139
- asBoolean() {
140
- if (this._source === 'static') {
141
- return DEFAULT_VALUE_FOR_BOOLEAN;
142
- }
143
- return BOOLEAN_TRUTHY_VALUES.indexOf(this._value.toLowerCase()) >= 0;
144
- }
145
- asNumber() {
146
- if (this._source === 'static') {
147
- return DEFAULT_VALUE_FOR_NUMBER;
148
- }
149
- let num = Number(this._value);
150
- if (isNaN(num)) {
151
- num = DEFAULT_VALUE_FOR_NUMBER;
152
- }
153
- return num;
154
- }
155
- getSource() {
156
- return this._source;
157
- }
111
+ /**
112
+ * @license
113
+ * Copyright 2019 Google LLC
114
+ *
115
+ * Licensed under the Apache License, Version 2.0 (the "License");
116
+ * you may not use this file except in compliance with the License.
117
+ * You may obtain a copy of the License at
118
+ *
119
+ * http://www.apache.org/licenses/LICENSE-2.0
120
+ *
121
+ * Unless required by applicable law or agreed to in writing, software
122
+ * distributed under the License is distributed on an "AS IS" BASIS,
123
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
124
+ * See the License for the specific language governing permissions and
125
+ * limitations under the License.
126
+ */
127
+ const DEFAULT_VALUE_FOR_BOOLEAN = false;
128
+ const DEFAULT_VALUE_FOR_STRING = '';
129
+ const DEFAULT_VALUE_FOR_NUMBER = 0;
130
+ const BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on'];
131
+ class Value {
132
+ constructor(_source, _value = DEFAULT_VALUE_FOR_STRING) {
133
+ this._source = _source;
134
+ this._value = _value;
135
+ }
136
+ asString() {
137
+ return this._value;
138
+ }
139
+ asBoolean() {
140
+ if (this._source === 'static') {
141
+ return DEFAULT_VALUE_FOR_BOOLEAN;
142
+ }
143
+ return BOOLEAN_TRUTHY_VALUES.indexOf(this._value.toLowerCase()) >= 0;
144
+ }
145
+ asNumber() {
146
+ if (this._source === 'static') {
147
+ return DEFAULT_VALUE_FOR_NUMBER;
148
+ }
149
+ let num = Number(this._value);
150
+ if (isNaN(num)) {
151
+ num = DEFAULT_VALUE_FOR_NUMBER;
152
+ }
153
+ return num;
154
+ }
155
+ getSource() {
156
+ return this._source;
157
+ }
158
158
  }
159
159
 
160
- /**
161
- * @license
162
- * Copyright 2020 Google LLC
163
- *
164
- * Licensed under the Apache License, Version 2.0 (the "License");
165
- * you may not use this file except in compliance with the License.
166
- * You may obtain a copy of the License at
167
- *
168
- * http://www.apache.org/licenses/LICENSE-2.0
169
- *
170
- * Unless required by applicable law or agreed to in writing, software
171
- * distributed under the License is distributed on an "AS IS" BASIS,
172
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
173
- * See the License for the specific language governing permissions and
174
- * limitations under the License.
175
- */
176
- /**
177
- *
178
- * @param app - The {@link @firebase/app#FirebaseApp} instance.
179
- * @returns A {@link RemoteConfig} instance.
180
- *
181
- * @public
182
- */
183
- function getRemoteConfig(app$1 = app.getApp()) {
184
- app$1 = util.getModularInstance(app$1);
185
- const rcProvider = app._getProvider(app$1, RC_COMPONENT_NAME);
186
- return rcProvider.getImmediate();
187
- }
188
- /**
189
- * Makes the last fetched config available to the getters.
190
- * @param remoteConfig - The {@link RemoteConfig} instance.
191
- * @returns A `Promise` which resolves to true if the current call activated the fetched configs.
192
- * If the fetched configs were already activated, the `Promise` will resolve to false.
193
- *
194
- * @public
195
- */
196
- async function activate(remoteConfig) {
197
- const rc = util.getModularInstance(remoteConfig);
198
- const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([
199
- rc._storage.getLastSuccessfulFetchResponse(),
200
- rc._storage.getActiveConfigEtag()
201
- ]);
202
- if (!lastSuccessfulFetchResponse ||
203
- !lastSuccessfulFetchResponse.config ||
204
- !lastSuccessfulFetchResponse.eTag ||
205
- lastSuccessfulFetchResponse.eTag === activeConfigEtag) {
206
- // Either there is no successful fetched config, or is the same as current active
207
- // config.
208
- return false;
209
- }
210
- await Promise.all([
211
- rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),
212
- rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag)
213
- ]);
214
- return true;
215
- }
216
- /**
217
- * Ensures the last activated config are available to the getters.
218
- * @param remoteConfig - The {@link RemoteConfig} instance.
219
- *
220
- * @returns A `Promise` that resolves when the last activated config is available to the getters.
221
- * @public
222
- */
223
- function ensureInitialized(remoteConfig) {
224
- const rc = util.getModularInstance(remoteConfig);
225
- if (!rc._initializePromise) {
226
- rc._initializePromise = rc._storageCache.loadFromStorage().then(() => {
227
- rc._isInitializationComplete = true;
228
- });
229
- }
230
- return rc._initializePromise;
231
- }
232
- /**
233
- * Fetches and caches configuration from the Remote Config service.
234
- * @param remoteConfig - The {@link RemoteConfig} instance.
235
- * @public
236
- */
237
- async function fetchConfig(remoteConfig) {
238
- const rc = util.getModularInstance(remoteConfig);
239
- // Aborts the request after the given timeout, causing the fetch call to
240
- // reject with an `AbortError`.
241
- //
242
- // <p>Aborting after the request completes is a no-op, so we don't need a
243
- // corresponding `clearTimeout`.
244
- //
245
- // Locating abort logic here because:
246
- // * it uses a developer setting (timeout)
247
- // * it applies to all retries (like curl's max-time arg)
248
- // * it is consistent with the Fetch API's signal input
249
- const abortSignal = new RemoteConfigAbortSignal();
250
- setTimeout(async () => {
251
- // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.
252
- abortSignal.abort();
253
- }, rc.settings.fetchTimeoutMillis);
254
- // Catches *all* errors thrown by client so status can be set consistently.
255
- try {
256
- await rc._client.fetch({
257
- cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis,
258
- signal: abortSignal
259
- });
260
- await rc._storageCache.setLastFetchStatus('success');
261
- }
262
- catch (e) {
263
- const lastFetchStatus = hasErrorCode(e, "fetch-throttle" /* ErrorCode.FETCH_THROTTLE */)
264
- ? 'throttle'
265
- : 'failure';
266
- await rc._storageCache.setLastFetchStatus(lastFetchStatus);
267
- throw e;
268
- }
269
- }
270
- /**
271
- * Gets all config.
272
- *
273
- * @param remoteConfig - The {@link RemoteConfig} instance.
274
- * @returns All config.
275
- *
276
- * @public
277
- */
278
- function getAll(remoteConfig) {
279
- const rc = util.getModularInstance(remoteConfig);
280
- return getAllKeys(rc._storageCache.getActiveConfig(), rc.defaultConfig).reduce((allConfigs, key) => {
281
- allConfigs[key] = getValue(remoteConfig, key);
282
- return allConfigs;
283
- }, {});
284
- }
285
- /**
286
- * Gets the value for the given key as a boolean.
287
- *
288
- * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>.
289
- *
290
- * @param remoteConfig - The {@link RemoteConfig} instance.
291
- * @param key - The name of the parameter.
292
- *
293
- * @returns The value for the given key as a boolean.
294
- * @public
295
- */
296
- function getBoolean(remoteConfig, key) {
297
- return getValue(util.getModularInstance(remoteConfig), key).asBoolean();
298
- }
299
- /**
300
- * Gets the value for the given key as a number.
301
- *
302
- * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>.
303
- *
304
- * @param remoteConfig - The {@link RemoteConfig} instance.
305
- * @param key - The name of the parameter.
306
- *
307
- * @returns The value for the given key as a number.
308
- *
309
- * @public
310
- */
311
- function getNumber(remoteConfig, key) {
312
- return getValue(util.getModularInstance(remoteConfig), key).asNumber();
313
- }
314
- /**
315
- * Gets the value for the given key as a string.
316
- * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>.
317
- *
318
- * @param remoteConfig - The {@link RemoteConfig} instance.
319
- * @param key - The name of the parameter.
320
- *
321
- * @returns The value for the given key as a string.
322
- *
323
- * @public
324
- */
325
- function getString(remoteConfig, key) {
326
- return getValue(util.getModularInstance(remoteConfig), key).asString();
327
- }
328
- /**
329
- * Gets the {@link Value} for the given key.
330
- *
331
- * @param remoteConfig - The {@link RemoteConfig} instance.
332
- * @param key - The name of the parameter.
333
- *
334
- * @returns The value for the given key.
335
- *
336
- * @public
337
- */
338
- function getValue(remoteConfig, key) {
339
- const rc = util.getModularInstance(remoteConfig);
340
- if (!rc._isInitializationComplete) {
341
- rc._logger.debug(`A value was requested for key "${key}" before SDK initialization completed.` +
342
- ' Await on ensureInitialized if the intent was to get a previously activated value.');
343
- }
344
- const activeConfig = rc._storageCache.getActiveConfig();
345
- if (activeConfig && activeConfig[key] !== undefined) {
346
- return new Value('remote', activeConfig[key]);
347
- }
348
- else if (rc.defaultConfig && rc.defaultConfig[key] !== undefined) {
349
- return new Value('default', String(rc.defaultConfig[key]));
350
- }
351
- rc._logger.debug(`Returning static value for key "${key}".` +
352
- ' Define a default or remote value if this is unintentional.');
353
- return new Value('static');
354
- }
355
- /**
356
- * Defines the log level to use.
357
- *
358
- * @param remoteConfig - The {@link RemoteConfig} instance.
359
- * @param logLevel - The log level to set.
360
- *
361
- * @public
362
- */
363
- function setLogLevel(remoteConfig, logLevel) {
364
- const rc = util.getModularInstance(remoteConfig);
365
- switch (logLevel) {
366
- case 'debug':
367
- rc._logger.logLevel = logger.LogLevel.DEBUG;
368
- break;
369
- case 'silent':
370
- rc._logger.logLevel = logger.LogLevel.SILENT;
371
- break;
372
- default:
373
- rc._logger.logLevel = logger.LogLevel.ERROR;
374
- }
375
- }
376
- /**
377
- * Dedupes and returns an array of all the keys of the received objects.
378
- */
379
- function getAllKeys(obj1 = {}, obj2 = {}) {
380
- return Object.keys(Object.assign(Object.assign({}, obj1), obj2));
160
+ /**
161
+ * @license
162
+ * Copyright 2020 Google LLC
163
+ *
164
+ * Licensed under the Apache License, Version 2.0 (the "License");
165
+ * you may not use this file except in compliance with the License.
166
+ * You may obtain a copy of the License at
167
+ *
168
+ * http://www.apache.org/licenses/LICENSE-2.0
169
+ *
170
+ * Unless required by applicable law or agreed to in writing, software
171
+ * distributed under the License is distributed on an "AS IS" BASIS,
172
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
173
+ * See the License for the specific language governing permissions and
174
+ * limitations under the License.
175
+ */
176
+ /**
177
+ *
178
+ * @param app - The {@link @firebase/app#FirebaseApp} instance.
179
+ * @returns A {@link RemoteConfig} instance.
180
+ *
181
+ * @public
182
+ */
183
+ function getRemoteConfig(app$1 = app.getApp()) {
184
+ app$1 = util.getModularInstance(app$1);
185
+ const rcProvider = app._getProvider(app$1, RC_COMPONENT_NAME);
186
+ return rcProvider.getImmediate();
187
+ }
188
+ /**
189
+ * Makes the last fetched config available to the getters.
190
+ * @param remoteConfig - The {@link RemoteConfig} instance.
191
+ * @returns A `Promise` which resolves to true if the current call activated the fetched configs.
192
+ * If the fetched configs were already activated, the `Promise` will resolve to false.
193
+ *
194
+ * @public
195
+ */
196
+ async function activate(remoteConfig) {
197
+ const rc = util.getModularInstance(remoteConfig);
198
+ const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([
199
+ rc._storage.getLastSuccessfulFetchResponse(),
200
+ rc._storage.getActiveConfigEtag()
201
+ ]);
202
+ if (!lastSuccessfulFetchResponse ||
203
+ !lastSuccessfulFetchResponse.config ||
204
+ !lastSuccessfulFetchResponse.eTag ||
205
+ lastSuccessfulFetchResponse.eTag === activeConfigEtag) {
206
+ // Either there is no successful fetched config, or is the same as current active
207
+ // config.
208
+ return false;
209
+ }
210
+ await Promise.all([
211
+ rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),
212
+ rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag)
213
+ ]);
214
+ return true;
215
+ }
216
+ /**
217
+ * Ensures the last activated config are available to the getters.
218
+ * @param remoteConfig - The {@link RemoteConfig} instance.
219
+ *
220
+ * @returns A `Promise` that resolves when the last activated config is available to the getters.
221
+ * @public
222
+ */
223
+ function ensureInitialized(remoteConfig) {
224
+ const rc = util.getModularInstance(remoteConfig);
225
+ if (!rc._initializePromise) {
226
+ rc._initializePromise = rc._storageCache.loadFromStorage().then(() => {
227
+ rc._isInitializationComplete = true;
228
+ });
229
+ }
230
+ return rc._initializePromise;
231
+ }
232
+ /**
233
+ * Fetches and caches configuration from the Remote Config service.
234
+ * @param remoteConfig - The {@link RemoteConfig} instance.
235
+ * @public
236
+ */
237
+ async function fetchConfig(remoteConfig) {
238
+ const rc = util.getModularInstance(remoteConfig);
239
+ // Aborts the request after the given timeout, causing the fetch call to
240
+ // reject with an `AbortError`.
241
+ //
242
+ // <p>Aborting after the request completes is a no-op, so we don't need a
243
+ // corresponding `clearTimeout`.
244
+ //
245
+ // Locating abort logic here because:
246
+ // * it uses a developer setting (timeout)
247
+ // * it applies to all retries (like curl's max-time arg)
248
+ // * it is consistent with the Fetch API's signal input
249
+ const abortSignal = new RemoteConfigAbortSignal();
250
+ setTimeout(async () => {
251
+ // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.
252
+ abortSignal.abort();
253
+ }, rc.settings.fetchTimeoutMillis);
254
+ // Catches *all* errors thrown by client so status can be set consistently.
255
+ try {
256
+ await rc._client.fetch({
257
+ cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis,
258
+ signal: abortSignal
259
+ });
260
+ await rc._storageCache.setLastFetchStatus('success');
261
+ }
262
+ catch (e) {
263
+ const lastFetchStatus = hasErrorCode(e, "fetch-throttle" /* ErrorCode.FETCH_THROTTLE */)
264
+ ? 'throttle'
265
+ : 'failure';
266
+ await rc._storageCache.setLastFetchStatus(lastFetchStatus);
267
+ throw e;
268
+ }
269
+ }
270
+ /**
271
+ * Gets all config.
272
+ *
273
+ * @param remoteConfig - The {@link RemoteConfig} instance.
274
+ * @returns All config.
275
+ *
276
+ * @public
277
+ */
278
+ function getAll(remoteConfig) {
279
+ const rc = util.getModularInstance(remoteConfig);
280
+ return getAllKeys(rc._storageCache.getActiveConfig(), rc.defaultConfig).reduce((allConfigs, key) => {
281
+ allConfigs[key] = getValue(remoteConfig, key);
282
+ return allConfigs;
283
+ }, {});
284
+ }
285
+ /**
286
+ * Gets the value for the given key as a boolean.
287
+ *
288
+ * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>.
289
+ *
290
+ * @param remoteConfig - The {@link RemoteConfig} instance.
291
+ * @param key - The name of the parameter.
292
+ *
293
+ * @returns The value for the given key as a boolean.
294
+ * @public
295
+ */
296
+ function getBoolean(remoteConfig, key) {
297
+ return getValue(util.getModularInstance(remoteConfig), key).asBoolean();
298
+ }
299
+ /**
300
+ * Gets the value for the given key as a number.
301
+ *
302
+ * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>.
303
+ *
304
+ * @param remoteConfig - The {@link RemoteConfig} instance.
305
+ * @param key - The name of the parameter.
306
+ *
307
+ * @returns The value for the given key as a number.
308
+ *
309
+ * @public
310
+ */
311
+ function getNumber(remoteConfig, key) {
312
+ return getValue(util.getModularInstance(remoteConfig), key).asNumber();
313
+ }
314
+ /**
315
+ * Gets the value for the given key as a string.
316
+ * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>.
317
+ *
318
+ * @param remoteConfig - The {@link RemoteConfig} instance.
319
+ * @param key - The name of the parameter.
320
+ *
321
+ * @returns The value for the given key as a string.
322
+ *
323
+ * @public
324
+ */
325
+ function getString(remoteConfig, key) {
326
+ return getValue(util.getModularInstance(remoteConfig), key).asString();
327
+ }
328
+ /**
329
+ * Gets the {@link Value} for the given key.
330
+ *
331
+ * @param remoteConfig - The {@link RemoteConfig} instance.
332
+ * @param key - The name of the parameter.
333
+ *
334
+ * @returns The value for the given key.
335
+ *
336
+ * @public
337
+ */
338
+ function getValue(remoteConfig, key) {
339
+ const rc = util.getModularInstance(remoteConfig);
340
+ if (!rc._isInitializationComplete) {
341
+ rc._logger.debug(`A value was requested for key "${key}" before SDK initialization completed.` +
342
+ ' Await on ensureInitialized if the intent was to get a previously activated value.');
343
+ }
344
+ const activeConfig = rc._storageCache.getActiveConfig();
345
+ if (activeConfig && activeConfig[key] !== undefined) {
346
+ return new Value('remote', activeConfig[key]);
347
+ }
348
+ else if (rc.defaultConfig && rc.defaultConfig[key] !== undefined) {
349
+ return new Value('default', String(rc.defaultConfig[key]));
350
+ }
351
+ rc._logger.debug(`Returning static value for key "${key}".` +
352
+ ' Define a default or remote value if this is unintentional.');
353
+ return new Value('static');
354
+ }
355
+ /**
356
+ * Defines the log level to use.
357
+ *
358
+ * @param remoteConfig - The {@link RemoteConfig} instance.
359
+ * @param logLevel - The log level to set.
360
+ *
361
+ * @public
362
+ */
363
+ function setLogLevel(remoteConfig, logLevel) {
364
+ const rc = util.getModularInstance(remoteConfig);
365
+ switch (logLevel) {
366
+ case 'debug':
367
+ rc._logger.logLevel = logger.LogLevel.DEBUG;
368
+ break;
369
+ case 'silent':
370
+ rc._logger.logLevel = logger.LogLevel.SILENT;
371
+ break;
372
+ default:
373
+ rc._logger.logLevel = logger.LogLevel.ERROR;
374
+ }
375
+ }
376
+ /**
377
+ * Dedupes and returns an array of all the keys of the received objects.
378
+ */
379
+ function getAllKeys(obj1 = {}, obj2 = {}) {
380
+ return Object.keys(Object.assign(Object.assign({}, obj1), obj2));
381
381
  }
382
382
 
383
- /**
384
- * @license
385
- * Copyright 2019 Google LLC
386
- *
387
- * Licensed under the Apache License, Version 2.0 (the "License");
388
- * you may not use this file except in compliance with the License.
389
- * You may obtain a copy of the License at
390
- *
391
- * http://www.apache.org/licenses/LICENSE-2.0
392
- *
393
- * Unless required by applicable law or agreed to in writing, software
394
- * distributed under the License is distributed on an "AS IS" BASIS,
395
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
396
- * See the License for the specific language governing permissions and
397
- * limitations under the License.
398
- */
399
- /**
400
- * Implements the {@link RemoteConfigClient} abstraction with success response caching.
401
- *
402
- * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service
403
- * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the
404
- * Cache API doesn't support matching entries by time.
405
- */
406
- class CachingClient {
407
- constructor(client, storage, storageCache, logger) {
408
- this.client = client;
409
- this.storage = storage;
410
- this.storageCache = storageCache;
411
- this.logger = logger;
412
- }
413
- /**
414
- * Returns true if the age of the cached fetched configs is less than or equal to
415
- * {@link Settings#minimumFetchIntervalInSeconds}.
416
- *
417
- * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the
418
- * native Fetch API.
419
- *
420
- * <p>Visible for testing.
421
- */
422
- isCachedDataFresh(cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis) {
423
- // Cache can only be fresh if it's populated.
424
- if (!lastSuccessfulFetchTimestampMillis) {
425
- this.logger.debug('Config fetch cache check. Cache unpopulated.');
426
- return false;
427
- }
428
- // Calculates age of cache entry.
429
- const cacheAgeMillis = Date.now() - lastSuccessfulFetchTimestampMillis;
430
- const isCachedDataFresh = cacheAgeMillis <= cacheMaxAgeMillis;
431
- this.logger.debug('Config fetch cache check.' +
432
- ` Cache age millis: ${cacheAgeMillis}.` +
433
- ` Cache max age millis (minimumFetchIntervalMillis setting): ${cacheMaxAgeMillis}.` +
434
- ` Is cache hit: ${isCachedDataFresh}.`);
435
- return isCachedDataFresh;
436
- }
437
- async fetch(request) {
438
- // Reads from persisted storage to avoid cache miss if callers don't wait on initialization.
439
- const [lastSuccessfulFetchTimestampMillis, lastSuccessfulFetchResponse] = await Promise.all([
440
- this.storage.getLastSuccessfulFetchTimestampMillis(),
441
- this.storage.getLastSuccessfulFetchResponse()
442
- ]);
443
- // Exits early on cache hit.
444
- if (lastSuccessfulFetchResponse &&
445
- this.isCachedDataFresh(request.cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis)) {
446
- return lastSuccessfulFetchResponse;
447
- }
448
- // Deviates from pure decorator by not honoring a passed ETag since we don't have a public API
449
- // that allows the caller to pass an ETag.
450
- request.eTag =
451
- lastSuccessfulFetchResponse && lastSuccessfulFetchResponse.eTag;
452
- // Falls back to service on cache miss.
453
- const response = await this.client.fetch(request);
454
- // Fetch throws for non-success responses, so success is guaranteed here.
455
- const storageOperations = [
456
- // Uses write-through cache for consistency with synchronous public API.
457
- this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())
458
- ];
459
- if (response.status === 200) {
460
- // Caches response only if it has changed, ie non-304 responses.
461
- storageOperations.push(this.storage.setLastSuccessfulFetchResponse(response));
462
- }
463
- await Promise.all(storageOperations);
464
- return response;
465
- }
383
+ /**
384
+ * @license
385
+ * Copyright 2019 Google LLC
386
+ *
387
+ * Licensed under the Apache License, Version 2.0 (the "License");
388
+ * you may not use this file except in compliance with the License.
389
+ * You may obtain a copy of the License at
390
+ *
391
+ * http://www.apache.org/licenses/LICENSE-2.0
392
+ *
393
+ * Unless required by applicable law or agreed to in writing, software
394
+ * distributed under the License is distributed on an "AS IS" BASIS,
395
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
396
+ * See the License for the specific language governing permissions and
397
+ * limitations under the License.
398
+ */
399
+ /**
400
+ * Implements the {@link RemoteConfigClient} abstraction with success response caching.
401
+ *
402
+ * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service
403
+ * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the
404
+ * Cache API doesn't support matching entries by time.
405
+ */
406
+ class CachingClient {
407
+ constructor(client, storage, storageCache, logger) {
408
+ this.client = client;
409
+ this.storage = storage;
410
+ this.storageCache = storageCache;
411
+ this.logger = logger;
412
+ }
413
+ /**
414
+ * Returns true if the age of the cached fetched configs is less than or equal to
415
+ * {@link Settings#minimumFetchIntervalInSeconds}.
416
+ *
417
+ * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the
418
+ * native Fetch API.
419
+ *
420
+ * <p>Visible for testing.
421
+ */
422
+ isCachedDataFresh(cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis) {
423
+ // Cache can only be fresh if it's populated.
424
+ if (!lastSuccessfulFetchTimestampMillis) {
425
+ this.logger.debug('Config fetch cache check. Cache unpopulated.');
426
+ return false;
427
+ }
428
+ // Calculates age of cache entry.
429
+ const cacheAgeMillis = Date.now() - lastSuccessfulFetchTimestampMillis;
430
+ const isCachedDataFresh = cacheAgeMillis <= cacheMaxAgeMillis;
431
+ this.logger.debug('Config fetch cache check.' +
432
+ ` Cache age millis: ${cacheAgeMillis}.` +
433
+ ` Cache max age millis (minimumFetchIntervalMillis setting): ${cacheMaxAgeMillis}.` +
434
+ ` Is cache hit: ${isCachedDataFresh}.`);
435
+ return isCachedDataFresh;
436
+ }
437
+ async fetch(request) {
438
+ // Reads from persisted storage to avoid cache miss if callers don't wait on initialization.
439
+ const [lastSuccessfulFetchTimestampMillis, lastSuccessfulFetchResponse] = await Promise.all([
440
+ this.storage.getLastSuccessfulFetchTimestampMillis(),
441
+ this.storage.getLastSuccessfulFetchResponse()
442
+ ]);
443
+ // Exits early on cache hit.
444
+ if (lastSuccessfulFetchResponse &&
445
+ this.isCachedDataFresh(request.cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis)) {
446
+ return lastSuccessfulFetchResponse;
447
+ }
448
+ // Deviates from pure decorator by not honoring a passed ETag since we don't have a public API
449
+ // that allows the caller to pass an ETag.
450
+ request.eTag =
451
+ lastSuccessfulFetchResponse && lastSuccessfulFetchResponse.eTag;
452
+ // Falls back to service on cache miss.
453
+ const response = await this.client.fetch(request);
454
+ // Fetch throws for non-success responses, so success is guaranteed here.
455
+ const storageOperations = [
456
+ // Uses write-through cache for consistency with synchronous public API.
457
+ this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())
458
+ ];
459
+ if (response.status === 200) {
460
+ // Caches response only if it has changed, ie non-304 responses.
461
+ storageOperations.push(this.storage.setLastSuccessfulFetchResponse(response));
462
+ }
463
+ await Promise.all(storageOperations);
464
+ return response;
465
+ }
466
466
  }
467
467
 
468
- /**
469
- * @license
470
- * Copyright 2019 Google LLC
471
- *
472
- * Licensed under the Apache License, Version 2.0 (the "License");
473
- * you may not use this file except in compliance with the License.
474
- * You may obtain a copy of the License at
475
- *
476
- * http://www.apache.org/licenses/LICENSE-2.0
477
- *
478
- * Unless required by applicable law or agreed to in writing, software
479
- * distributed under the License is distributed on an "AS IS" BASIS,
480
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
481
- * See the License for the specific language governing permissions and
482
- * limitations under the License.
483
- */
484
- /**
485
- * Attempts to get the most accurate browser language setting.
486
- *
487
- * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript.
488
- *
489
- * <p>Defers default language specification to server logic for consistency.
490
- *
491
- * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}.
492
- */
493
- function getUserLanguage(navigatorLanguage = navigator) {
494
- return (
495
- // Most reliable, but only supported in Chrome/Firefox.
496
- (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
497
- // Supported in most browsers, but returns the language of the browser
498
- // UI, not the language set in browser settings.
499
- navigatorLanguage.language
500
- // Polyfill otherwise.
501
- );
468
+ /**
469
+ * @license
470
+ * Copyright 2019 Google LLC
471
+ *
472
+ * Licensed under the Apache License, Version 2.0 (the "License");
473
+ * you may not use this file except in compliance with the License.
474
+ * You may obtain a copy of the License at
475
+ *
476
+ * http://www.apache.org/licenses/LICENSE-2.0
477
+ *
478
+ * Unless required by applicable law or agreed to in writing, software
479
+ * distributed under the License is distributed on an "AS IS" BASIS,
480
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
481
+ * See the License for the specific language governing permissions and
482
+ * limitations under the License.
483
+ */
484
+ /**
485
+ * Attempts to get the most accurate browser language setting.
486
+ *
487
+ * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript.
488
+ *
489
+ * <p>Defers default language specification to server logic for consistency.
490
+ *
491
+ * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}.
492
+ */
493
+ function getUserLanguage(navigatorLanguage = navigator) {
494
+ return (
495
+ // Most reliable, but only supported in Chrome/Firefox.
496
+ (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
497
+ // Supported in most browsers, but returns the language of the browser
498
+ // UI, not the language set in browser settings.
499
+ navigatorLanguage.language
500
+ // Polyfill otherwise.
501
+ );
502
502
  }
503
503
 
504
- /**
505
- * @license
506
- * Copyright 2019 Google LLC
507
- *
508
- * Licensed under the Apache License, Version 2.0 (the "License");
509
- * you may not use this file except in compliance with the License.
510
- * You may obtain a copy of the License at
511
- *
512
- * http://www.apache.org/licenses/LICENSE-2.0
513
- *
514
- * Unless required by applicable law or agreed to in writing, software
515
- * distributed under the License is distributed on an "AS IS" BASIS,
516
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
517
- * See the License for the specific language governing permissions and
518
- * limitations under the License.
519
- */
520
- /**
521
- * Implements the Client abstraction for the Remote Config REST API.
522
- */
523
- class RestClient {
524
- constructor(firebaseInstallations, sdkVersion, namespace, projectId, apiKey, appId) {
525
- this.firebaseInstallations = firebaseInstallations;
526
- this.sdkVersion = sdkVersion;
527
- this.namespace = namespace;
528
- this.projectId = projectId;
529
- this.apiKey = apiKey;
530
- this.appId = appId;
531
- }
532
- /**
533
- * Fetches from the Remote Config REST API.
534
- *
535
- * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't
536
- * connect to the network.
537
- * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the
538
- * fetch response.
539
- * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status.
540
- */
541
- async fetch(request) {
542
- const [installationId, installationToken] = await Promise.all([
543
- this.firebaseInstallations.getId(),
544
- this.firebaseInstallations.getToken()
545
- ]);
546
- const urlBase = window.FIREBASE_REMOTE_CONFIG_URL_BASE ||
547
- 'https://firebaseremoteconfig.googleapis.com';
548
- const url = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`;
549
- const headers = {
550
- 'Content-Type': 'application/json',
551
- 'Content-Encoding': 'gzip',
552
- // Deviates from pure decorator by not passing max-age header since we don't currently have
553
- // service behavior using that header.
554
- 'If-None-Match': request.eTag || '*'
555
- };
556
- const requestBody = {
557
- /* eslint-disable camelcase */
558
- sdk_version: this.sdkVersion,
559
- app_instance_id: installationId,
560
- app_instance_id_token: installationToken,
561
- app_id: this.appId,
562
- language_code: getUserLanguage()
563
- /* eslint-enable camelcase */
564
- };
565
- const options = {
566
- method: 'POST',
567
- headers,
568
- body: JSON.stringify(requestBody)
569
- };
570
- // This logic isn't REST-specific, but shimming abort logic isn't worth another decorator.
571
- const fetchPromise = fetch(url, options);
572
- const timeoutPromise = new Promise((_resolve, reject) => {
573
- // Maps async event listener to Promise API.
574
- request.signal.addEventListener(() => {
575
- // Emulates https://heycam.github.io/webidl/#aborterror
576
- const error = new Error('The operation was aborted.');
577
- error.name = 'AbortError';
578
- reject(error);
579
- });
580
- });
581
- let response;
582
- try {
583
- await Promise.race([fetchPromise, timeoutPromise]);
584
- response = await fetchPromise;
585
- }
586
- catch (originalError) {
587
- let errorCode = "fetch-client-network" /* ErrorCode.FETCH_NETWORK */;
588
- if ((originalError === null || originalError === void 0 ? void 0 : originalError.name) === 'AbortError') {
589
- errorCode = "fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */;
590
- }
591
- throw ERROR_FACTORY.create(errorCode, {
592
- originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
593
- });
594
- }
595
- let status = response.status;
596
- // Normalizes nullable header to optional.
597
- const responseEtag = response.headers.get('ETag') || undefined;
598
- let config;
599
- let state;
600
- // JSON parsing throws SyntaxError if the response body isn't a JSON string.
601
- // Requesting application/json and checking for a 200 ensures there's JSON data.
602
- if (response.status === 200) {
603
- let responseBody;
604
- try {
605
- responseBody = await response.json();
606
- }
607
- catch (originalError) {
608
- throw ERROR_FACTORY.create("fetch-client-parse" /* ErrorCode.FETCH_PARSE */, {
609
- originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
610
- });
611
- }
612
- config = responseBody['entries'];
613
- state = responseBody['state'];
614
- }
615
- // Normalizes based on legacy state.
616
- if (state === 'INSTANCE_STATE_UNSPECIFIED') {
617
- status = 500;
618
- }
619
- else if (state === 'NO_CHANGE') {
620
- status = 304;
621
- }
622
- else if (state === 'NO_TEMPLATE' || state === 'EMPTY_CONFIG') {
623
- // These cases can be fixed remotely, so normalize to safe value.
624
- config = {};
625
- }
626
- // Normalize to exception-based control flow for non-success cases.
627
- // Encapsulates HTTP specifics in this class as much as possible. Status is still the best for
628
- // differentiating success states (200 from 304; the state body param is undefined in a
629
- // standard 304).
630
- if (status !== 304 && status !== 200) {
631
- throw ERROR_FACTORY.create("fetch-status" /* ErrorCode.FETCH_STATUS */, {
632
- httpStatus: status
633
- });
634
- }
635
- return { status, eTag: responseEtag, config };
636
- }
504
+ /**
505
+ * @license
506
+ * Copyright 2019 Google LLC
507
+ *
508
+ * Licensed under the Apache License, Version 2.0 (the "License");
509
+ * you may not use this file except in compliance with the License.
510
+ * You may obtain a copy of the License at
511
+ *
512
+ * http://www.apache.org/licenses/LICENSE-2.0
513
+ *
514
+ * Unless required by applicable law or agreed to in writing, software
515
+ * distributed under the License is distributed on an "AS IS" BASIS,
516
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
517
+ * See the License for the specific language governing permissions and
518
+ * limitations under the License.
519
+ */
520
+ /**
521
+ * Implements the Client abstraction for the Remote Config REST API.
522
+ */
523
+ class RestClient {
524
+ constructor(firebaseInstallations, sdkVersion, namespace, projectId, apiKey, appId) {
525
+ this.firebaseInstallations = firebaseInstallations;
526
+ this.sdkVersion = sdkVersion;
527
+ this.namespace = namespace;
528
+ this.projectId = projectId;
529
+ this.apiKey = apiKey;
530
+ this.appId = appId;
531
+ }
532
+ /**
533
+ * Fetches from the Remote Config REST API.
534
+ *
535
+ * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't
536
+ * connect to the network.
537
+ * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the
538
+ * fetch response.
539
+ * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status.
540
+ */
541
+ async fetch(request) {
542
+ const [installationId, installationToken] = await Promise.all([
543
+ this.firebaseInstallations.getId(),
544
+ this.firebaseInstallations.getToken()
545
+ ]);
546
+ const urlBase = window.FIREBASE_REMOTE_CONFIG_URL_BASE ||
547
+ 'https://firebaseremoteconfig.googleapis.com';
548
+ const url = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`;
549
+ const headers = {
550
+ 'Content-Type': 'application/json',
551
+ 'Content-Encoding': 'gzip',
552
+ // Deviates from pure decorator by not passing max-age header since we don't currently have
553
+ // service behavior using that header.
554
+ 'If-None-Match': request.eTag || '*'
555
+ };
556
+ const requestBody = {
557
+ /* eslint-disable camelcase */
558
+ sdk_version: this.sdkVersion,
559
+ app_instance_id: installationId,
560
+ app_instance_id_token: installationToken,
561
+ app_id: this.appId,
562
+ language_code: getUserLanguage()
563
+ /* eslint-enable camelcase */
564
+ };
565
+ const options = {
566
+ method: 'POST',
567
+ headers,
568
+ body: JSON.stringify(requestBody)
569
+ };
570
+ // This logic isn't REST-specific, but shimming abort logic isn't worth another decorator.
571
+ const fetchPromise = fetch(url, options);
572
+ const timeoutPromise = new Promise((_resolve, reject) => {
573
+ // Maps async event listener to Promise API.
574
+ request.signal.addEventListener(() => {
575
+ // Emulates https://heycam.github.io/webidl/#aborterror
576
+ const error = new Error('The operation was aborted.');
577
+ error.name = 'AbortError';
578
+ reject(error);
579
+ });
580
+ });
581
+ let response;
582
+ try {
583
+ await Promise.race([fetchPromise, timeoutPromise]);
584
+ response = await fetchPromise;
585
+ }
586
+ catch (originalError) {
587
+ let errorCode = "fetch-client-network" /* ErrorCode.FETCH_NETWORK */;
588
+ if ((originalError === null || originalError === void 0 ? void 0 : originalError.name) === 'AbortError') {
589
+ errorCode = "fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */;
590
+ }
591
+ throw ERROR_FACTORY.create(errorCode, {
592
+ originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
593
+ });
594
+ }
595
+ let status = response.status;
596
+ // Normalizes nullable header to optional.
597
+ const responseEtag = response.headers.get('ETag') || undefined;
598
+ let config;
599
+ let state;
600
+ // JSON parsing throws SyntaxError if the response body isn't a JSON string.
601
+ // Requesting application/json and checking for a 200 ensures there's JSON data.
602
+ if (response.status === 200) {
603
+ let responseBody;
604
+ try {
605
+ responseBody = await response.json();
606
+ }
607
+ catch (originalError) {
608
+ throw ERROR_FACTORY.create("fetch-client-parse" /* ErrorCode.FETCH_PARSE */, {
609
+ originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
610
+ });
611
+ }
612
+ config = responseBody['entries'];
613
+ state = responseBody['state'];
614
+ }
615
+ // Normalizes based on legacy state.
616
+ if (state === 'INSTANCE_STATE_UNSPECIFIED') {
617
+ status = 500;
618
+ }
619
+ else if (state === 'NO_CHANGE') {
620
+ status = 304;
621
+ }
622
+ else if (state === 'NO_TEMPLATE' || state === 'EMPTY_CONFIG') {
623
+ // These cases can be fixed remotely, so normalize to safe value.
624
+ config = {};
625
+ }
626
+ // Normalize to exception-based control flow for non-success cases.
627
+ // Encapsulates HTTP specifics in this class as much as possible. Status is still the best for
628
+ // differentiating success states (200 from 304; the state body param is undefined in a
629
+ // standard 304).
630
+ if (status !== 304 && status !== 200) {
631
+ throw ERROR_FACTORY.create("fetch-status" /* ErrorCode.FETCH_STATUS */, {
632
+ httpStatus: status
633
+ });
634
+ }
635
+ return { status, eTag: responseEtag, config };
636
+ }
637
637
  }
638
638
 
639
- /**
640
- * @license
641
- * Copyright 2019 Google LLC
642
- *
643
- * Licensed under the Apache License, Version 2.0 (the "License");
644
- * you may not use this file except in compliance with the License.
645
- * You may obtain a copy of the License at
646
- *
647
- * http://www.apache.org/licenses/LICENSE-2.0
648
- *
649
- * Unless required by applicable law or agreed to in writing, software
650
- * distributed under the License is distributed on an "AS IS" BASIS,
651
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
652
- * See the License for the specific language governing permissions and
653
- * limitations under the License.
654
- */
655
- /**
656
- * Supports waiting on a backoff by:
657
- *
658
- * <ul>
659
- * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>
660
- * <li>Listening on a signal bus for abort events, just like the Fetch API</li>
661
- * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled
662
- * request appear the same.</li>
663
- * </ul>
664
- *
665
- * <p>Visible for testing.
666
- */
667
- function setAbortableTimeout(signal, throttleEndTimeMillis) {
668
- return new Promise((resolve, reject) => {
669
- // Derives backoff from given end time, normalizing negative numbers to zero.
670
- const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);
671
- const timeout = setTimeout(resolve, backoffMillis);
672
- // Adds listener, rather than sets onabort, because signal is a shared object.
673
- signal.addEventListener(() => {
674
- clearTimeout(timeout);
675
- // If the request completes before this timeout, the rejection has no effect.
676
- reject(ERROR_FACTORY.create("fetch-throttle" /* ErrorCode.FETCH_THROTTLE */, {
677
- throttleEndTimeMillis
678
- }));
679
- });
680
- });
681
- }
682
- /**
683
- * Returns true if the {@link Error} indicates a fetch request may succeed later.
684
- */
685
- function isRetriableError(e) {
686
- if (!(e instanceof util.FirebaseError) || !e.customData) {
687
- return false;
688
- }
689
- // Uses string index defined by ErrorData, which FirebaseError implements.
690
- const httpStatus = Number(e.customData['httpStatus']);
691
- return (httpStatus === 429 ||
692
- httpStatus === 500 ||
693
- httpStatus === 503 ||
694
- httpStatus === 504);
695
- }
696
- /**
697
- * Decorates a Client with retry logic.
698
- *
699
- * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache
700
- * responses (because the SDK has no use for error responses).
701
- */
702
- class RetryingClient {
703
- constructor(client, storage) {
704
- this.client = client;
705
- this.storage = storage;
706
- }
707
- async fetch(request) {
708
- const throttleMetadata = (await this.storage.getThrottleMetadata()) || {
709
- backoffCount: 0,
710
- throttleEndTimeMillis: Date.now()
711
- };
712
- return this.attemptFetch(request, throttleMetadata);
713
- }
714
- /**
715
- * A recursive helper for attempting a fetch request repeatedly.
716
- *
717
- * @throws any non-retriable errors.
718
- */
719
- async attemptFetch(request, { throttleEndTimeMillis, backoffCount }) {
720
- // Starts with a (potentially zero) timeout to support resumption from stored state.
721
- // Ensures the throttle end time is honored if the last attempt timed out.
722
- // Note the SDK will never make a request if the fetch timeout expires at this point.
723
- await setAbortableTimeout(request.signal, throttleEndTimeMillis);
724
- try {
725
- const response = await this.client.fetch(request);
726
- // Note the SDK only clears throttle state if response is success or non-retriable.
727
- await this.storage.deleteThrottleMetadata();
728
- return response;
729
- }
730
- catch (e) {
731
- if (!isRetriableError(e)) {
732
- throw e;
733
- }
734
- // Increments backoff state.
735
- const throttleMetadata = {
736
- throttleEndTimeMillis: Date.now() + util.calculateBackoffMillis(backoffCount),
737
- backoffCount: backoffCount + 1
738
- };
739
- // Persists state.
740
- await this.storage.setThrottleMetadata(throttleMetadata);
741
- return this.attemptFetch(request, throttleMetadata);
742
- }
743
- }
639
+ /**
640
+ * @license
641
+ * Copyright 2019 Google LLC
642
+ *
643
+ * Licensed under the Apache License, Version 2.0 (the "License");
644
+ * you may not use this file except in compliance with the License.
645
+ * You may obtain a copy of the License at
646
+ *
647
+ * http://www.apache.org/licenses/LICENSE-2.0
648
+ *
649
+ * Unless required by applicable law or agreed to in writing, software
650
+ * distributed under the License is distributed on an "AS IS" BASIS,
651
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
652
+ * See the License for the specific language governing permissions and
653
+ * limitations under the License.
654
+ */
655
+ /**
656
+ * Supports waiting on a backoff by:
657
+ *
658
+ * <ul>
659
+ * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>
660
+ * <li>Listening on a signal bus for abort events, just like the Fetch API</li>
661
+ * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled
662
+ * request appear the same.</li>
663
+ * </ul>
664
+ *
665
+ * <p>Visible for testing.
666
+ */
667
+ function setAbortableTimeout(signal, throttleEndTimeMillis) {
668
+ return new Promise((resolve, reject) => {
669
+ // Derives backoff from given end time, normalizing negative numbers to zero.
670
+ const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);
671
+ const timeout = setTimeout(resolve, backoffMillis);
672
+ // Adds listener, rather than sets onabort, because signal is a shared object.
673
+ signal.addEventListener(() => {
674
+ clearTimeout(timeout);
675
+ // If the request completes before this timeout, the rejection has no effect.
676
+ reject(ERROR_FACTORY.create("fetch-throttle" /* ErrorCode.FETCH_THROTTLE */, {
677
+ throttleEndTimeMillis
678
+ }));
679
+ });
680
+ });
681
+ }
682
+ /**
683
+ * Returns true if the {@link Error} indicates a fetch request may succeed later.
684
+ */
685
+ function isRetriableError(e) {
686
+ if (!(e instanceof util.FirebaseError) || !e.customData) {
687
+ return false;
688
+ }
689
+ // Uses string index defined by ErrorData, which FirebaseError implements.
690
+ const httpStatus = Number(e.customData['httpStatus']);
691
+ return (httpStatus === 429 ||
692
+ httpStatus === 500 ||
693
+ httpStatus === 503 ||
694
+ httpStatus === 504);
695
+ }
696
+ /**
697
+ * Decorates a Client with retry logic.
698
+ *
699
+ * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache
700
+ * responses (because the SDK has no use for error responses).
701
+ */
702
+ class RetryingClient {
703
+ constructor(client, storage) {
704
+ this.client = client;
705
+ this.storage = storage;
706
+ }
707
+ async fetch(request) {
708
+ const throttleMetadata = (await this.storage.getThrottleMetadata()) || {
709
+ backoffCount: 0,
710
+ throttleEndTimeMillis: Date.now()
711
+ };
712
+ return this.attemptFetch(request, throttleMetadata);
713
+ }
714
+ /**
715
+ * A recursive helper for attempting a fetch request repeatedly.
716
+ *
717
+ * @throws any non-retriable errors.
718
+ */
719
+ async attemptFetch(request, { throttleEndTimeMillis, backoffCount }) {
720
+ // Starts with a (potentially zero) timeout to support resumption from stored state.
721
+ // Ensures the throttle end time is honored if the last attempt timed out.
722
+ // Note the SDK will never make a request if the fetch timeout expires at this point.
723
+ await setAbortableTimeout(request.signal, throttleEndTimeMillis);
724
+ try {
725
+ const response = await this.client.fetch(request);
726
+ // Note the SDK only clears throttle state if response is success or non-retriable.
727
+ await this.storage.deleteThrottleMetadata();
728
+ return response;
729
+ }
730
+ catch (e) {
731
+ if (!isRetriableError(e)) {
732
+ throw e;
733
+ }
734
+ // Increments backoff state.
735
+ const throttleMetadata = {
736
+ throttleEndTimeMillis: Date.now() + util.calculateBackoffMillis(backoffCount),
737
+ backoffCount: backoffCount + 1
738
+ };
739
+ // Persists state.
740
+ await this.storage.setThrottleMetadata(throttleMetadata);
741
+ return this.attemptFetch(request, throttleMetadata);
742
+ }
743
+ }
744
744
  }
745
745
 
746
- /**
747
- * @license
748
- * Copyright 2019 Google LLC
749
- *
750
- * Licensed under the Apache License, Version 2.0 (the "License");
751
- * you may not use this file except in compliance with the License.
752
- * You may obtain a copy of the License at
753
- *
754
- * http://www.apache.org/licenses/LICENSE-2.0
755
- *
756
- * Unless required by applicable law or agreed to in writing, software
757
- * distributed under the License is distributed on an "AS IS" BASIS,
758
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
759
- * See the License for the specific language governing permissions and
760
- * limitations under the License.
761
- */
762
- const DEFAULT_FETCH_TIMEOUT_MILLIS = 60 * 1000; // One minute
763
- const DEFAULT_CACHE_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000; // Twelve hours.
764
- /**
765
- * Encapsulates business logic mapping network and storage dependencies to the public SDK API.
766
- *
767
- * See {@link https://github.com/firebase/firebase-js-sdk/blob/main/packages/firebase/index.d.ts|interface documentation} for method descriptions.
768
- */
769
- class RemoteConfig {
770
- constructor(
771
- // Required by FirebaseServiceFactory interface.
772
- app,
773
- // JS doesn't support private yet
774
- // (https://github.com/tc39/proposal-class-fields#private-fields), so we hint using an
775
- // underscore prefix.
776
- /**
777
- * @internal
778
- */
779
- _client,
780
- /**
781
- * @internal
782
- */
783
- _storageCache,
784
- /**
785
- * @internal
786
- */
787
- _storage,
788
- /**
789
- * @internal
790
- */
791
- _logger) {
792
- this.app = app;
793
- this._client = _client;
794
- this._storageCache = _storageCache;
795
- this._storage = _storage;
796
- this._logger = _logger;
797
- /**
798
- * Tracks completion of initialization promise.
799
- * @internal
800
- */
801
- this._isInitializationComplete = false;
802
- this.settings = {
803
- fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS,
804
- minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS
805
- };
806
- this.defaultConfig = {};
807
- }
808
- get fetchTimeMillis() {
809
- return this._storageCache.getLastSuccessfulFetchTimestampMillis() || -1;
810
- }
811
- get lastFetchStatus() {
812
- return this._storageCache.getLastFetchStatus() || 'no-fetch-yet';
813
- }
746
+ /**
747
+ * @license
748
+ * Copyright 2019 Google LLC
749
+ *
750
+ * Licensed under the Apache License, Version 2.0 (the "License");
751
+ * you may not use this file except in compliance with the License.
752
+ * You may obtain a copy of the License at
753
+ *
754
+ * http://www.apache.org/licenses/LICENSE-2.0
755
+ *
756
+ * Unless required by applicable law or agreed to in writing, software
757
+ * distributed under the License is distributed on an "AS IS" BASIS,
758
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
759
+ * See the License for the specific language governing permissions and
760
+ * limitations under the License.
761
+ */
762
+ const DEFAULT_FETCH_TIMEOUT_MILLIS = 60 * 1000; // One minute
763
+ const DEFAULT_CACHE_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000; // Twelve hours.
764
+ /**
765
+ * Encapsulates business logic mapping network and storage dependencies to the public SDK API.
766
+ *
767
+ * See {@link https://github.com/firebase/firebase-js-sdk/blob/main/packages/firebase/index.d.ts|interface documentation} for method descriptions.
768
+ */
769
+ class RemoteConfig {
770
+ get fetchTimeMillis() {
771
+ return this._storageCache.getLastSuccessfulFetchTimestampMillis() || -1;
772
+ }
773
+ get lastFetchStatus() {
774
+ return this._storageCache.getLastFetchStatus() || 'no-fetch-yet';
775
+ }
776
+ constructor(
777
+ // Required by FirebaseServiceFactory interface.
778
+ app,
779
+ // JS doesn't support private yet
780
+ // (https://github.com/tc39/proposal-class-fields#private-fields), so we hint using an
781
+ // underscore prefix.
782
+ /**
783
+ * @internal
784
+ */
785
+ _client,
786
+ /**
787
+ * @internal
788
+ */
789
+ _storageCache,
790
+ /**
791
+ * @internal
792
+ */
793
+ _storage,
794
+ /**
795
+ * @internal
796
+ */
797
+ _logger) {
798
+ this.app = app;
799
+ this._client = _client;
800
+ this._storageCache = _storageCache;
801
+ this._storage = _storage;
802
+ this._logger = _logger;
803
+ /**
804
+ * Tracks completion of initialization promise.
805
+ * @internal
806
+ */
807
+ this._isInitializationComplete = false;
808
+ this.settings = {
809
+ fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS,
810
+ minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS
811
+ };
812
+ this.defaultConfig = {};
813
+ }
814
814
  }
815
815
 
816
- /**
817
- * @license
818
- * Copyright 2019 Google LLC
819
- *
820
- * Licensed under the Apache License, Version 2.0 (the "License");
821
- * you may not use this file except in compliance with the License.
822
- * You may obtain a copy of the License at
823
- *
824
- * http://www.apache.org/licenses/LICENSE-2.0
825
- *
826
- * Unless required by applicable law or agreed to in writing, software
827
- * distributed under the License is distributed on an "AS IS" BASIS,
828
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
829
- * See the License for the specific language governing permissions and
830
- * limitations under the License.
831
- */
832
- /**
833
- * Converts an error event associated with a {@link IDBRequest} to a {@link FirebaseError}.
834
- */
835
- function toFirebaseError(event, errorCode) {
836
- const originalError = event.target.error || undefined;
837
- return ERROR_FACTORY.create(errorCode, {
838
- originalErrorMessage: originalError && (originalError === null || originalError === void 0 ? void 0 : originalError.message)
839
- });
840
- }
841
- /**
842
- * A general-purpose store keyed by app + namespace + {@link
843
- * ProjectNamespaceKeyFieldValue}.
844
- *
845
- * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact
846
- * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys
847
- * for a set of key-value pairs. See {@link Storage#createCompositeKey}.
848
- *
849
- * <p>Visible for testing.
850
- */
851
- const APP_NAMESPACE_STORE = 'app_namespace_store';
852
- const DB_NAME = 'firebase_remote_config';
853
- const DB_VERSION = 1;
854
- // Visible for testing.
855
- function openDatabase() {
856
- return new Promise((resolve, reject) => {
857
- try {
858
- const request = indexedDB.open(DB_NAME, DB_VERSION);
859
- request.onerror = event => {
860
- reject(toFirebaseError(event, "storage-open" /* ErrorCode.STORAGE_OPEN */));
861
- };
862
- request.onsuccess = event => {
863
- resolve(event.target.result);
864
- };
865
- request.onupgradeneeded = event => {
866
- const db = event.target.result;
867
- // We don't use 'break' in this switch statement, the fall-through
868
- // behavior is what we want, because if there are multiple versions between
869
- // the old version and the current version, we want ALL the migrations
870
- // that correspond to those versions to run, not only the last one.
871
- // eslint-disable-next-line default-case
872
- switch (event.oldVersion) {
873
- case 0:
874
- db.createObjectStore(APP_NAMESPACE_STORE, {
875
- keyPath: 'compositeKey'
876
- });
877
- }
878
- };
879
- }
880
- catch (error) {
881
- reject(ERROR_FACTORY.create("storage-open" /* ErrorCode.STORAGE_OPEN */, {
882
- originalErrorMessage: error === null || error === void 0 ? void 0 : error.message
883
- }));
884
- }
885
- });
886
- }
887
- /**
888
- * Abstracts data persistence.
889
- */
890
- class Storage {
891
- /**
892
- * @param appId enables storage segmentation by app (ID + name).
893
- * @param appName enables storage segmentation by app (ID + name).
894
- * @param namespace enables storage segmentation by namespace.
895
- */
896
- constructor(appId, appName, namespace, openDbPromise = openDatabase()) {
897
- this.appId = appId;
898
- this.appName = appName;
899
- this.namespace = namespace;
900
- this.openDbPromise = openDbPromise;
901
- }
902
- getLastFetchStatus() {
903
- return this.get('last_fetch_status');
904
- }
905
- setLastFetchStatus(status) {
906
- return this.set('last_fetch_status', status);
907
- }
908
- // This is comparable to a cache entry timestamp. If we need to expire other data, we could
909
- // consider adding timestamp to all storage records and an optional max age arg to getters.
910
- getLastSuccessfulFetchTimestampMillis() {
911
- return this.get('last_successful_fetch_timestamp_millis');
912
- }
913
- setLastSuccessfulFetchTimestampMillis(timestamp) {
914
- return this.set('last_successful_fetch_timestamp_millis', timestamp);
915
- }
916
- getLastSuccessfulFetchResponse() {
917
- return this.get('last_successful_fetch_response');
918
- }
919
- setLastSuccessfulFetchResponse(response) {
920
- return this.set('last_successful_fetch_response', response);
921
- }
922
- getActiveConfig() {
923
- return this.get('active_config');
924
- }
925
- setActiveConfig(config) {
926
- return this.set('active_config', config);
927
- }
928
- getActiveConfigEtag() {
929
- return this.get('active_config_etag');
930
- }
931
- setActiveConfigEtag(etag) {
932
- return this.set('active_config_etag', etag);
933
- }
934
- getThrottleMetadata() {
935
- return this.get('throttle_metadata');
936
- }
937
- setThrottleMetadata(metadata) {
938
- return this.set('throttle_metadata', metadata);
939
- }
940
- deleteThrottleMetadata() {
941
- return this.delete('throttle_metadata');
942
- }
943
- async get(key) {
944
- const db = await this.openDbPromise;
945
- return new Promise((resolve, reject) => {
946
- const transaction = db.transaction([APP_NAMESPACE_STORE], 'readonly');
947
- const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
948
- const compositeKey = this.createCompositeKey(key);
949
- try {
950
- const request = objectStore.get(compositeKey);
951
- request.onerror = event => {
952
- reject(toFirebaseError(event, "storage-get" /* ErrorCode.STORAGE_GET */));
953
- };
954
- request.onsuccess = event => {
955
- const result = event.target.result;
956
- if (result) {
957
- resolve(result.value);
958
- }
959
- else {
960
- resolve(undefined);
961
- }
962
- };
963
- }
964
- catch (e) {
965
- reject(ERROR_FACTORY.create("storage-get" /* ErrorCode.STORAGE_GET */, {
966
- originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
967
- }));
968
- }
969
- });
970
- }
971
- async set(key, value) {
972
- const db = await this.openDbPromise;
973
- return new Promise((resolve, reject) => {
974
- const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');
975
- const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
976
- const compositeKey = this.createCompositeKey(key);
977
- try {
978
- const request = objectStore.put({
979
- compositeKey,
980
- value
981
- });
982
- request.onerror = (event) => {
983
- reject(toFirebaseError(event, "storage-set" /* ErrorCode.STORAGE_SET */));
984
- };
985
- request.onsuccess = () => {
986
- resolve();
987
- };
988
- }
989
- catch (e) {
990
- reject(ERROR_FACTORY.create("storage-set" /* ErrorCode.STORAGE_SET */, {
991
- originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
992
- }));
993
- }
994
- });
995
- }
996
- async delete(key) {
997
- const db = await this.openDbPromise;
998
- return new Promise((resolve, reject) => {
999
- const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');
1000
- const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
1001
- const compositeKey = this.createCompositeKey(key);
1002
- try {
1003
- const request = objectStore.delete(compositeKey);
1004
- request.onerror = (event) => {
1005
- reject(toFirebaseError(event, "storage-delete" /* ErrorCode.STORAGE_DELETE */));
1006
- };
1007
- request.onsuccess = () => {
1008
- resolve();
1009
- };
1010
- }
1011
- catch (e) {
1012
- reject(ERROR_FACTORY.create("storage-delete" /* ErrorCode.STORAGE_DELETE */, {
1013
- originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
1014
- }));
1015
- }
1016
- });
1017
- }
1018
- // Facilitates composite key functionality (which is unsupported in IE).
1019
- createCompositeKey(key) {
1020
- return [this.appId, this.appName, this.namespace, key].join();
1021
- }
816
+ /**
817
+ * @license
818
+ * Copyright 2019 Google LLC
819
+ *
820
+ * Licensed under the Apache License, Version 2.0 (the "License");
821
+ * you may not use this file except in compliance with the License.
822
+ * You may obtain a copy of the License at
823
+ *
824
+ * http://www.apache.org/licenses/LICENSE-2.0
825
+ *
826
+ * Unless required by applicable law or agreed to in writing, software
827
+ * distributed under the License is distributed on an "AS IS" BASIS,
828
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
829
+ * See the License for the specific language governing permissions and
830
+ * limitations under the License.
831
+ */
832
+ /**
833
+ * Converts an error event associated with a {@link IDBRequest} to a {@link FirebaseError}.
834
+ */
835
+ function toFirebaseError(event, errorCode) {
836
+ const originalError = event.target.error || undefined;
837
+ return ERROR_FACTORY.create(errorCode, {
838
+ originalErrorMessage: originalError && (originalError === null || originalError === void 0 ? void 0 : originalError.message)
839
+ });
840
+ }
841
+ /**
842
+ * A general-purpose store keyed by app + namespace + {@link
843
+ * ProjectNamespaceKeyFieldValue}.
844
+ *
845
+ * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact
846
+ * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys
847
+ * for a set of key-value pairs. See {@link Storage#createCompositeKey}.
848
+ *
849
+ * <p>Visible for testing.
850
+ */
851
+ const APP_NAMESPACE_STORE = 'app_namespace_store';
852
+ const DB_NAME = 'firebase_remote_config';
853
+ const DB_VERSION = 1;
854
+ // Visible for testing.
855
+ function openDatabase() {
856
+ return new Promise((resolve, reject) => {
857
+ try {
858
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
859
+ request.onerror = event => {
860
+ reject(toFirebaseError(event, "storage-open" /* ErrorCode.STORAGE_OPEN */));
861
+ };
862
+ request.onsuccess = event => {
863
+ resolve(event.target.result);
864
+ };
865
+ request.onupgradeneeded = event => {
866
+ const db = event.target.result;
867
+ // We don't use 'break' in this switch statement, the fall-through
868
+ // behavior is what we want, because if there are multiple versions between
869
+ // the old version and the current version, we want ALL the migrations
870
+ // that correspond to those versions to run, not only the last one.
871
+ // eslint-disable-next-line default-case
872
+ switch (event.oldVersion) {
873
+ case 0:
874
+ db.createObjectStore(APP_NAMESPACE_STORE, {
875
+ keyPath: 'compositeKey'
876
+ });
877
+ }
878
+ };
879
+ }
880
+ catch (error) {
881
+ reject(ERROR_FACTORY.create("storage-open" /* ErrorCode.STORAGE_OPEN */, {
882
+ originalErrorMessage: error === null || error === void 0 ? void 0 : error.message
883
+ }));
884
+ }
885
+ });
886
+ }
887
+ /**
888
+ * Abstracts data persistence.
889
+ */
890
+ class Storage {
891
+ /**
892
+ * @param appId enables storage segmentation by app (ID + name).
893
+ * @param appName enables storage segmentation by app (ID + name).
894
+ * @param namespace enables storage segmentation by namespace.
895
+ */
896
+ constructor(appId, appName, namespace, openDbPromise = openDatabase()) {
897
+ this.appId = appId;
898
+ this.appName = appName;
899
+ this.namespace = namespace;
900
+ this.openDbPromise = openDbPromise;
901
+ }
902
+ getLastFetchStatus() {
903
+ return this.get('last_fetch_status');
904
+ }
905
+ setLastFetchStatus(status) {
906
+ return this.set('last_fetch_status', status);
907
+ }
908
+ // This is comparable to a cache entry timestamp. If we need to expire other data, we could
909
+ // consider adding timestamp to all storage records and an optional max age arg to getters.
910
+ getLastSuccessfulFetchTimestampMillis() {
911
+ return this.get('last_successful_fetch_timestamp_millis');
912
+ }
913
+ setLastSuccessfulFetchTimestampMillis(timestamp) {
914
+ return this.set('last_successful_fetch_timestamp_millis', timestamp);
915
+ }
916
+ getLastSuccessfulFetchResponse() {
917
+ return this.get('last_successful_fetch_response');
918
+ }
919
+ setLastSuccessfulFetchResponse(response) {
920
+ return this.set('last_successful_fetch_response', response);
921
+ }
922
+ getActiveConfig() {
923
+ return this.get('active_config');
924
+ }
925
+ setActiveConfig(config) {
926
+ return this.set('active_config', config);
927
+ }
928
+ getActiveConfigEtag() {
929
+ return this.get('active_config_etag');
930
+ }
931
+ setActiveConfigEtag(etag) {
932
+ return this.set('active_config_etag', etag);
933
+ }
934
+ getThrottleMetadata() {
935
+ return this.get('throttle_metadata');
936
+ }
937
+ setThrottleMetadata(metadata) {
938
+ return this.set('throttle_metadata', metadata);
939
+ }
940
+ deleteThrottleMetadata() {
941
+ return this.delete('throttle_metadata');
942
+ }
943
+ async get(key) {
944
+ const db = await this.openDbPromise;
945
+ return new Promise((resolve, reject) => {
946
+ const transaction = db.transaction([APP_NAMESPACE_STORE], 'readonly');
947
+ const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
948
+ const compositeKey = this.createCompositeKey(key);
949
+ try {
950
+ const request = objectStore.get(compositeKey);
951
+ request.onerror = event => {
952
+ reject(toFirebaseError(event, "storage-get" /* ErrorCode.STORAGE_GET */));
953
+ };
954
+ request.onsuccess = event => {
955
+ const result = event.target.result;
956
+ if (result) {
957
+ resolve(result.value);
958
+ }
959
+ else {
960
+ resolve(undefined);
961
+ }
962
+ };
963
+ }
964
+ catch (e) {
965
+ reject(ERROR_FACTORY.create("storage-get" /* ErrorCode.STORAGE_GET */, {
966
+ originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
967
+ }));
968
+ }
969
+ });
970
+ }
971
+ async set(key, value) {
972
+ const db = await this.openDbPromise;
973
+ return new Promise((resolve, reject) => {
974
+ const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');
975
+ const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
976
+ const compositeKey = this.createCompositeKey(key);
977
+ try {
978
+ const request = objectStore.put({
979
+ compositeKey,
980
+ value
981
+ });
982
+ request.onerror = (event) => {
983
+ reject(toFirebaseError(event, "storage-set" /* ErrorCode.STORAGE_SET */));
984
+ };
985
+ request.onsuccess = () => {
986
+ resolve();
987
+ };
988
+ }
989
+ catch (e) {
990
+ reject(ERROR_FACTORY.create("storage-set" /* ErrorCode.STORAGE_SET */, {
991
+ originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
992
+ }));
993
+ }
994
+ });
995
+ }
996
+ async delete(key) {
997
+ const db = await this.openDbPromise;
998
+ return new Promise((resolve, reject) => {
999
+ const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');
1000
+ const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
1001
+ const compositeKey = this.createCompositeKey(key);
1002
+ try {
1003
+ const request = objectStore.delete(compositeKey);
1004
+ request.onerror = (event) => {
1005
+ reject(toFirebaseError(event, "storage-delete" /* ErrorCode.STORAGE_DELETE */));
1006
+ };
1007
+ request.onsuccess = () => {
1008
+ resolve();
1009
+ };
1010
+ }
1011
+ catch (e) {
1012
+ reject(ERROR_FACTORY.create("storage-delete" /* ErrorCode.STORAGE_DELETE */, {
1013
+ originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
1014
+ }));
1015
+ }
1016
+ });
1017
+ }
1018
+ // Facilitates composite key functionality (which is unsupported in IE).
1019
+ createCompositeKey(key) {
1020
+ return [this.appId, this.appName, this.namespace, key].join();
1021
+ }
1022
1022
  }
1023
1023
 
1024
- /**
1025
- * @license
1026
- * Copyright 2019 Google LLC
1027
- *
1028
- * Licensed under the Apache License, Version 2.0 (the "License");
1029
- * you may not use this file except in compliance with the License.
1030
- * You may obtain a copy of the License at
1031
- *
1032
- * http://www.apache.org/licenses/LICENSE-2.0
1033
- *
1034
- * Unless required by applicable law or agreed to in writing, software
1035
- * distributed under the License is distributed on an "AS IS" BASIS,
1036
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1037
- * See the License for the specific language governing permissions and
1038
- * limitations under the License.
1039
- */
1040
- /**
1041
- * A memory cache layer over storage to support the SDK's synchronous read requirements.
1042
- */
1043
- class StorageCache {
1044
- constructor(storage) {
1045
- this.storage = storage;
1046
- }
1047
- /**
1048
- * Memory-only getters
1049
- */
1050
- getLastFetchStatus() {
1051
- return this.lastFetchStatus;
1052
- }
1053
- getLastSuccessfulFetchTimestampMillis() {
1054
- return this.lastSuccessfulFetchTimestampMillis;
1055
- }
1056
- getActiveConfig() {
1057
- return this.activeConfig;
1058
- }
1059
- /**
1060
- * Read-ahead getter
1061
- */
1062
- async loadFromStorage() {
1063
- const lastFetchStatusPromise = this.storage.getLastFetchStatus();
1064
- const lastSuccessfulFetchTimestampMillisPromise = this.storage.getLastSuccessfulFetchTimestampMillis();
1065
- const activeConfigPromise = this.storage.getActiveConfig();
1066
- // Note:
1067
- // 1. we consistently check for undefined to avoid clobbering defined values
1068
- // in memory
1069
- // 2. we defer awaiting to improve readability, as opposed to destructuring
1070
- // a Promise.all result, for example
1071
- const lastFetchStatus = await lastFetchStatusPromise;
1072
- if (lastFetchStatus) {
1073
- this.lastFetchStatus = lastFetchStatus;
1074
- }
1075
- const lastSuccessfulFetchTimestampMillis = await lastSuccessfulFetchTimestampMillisPromise;
1076
- if (lastSuccessfulFetchTimestampMillis) {
1077
- this.lastSuccessfulFetchTimestampMillis =
1078
- lastSuccessfulFetchTimestampMillis;
1079
- }
1080
- const activeConfig = await activeConfigPromise;
1081
- if (activeConfig) {
1082
- this.activeConfig = activeConfig;
1083
- }
1084
- }
1085
- /**
1086
- * Write-through setters
1087
- */
1088
- setLastFetchStatus(status) {
1089
- this.lastFetchStatus = status;
1090
- return this.storage.setLastFetchStatus(status);
1091
- }
1092
- setLastSuccessfulFetchTimestampMillis(timestampMillis) {
1093
- this.lastSuccessfulFetchTimestampMillis = timestampMillis;
1094
- return this.storage.setLastSuccessfulFetchTimestampMillis(timestampMillis);
1095
- }
1096
- setActiveConfig(activeConfig) {
1097
- this.activeConfig = activeConfig;
1098
- return this.storage.setActiveConfig(activeConfig);
1099
- }
1024
+ /**
1025
+ * @license
1026
+ * Copyright 2019 Google LLC
1027
+ *
1028
+ * Licensed under the Apache License, Version 2.0 (the "License");
1029
+ * you may not use this file except in compliance with the License.
1030
+ * You may obtain a copy of the License at
1031
+ *
1032
+ * http://www.apache.org/licenses/LICENSE-2.0
1033
+ *
1034
+ * Unless required by applicable law or agreed to in writing, software
1035
+ * distributed under the License is distributed on an "AS IS" BASIS,
1036
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1037
+ * See the License for the specific language governing permissions and
1038
+ * limitations under the License.
1039
+ */
1040
+ /**
1041
+ * A memory cache layer over storage to support the SDK's synchronous read requirements.
1042
+ */
1043
+ class StorageCache {
1044
+ constructor(storage) {
1045
+ this.storage = storage;
1046
+ }
1047
+ /**
1048
+ * Memory-only getters
1049
+ */
1050
+ getLastFetchStatus() {
1051
+ return this.lastFetchStatus;
1052
+ }
1053
+ getLastSuccessfulFetchTimestampMillis() {
1054
+ return this.lastSuccessfulFetchTimestampMillis;
1055
+ }
1056
+ getActiveConfig() {
1057
+ return this.activeConfig;
1058
+ }
1059
+ /**
1060
+ * Read-ahead getter
1061
+ */
1062
+ async loadFromStorage() {
1063
+ const lastFetchStatusPromise = this.storage.getLastFetchStatus();
1064
+ const lastSuccessfulFetchTimestampMillisPromise = this.storage.getLastSuccessfulFetchTimestampMillis();
1065
+ const activeConfigPromise = this.storage.getActiveConfig();
1066
+ // Note:
1067
+ // 1. we consistently check for undefined to avoid clobbering defined values
1068
+ // in memory
1069
+ // 2. we defer awaiting to improve readability, as opposed to destructuring
1070
+ // a Promise.all result, for example
1071
+ const lastFetchStatus = await lastFetchStatusPromise;
1072
+ if (lastFetchStatus) {
1073
+ this.lastFetchStatus = lastFetchStatus;
1074
+ }
1075
+ const lastSuccessfulFetchTimestampMillis = await lastSuccessfulFetchTimestampMillisPromise;
1076
+ if (lastSuccessfulFetchTimestampMillis) {
1077
+ this.lastSuccessfulFetchTimestampMillis =
1078
+ lastSuccessfulFetchTimestampMillis;
1079
+ }
1080
+ const activeConfig = await activeConfigPromise;
1081
+ if (activeConfig) {
1082
+ this.activeConfig = activeConfig;
1083
+ }
1084
+ }
1085
+ /**
1086
+ * Write-through setters
1087
+ */
1088
+ setLastFetchStatus(status) {
1089
+ this.lastFetchStatus = status;
1090
+ return this.storage.setLastFetchStatus(status);
1091
+ }
1092
+ setLastSuccessfulFetchTimestampMillis(timestampMillis) {
1093
+ this.lastSuccessfulFetchTimestampMillis = timestampMillis;
1094
+ return this.storage.setLastSuccessfulFetchTimestampMillis(timestampMillis);
1095
+ }
1096
+ setActiveConfig(activeConfig) {
1097
+ this.activeConfig = activeConfig;
1098
+ return this.storage.setActiveConfig(activeConfig);
1099
+ }
1100
1100
  }
1101
1101
 
1102
- /**
1103
- * @license
1104
- * Copyright 2020 Google LLC
1105
- *
1106
- * Licensed under the Apache License, Version 2.0 (the "License");
1107
- * you may not use this file except in compliance with the License.
1108
- * You may obtain a copy of the License at
1109
- *
1110
- * http://www.apache.org/licenses/LICENSE-2.0
1111
- *
1112
- * Unless required by applicable law or agreed to in writing, software
1113
- * distributed under the License is distributed on an "AS IS" BASIS,
1114
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1115
- * See the License for the specific language governing permissions and
1116
- * limitations under the License.
1117
- */
1118
- function registerRemoteConfig() {
1119
- app._registerComponent(new component.Component(RC_COMPONENT_NAME, remoteConfigFactory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
1120
- app.registerVersion(name, version);
1121
- // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
1122
- app.registerVersion(name, version, 'cjs2017');
1123
- function remoteConfigFactory(container, { instanceIdentifier: namespace }) {
1124
- /* Dependencies */
1125
- // getImmediate for FirebaseApp will always succeed
1126
- const app$1 = container.getProvider('app').getImmediate();
1127
- // The following call will always succeed because rc has `import '@firebase/installations'`
1128
- const installations = container
1129
- .getProvider('installations-internal')
1130
- .getImmediate();
1131
- // Guards against the SDK being used in non-browser environments.
1132
- if (typeof window === 'undefined') {
1133
- throw ERROR_FACTORY.create("registration-window" /* ErrorCode.REGISTRATION_WINDOW */);
1134
- }
1135
- // Guards against the SDK being used when indexedDB is not available.
1136
- if (!util.isIndexedDBAvailable()) {
1137
- throw ERROR_FACTORY.create("indexed-db-unavailable" /* ErrorCode.INDEXED_DB_UNAVAILABLE */);
1138
- }
1139
- // Normalizes optional inputs.
1140
- const { projectId, apiKey, appId } = app$1.options;
1141
- if (!projectId) {
1142
- throw ERROR_FACTORY.create("registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */);
1143
- }
1144
- if (!apiKey) {
1145
- throw ERROR_FACTORY.create("registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */);
1146
- }
1147
- if (!appId) {
1148
- throw ERROR_FACTORY.create("registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */);
1149
- }
1150
- namespace = namespace || 'firebase';
1151
- const storage = new Storage(appId, app$1.name, namespace);
1152
- const storageCache = new StorageCache(storage);
1153
- const logger$1 = new logger.Logger(name);
1154
- // Sets ERROR as the default log level.
1155
- // See RemoteConfig#setLogLevel for corresponding normalization to ERROR log level.
1156
- logger$1.logLevel = logger.LogLevel.ERROR;
1157
- const restClient = new RestClient(installations,
1158
- // Uses the JS SDK version, by which the RC package version can be deduced, if necessary.
1159
- app.SDK_VERSION, namespace, projectId, apiKey, appId);
1160
- const retryingClient = new RetryingClient(restClient, storage);
1161
- const cachingClient = new CachingClient(retryingClient, storage, storageCache, logger$1);
1162
- const remoteConfigInstance = new RemoteConfig(app$1, cachingClient, storageCache, storage, logger$1);
1163
- // Starts warming cache.
1164
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
1165
- ensureInitialized(remoteConfigInstance);
1166
- return remoteConfigInstance;
1167
- }
1102
+ /**
1103
+ * @license
1104
+ * Copyright 2020 Google LLC
1105
+ *
1106
+ * Licensed under the Apache License, Version 2.0 (the "License");
1107
+ * you may not use this file except in compliance with the License.
1108
+ * You may obtain a copy of the License at
1109
+ *
1110
+ * http://www.apache.org/licenses/LICENSE-2.0
1111
+ *
1112
+ * Unless required by applicable law or agreed to in writing, software
1113
+ * distributed under the License is distributed on an "AS IS" BASIS,
1114
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1115
+ * See the License for the specific language governing permissions and
1116
+ * limitations under the License.
1117
+ */
1118
+ function registerRemoteConfig() {
1119
+ app._registerComponent(new component.Component(RC_COMPONENT_NAME, remoteConfigFactory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
1120
+ app.registerVersion(name, version);
1121
+ // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
1122
+ app.registerVersion(name, version, 'cjs2017');
1123
+ function remoteConfigFactory(container, { instanceIdentifier: namespace }) {
1124
+ /* Dependencies */
1125
+ // getImmediate for FirebaseApp will always succeed
1126
+ const app$1 = container.getProvider('app').getImmediate();
1127
+ // The following call will always succeed because rc has `import '@firebase/installations'`
1128
+ const installations = container
1129
+ .getProvider('installations-internal')
1130
+ .getImmediate();
1131
+ // Guards against the SDK being used in non-browser environments.
1132
+ if (typeof window === 'undefined') {
1133
+ throw ERROR_FACTORY.create("registration-window" /* ErrorCode.REGISTRATION_WINDOW */);
1134
+ }
1135
+ // Guards against the SDK being used when indexedDB is not available.
1136
+ if (!util.isIndexedDBAvailable()) {
1137
+ throw ERROR_FACTORY.create("indexed-db-unavailable" /* ErrorCode.INDEXED_DB_UNAVAILABLE */);
1138
+ }
1139
+ // Normalizes optional inputs.
1140
+ const { projectId, apiKey, appId } = app$1.options;
1141
+ if (!projectId) {
1142
+ throw ERROR_FACTORY.create("registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */);
1143
+ }
1144
+ if (!apiKey) {
1145
+ throw ERROR_FACTORY.create("registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */);
1146
+ }
1147
+ if (!appId) {
1148
+ throw ERROR_FACTORY.create("registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */);
1149
+ }
1150
+ namespace = namespace || 'firebase';
1151
+ const storage = new Storage(appId, app$1.name, namespace);
1152
+ const storageCache = new StorageCache(storage);
1153
+ const logger$1 = new logger.Logger(name);
1154
+ // Sets ERROR as the default log level.
1155
+ // See RemoteConfig#setLogLevel for corresponding normalization to ERROR log level.
1156
+ logger$1.logLevel = logger.LogLevel.ERROR;
1157
+ const restClient = new RestClient(installations,
1158
+ // Uses the JS SDK version, by which the RC package version can be deduced, if necessary.
1159
+ app.SDK_VERSION, namespace, projectId, apiKey, appId);
1160
+ const retryingClient = new RetryingClient(restClient, storage);
1161
+ const cachingClient = new CachingClient(retryingClient, storage, storageCache, logger$1);
1162
+ const remoteConfigInstance = new RemoteConfig(app$1, cachingClient, storageCache, storage, logger$1);
1163
+ // Starts warming cache.
1164
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
1165
+ ensureInitialized(remoteConfigInstance);
1166
+ return remoteConfigInstance;
1167
+ }
1168
1168
  }
1169
1169
 
1170
- /**
1171
- * @license
1172
- * Copyright 2020 Google LLC
1173
- *
1174
- * Licensed under the Apache License, Version 2.0 (the "License");
1175
- * you may not use this file except in compliance with the License.
1176
- * You may obtain a copy of the License at
1177
- *
1178
- * http://www.apache.org/licenses/LICENSE-2.0
1179
- *
1180
- * Unless required by applicable law or agreed to in writing, software
1181
- * distributed under the License is distributed on an "AS IS" BASIS,
1182
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1183
- * See the License for the specific language governing permissions and
1184
- * limitations under the License.
1185
- */
1186
- // This API is put in a separate file, so we can stub fetchConfig and activate in tests.
1187
- // It's not possible to stub standalone functions from the same module.
1188
- /**
1189
- *
1190
- * Performs fetch and activate operations, as a convenience.
1191
- *
1192
- * @param remoteConfig - The {@link RemoteConfig} instance.
1193
- *
1194
- * @returns A `Promise` which resolves to true if the current call activated the fetched configs.
1195
- * If the fetched configs were already activated, the `Promise` will resolve to false.
1196
- *
1197
- * @public
1198
- */
1199
- async function fetchAndActivate(remoteConfig) {
1200
- remoteConfig = util.getModularInstance(remoteConfig);
1201
- await fetchConfig(remoteConfig);
1202
- return activate(remoteConfig);
1203
- }
1204
- /**
1205
- * This method provides two different checks:
1206
- *
1207
- * 1. Check if IndexedDB exists in the browser environment.
1208
- * 2. Check if the current browser context allows IndexedDB `open()` calls.
1209
- *
1210
- * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance
1211
- * can be initialized in this environment, or false if it cannot.
1212
- * @public
1213
- */
1214
- async function isSupported() {
1215
- if (!util.isIndexedDBAvailable()) {
1216
- return false;
1217
- }
1218
- try {
1219
- const isDBOpenable = await util.validateIndexedDBOpenable();
1220
- return isDBOpenable;
1221
- }
1222
- catch (error) {
1223
- return false;
1224
- }
1170
+ /**
1171
+ * @license
1172
+ * Copyright 2020 Google LLC
1173
+ *
1174
+ * Licensed under the Apache License, Version 2.0 (the "License");
1175
+ * you may not use this file except in compliance with the License.
1176
+ * You may obtain a copy of the License at
1177
+ *
1178
+ * http://www.apache.org/licenses/LICENSE-2.0
1179
+ *
1180
+ * Unless required by applicable law or agreed to in writing, software
1181
+ * distributed under the License is distributed on an "AS IS" BASIS,
1182
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1183
+ * See the License for the specific language governing permissions and
1184
+ * limitations under the License.
1185
+ */
1186
+ // This API is put in a separate file, so we can stub fetchConfig and activate in tests.
1187
+ // It's not possible to stub standalone functions from the same module.
1188
+ /**
1189
+ *
1190
+ * Performs fetch and activate operations, as a convenience.
1191
+ *
1192
+ * @param remoteConfig - The {@link RemoteConfig} instance.
1193
+ *
1194
+ * @returns A `Promise` which resolves to true if the current call activated the fetched configs.
1195
+ * If the fetched configs were already activated, the `Promise` will resolve to false.
1196
+ *
1197
+ * @public
1198
+ */
1199
+ async function fetchAndActivate(remoteConfig) {
1200
+ remoteConfig = util.getModularInstance(remoteConfig);
1201
+ await fetchConfig(remoteConfig);
1202
+ return activate(remoteConfig);
1203
+ }
1204
+ /**
1205
+ * This method provides two different checks:
1206
+ *
1207
+ * 1. Check if IndexedDB exists in the browser environment.
1208
+ * 2. Check if the current browser context allows IndexedDB `open()` calls.
1209
+ *
1210
+ * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance
1211
+ * can be initialized in this environment, or false if it cannot.
1212
+ * @public
1213
+ */
1214
+ async function isSupported() {
1215
+ if (!util.isIndexedDBAvailable()) {
1216
+ return false;
1217
+ }
1218
+ try {
1219
+ const isDBOpenable = await util.validateIndexedDBOpenable();
1220
+ return isDBOpenable;
1221
+ }
1222
+ catch (error) {
1223
+ return false;
1224
+ }
1225
1225
  }
1226
1226
 
1227
- /**
1228
- * The Firebase Remote Config Web SDK.
1229
- * This SDK does not work in a Node.js environment.
1230
- *
1231
- * @packageDocumentation
1232
- */
1233
- /** register component and version */
1227
+ /**
1228
+ * The Firebase Remote Config Web SDK.
1229
+ * This SDK does not work in a Node.js environment.
1230
+ *
1231
+ * @packageDocumentation
1232
+ */
1233
+ /** register component and version */
1234
1234
  registerRemoteConfig();
1235
1235
 
1236
1236
  exports.activate = activate;